Search code examples
djangodjango-import-export

Change value of field if input is not in choices Django ImportExportModelAdmin


I have this model field as an example:

compliance_approve_status = models.CharField(max_length=200, blank=True, null=True, default=None, choices=review_status_choices)

with these choices:

for_review = 'FOR REVIEW'
approved = 'APPROVED'
rejected = 'REJECTED'
review_status_choices = [(for_review, 'FOR REVIEW'), (approved, 'APPROVED'), (rejected, 'REJECTED')]

A simplified version of fields with choices.

I want to be able to make a default value in which if a user imports from a file and puts something other than a 'FOR REVIEW', 'APPROVED' or 'REJECTED', or is NULL, it would default to None. I thought adding a default=None would do it, but it accepts other values in Django's ImportExportModelAdmin.

enter image description here

enter image description here

enter image description here


Solution

  • Something like this should work (not tested):

    class ComplianceStatusWidget(widgets.CharWidget):
        def clean(self, value, row=None, *args, **kwargs):
            if value:
                for status, text in models.YourModel.review_status_choices:
                    if value.strip().lower() == text.lower():
                        return text
            return None
    

    Some improvements to this:

    1. Consider using a widget in your HTML to avoid duplication.

    2. Consider passing the choices into the widget using constructor for better separation of logic. This would help you to reuse the widget in other contexts.

    3. The code above is case-insensitive which might not be what you want.