Opened 3 years ago

Last modified 3 years ago

#33399 closed Uncategorized

Overriding Choices for a field in the Form not working when using ModelForm | Django 3.2 — at Version 2

Reported by: Swaroop P Owned by: nobody
Component: Forms Version: 3.0
Severity: Normal Keywords: modelform
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Swaroop P)

Hi All

Facing the following issue after migrating to 3.2.

Example:

class SomeModel(models.Model):
       field1 = models.CharField(choices=[])

class SomeModelForm(forms.ModelForm):

     __init__(*args, **kwargs):
         super().__init__(*args **kwargs)
         self.fields['field1'].choices = <some choices dynamically generated>

    class Meta:
         model = SomeModel
         fields = [ 'field1' ]

In the above case any choice selected is shown with the error "not a valid choice" this is happening because model fields is revalidated again in modelform._post_clean() function.

Intermediate solution is to remove choices from modelfield and reinitalize field in form init wiht dynamic choices. But In previous versions We had choices to only override some attributes of a field rather than reinitalizing whole field.

Thanks

Change History (2)

comment:1 by Swaroop P, 3 years ago

Description: modified (diff)

comment:2 by Swaroop P, 3 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top