Model Formset - by default the formet model is one additional field (2 fields in total)

My model form, which doesn't even define "additional" parameters in modelformset_factory, is one additional field in the template. I tried many options but it didn't work. If I print the form (model form) on the command line, it just prints one form field as needed, but on the sample model it prints 2 by default.

Here is my code.

models.py

class Direction(models.Model):
    text = models.TextField(blank=True, verbose_name='Direction|text')

      

forms.py

class DirectionForm(forms.ModelForm):
    class Meta:
        model = Direction
        fields = ['text',]

      

views.py

def myview(request):
    Dirset = modelformset_factory(Direction, form=DirectionForm)
    if request.method == "POST":
        dir_formset = Dirset(request.POST or None)
        if dir_formset.is_valid():
        for direction in dir_formset:
            text = direction.cleaned_data.get('text')
            Direction.objects.create(text=text)
return render(request, "test/test.html", {'DirFormSet':Dirset})     

      

template

{% block content %}
<form method="POST">{% csrf_token %}
<div id="forms">
    {{DirFormSet.management_form}}
    {% for form in DirFormSet %}
        {{form.text}}
        {% if error in form.text.errors %}
            {{error|escape}
        {% endif %}
    {% endfor %}
</div>
<button id="add-another">add another</button>

<input type="submit" />
</form>

{% endblock %}

      

As a side note, if I submit data to this form, it gives the following error. Mistake

Exception Type: MultiValueDictKeyError
Exception Value:"u'form-0-id'"

      

+3


source to share


1 answer


modelformset_factory

Creates one additional form by default . If you don't want any additional forms, install extra=0

.

Dirset = modelformset_factory(Direction, form=DirectionForm, extra=0)

      

KeyError

is that you have not included the field template in the form id

. You should have something like:

{% for form in dir_formset %}
    {{ form.id }}
    {{ form.text }}
    ...
{% endfor %}

      



Note that when rendering the template, not the class, DirFormSet

you should pass in an instance of the form dir_formset

. Your opinion should look something like this:

return render(request, "test/test.html", {'dir_formset': dir_formset})     

      

then the template must be updated to use dir_formset

instead DirFormSet

.

+3


source







All Articles