简体   繁体   中英

Django Formset in generic FormView

Hi i used formsets in generic FormView like this:

class RequestRecommendationView(FormView):
    template_name = "account/stepfour.html"
    form_class = formset_factory(StepFourForm)

    def form_valid(self,form):
        print form.is_valid()
        cleaned_data = form.cleaned_data
        # return redirect(reverse("some_url_name"))

form for formset_factory is like this:

class StepFourForm(forms.Form):
    contact_person = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    company = forms.CharField(required=True)
    request_message = forms.CharField(required=True)

my html structure is like this:

<div style="padding-top:100px;padding-left:10px;">
    <h4> Request a Recommendation </h4>
    <form method="post" action="">
            {% csrf_token %}

            <table id="myForm">
                <tbody>
                {% for f in form %}
                    {% for field in f %}
                        <tr>
                            <td>{{field.label_tag}}</td>
                            <td>{{field}}</td>

                            {% for error in field.errors %}
                            <td><span>{{ error }}</span></td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                {% endfor %}
                </tbody>
            </table>

            <button class="btn btn-primary btn-xlarge" type="submit" name="submit">Request Now</button>
            {{ form.management_form }}
        </form>
</div>

Then i used django-dynamic-formset ( https://code.google.com/p/django-dynamic-formset/ ) to add/remove extra forms through these:

<script type="text/javascript">
    $(function() {
               $('#myForm tbody').formset();
           })
</script>

the problem is: if i leave the form empty,(every field is required), it manages to get to form_valid() of my class-view (though it should not), if i fill one of the fields (leaving others unfilled), it displays the errors associated message successfully. why is this happening ? what should i do to fix it ? is providing form_class a formset is behind all of this ?

This question has been asked 6 years ago, I found it because i faced the same issue, since it is unanswered, I'll provide the solution i found. according to the documentation to validate a minimum of forms, you have to provide a min_num and set validate_min=True in the formset_factory:

formset = formset_factory(your_form, min_num=2, validate_min=True, extra=2)

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