Django formsets: make first required?

前端 未结 4 454
独厮守ぢ
独厮守ぢ 2020-11-28 04:05

These formsets are exhibiting exactly the opposite behavior that I want.

My view is set up like this:

def post(request): # TODO: handle vehi         


        
相关标签:
4条回答
  • 2020-11-28 04:39

    Well... this makes the first form required.

    class RequiredFormSet(BaseFormSet):
        def clean(self):
            if any(self.errors):
                return
            if not self.forms[0].has_changed():
                raise forms.ValidationError('Please add at least one vehicle.') 
    

    Only "problem" is that if there are 0 forms, then the clean method doesn't seem to get called at all, so I don't know how to check if there are 0. Really...this should never happen though (except that my JS has a bug in it, allowing you to remove all the forms).

    0 讨论(0)
  • 2020-11-28 04:41

    Found a better solution:

    class RequiredFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(RequiredFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False
    

    Then create your formset like this:

    MyFormSet = formset_factory(MyForm, formset=RequiredFormSet)
    

    I really don't know why this wasn't an option to begin with... but, whatever. It only took a few hours of my life to figure out.

    This will make all the forms required. You could make just the first one required by setting self.forms[0].empty_permitted to False.

    0 讨论(0)
  • 2020-11-28 04:43

    Oh I think I see. Try this:

    from django.forms.formsets import BaseFormSet, formset_factory
    class OneExtraRequiredFormSet(BaseFormSet):
        def initial_form_count(self):
            return max(super(OneExtraRequiredFormSet,self).initial_form_count() - 1,0)
    
    VehicleFormSetFactory = formset_factory(VehicleForm, formset=OneExtraRequiredFormSet, extra=1)
    

    == Original answer below ==

    When you say "at least make one form required", I assume you mean "make only one extra form required, regardless of how many have been added via javascript".

    You will need to have hidden input on your page which contains the number of forms that have been added via javascript, and then use that number, minus 1, as the value to pass in as the extra attribute to your formsets constructor.

    0 讨论(0)
  • 2020-11-28 04:54

    New in Django 1.7: you can specify this behaviour with your formset_factory

    https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#validate-min

    VehicleFormSetFactory = formset_factory(VehicleForm, min_num=1, validate_min=True, extra=1)
    
    0 讨论(0)
提交回复
热议问题