Home > Blockchain >  Catch decimal.ConversionSyntax django import export
Catch decimal.ConversionSyntax django import export

Time:10-29

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:

enter image description here

What I wanted to display was the error along with all other errors here:

enter image description here

Thanks in advance!

CodePudding user response:

There are a couple of ways you can solve this.

  1. For DecimalWidget declare it as CharWidget - this will handle any input string and if you have clean_model_instances enabled, then the error will be raised when the model object is validated.

  2. For ForeignKeyWidget, you will have to override the clean() method so that it raises a ValueError for a non-existent reference. IMO this isn't ideal because it is breaking the contract for the clean() 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

enter image description here

  • Related