I need to be able to display the error regarding invalid decimals and invalid foreign keys into a much more user-friendly way.
I thought the clean_model_instances = True
would catch it but it did not.
Invalid decimal error:
Invalid foreign key error:
What I wanted to display was the error along with all other errors here:
Thanks in advance!
CodePudding user response:
There are a couple of ways you can solve this.
For
DecimalWidget
declare it asCharWidget
- this will handle any input string and if you haveclean_model_instances
enabled, then the error will be raised when the model object is validated.For
ForeignKeyWidget
, you will have to override theclean()
method so that it raises aValueError
for a non-existent reference. IMO this isn't ideal because it is breaking the contract for theclean()
function. The error message isn't perfect, but it does achieve what you want.
class ValidatingForeignKeyWidget(widgets.ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
try:
val = super().clean(value)
except self.model.DoesNotExist:
raise ValueError(f"{self.model.__name__} with value={value} does not exist")
return val
class BookResource(ModelResource):
price = fields.Field(attribute='price', widget=widgets.CharWidget())
author = fields.Field(attribute="author", widget=ValidatingForeignKeyWidget(Author))
class Meta:
model = Book
clean_model_instances = True