简体   繁体   中英

Django ModelChoiceField, validation for dynamic queryset

I have this current form:

class PersonForm(forms.Form):                                                                                           
    article = forms.CharField(required=False)
    workshop = forms.ModelChoiceField(queryset=Program.objects.none(),
                                      empty_label="----",
                                      required=False,
                                      label='Atelier')

    def __init__(self, *args, **kwargs):                                                                                    
        super(PersonForm, self).__init__(*args, **kwargs)
        article = self.initial.get('article', None)
        if article:
            a = Article.objects.get(pk=article)
            if a.workshop:
                self.fields['workshop'].queryset = Program.objects.filter(event=a.event, workshop=True)
                self.fields['workshop'].required = True
                self.helper.layout.insert(4, Row1Field('workshop',))

The queryset used to retrieve all the workshops is dynamic, so the queryset attribute inside the ModelChoiceField is set to Program.objects.none() , and the dynamic queryset is done inside the form's __init__ method

Everything is working fine: all the values displayed for workshop inside the select are ok. But when I post the form, there is a validation error: 'Select a valid choice. This choice is not among available choices.' 'Select a valid choice. This choice is not among available choices.'

Is there something I'm missing?

Depending on the code that is instantiating the form upon post, initial may not be passed. You could try:

article = self.initial.get('article', None) or self.data.get('article', None)

This will get the pk from your form POST data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM