Dynamic model choice field in django formset using multiple select elements

后端 未结 2 1454
梦如初夏
梦如初夏 2020-12-21 16:54

I posted this question on the django-users list, but haven\'t had a reply there yet.

I have models that look something like this:

class ProductGroup(         


        
2条回答
  •  生来不讨喜
    2020-12-21 17:47

    One way of setting field choices of a form in a formset is in the form's __init__ method by overwriting the self.fields['field_name'].choices, but since a more dynamic approach is desired, here is what works in a view:

    from django.forms.models import modelformset_factory
    user_choices = [(1, 'something'), (2, 'something_else')]  # some basic choices
    PurchaserChoiceFormSet = modelformset_factory(PurchaserChoice, form=PurchaserChoiceForm, extra=5, max_num=5)
    my_formset = PurchaserChoiceFormSet(self.request.POST or None, queryset=worksheet_choices)
    
    # and now for the magical for loop
    for choice_form in my_formset:
        choice_form.fields['model'].choices = user_choices
    

    I wasn't able to find the answer for this but tried it out and it works in Django 1.6.5. I figured it out since formsets and for loops seem to go so well together :)

提交回复
热议问题