开发者

Django Model Formset Only first form required

In a modelformset with 3 copies 开发者_运维问答of the form, how do i specify that only the first set is required but the rest can be blank or null?


I've used something like this for inline formsets:

class BaseSomethingFormset(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseSomethingFormset, self).__init__(*args, **kwargs)
        self.forms[0].empty_permitted = False
        self.forms[0].required = True

The form fields must be by default set to required=False


Matthew Flanagan has a package of things for Django, and in that package is the RequireOneFormset class. You can easily extend this class to require 3 forms instead of one.

Hope that helps you out.


You can subclass BaseModelFormSet so it modifies the first form and makes it required:

from django.forms.models import BaseModelFormSet

class OneRequiredFormSet(BaseModelFormSet):
    def _construct_form(self, i, **kwargs):
        f = super(OneRequiredFormSet, self)._construct_form(i, **kwargs)
        if i == 0:
            f.empty_permitted = False
            f.required = True
        return f

Then you can use the formset keyword argument to tell modelformset_factory to use your new class:

from django.forms.models import modelformset_factory

ParticipantFormSet = modelformset_factory(Participant, extra=1,
                                          form=ParticipantForm,
                                          formset=OneRequiredFormSet)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜