模型表单集-默认情况下,模型表单集会渲染一个额外的字段(总共2个字段) [英] Model Formset - By Default model formset is rendering one extra field (2 fields in total)

查看:72
本文介绍了模型表单集-默认情况下,模型表单集会渲染一个额外的字段(总共2个字段)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型表单集甚至没有在modelformset_factory中定义额外参数,正在模板中渲染一个额外的字段。我尝试了许多变体,但没有用。如果我在命令行上打印表单(模型表单),则仅打印所需的单个表单字段,但在模型表单集上,默认情况下将打印2。

My model formset without even defining "extra" parameters in modelformset_factory is rendering one extra field in the template. I have tried many variations but it didn't work. If I print the form (the model form) on the command line it just prints a single form field as required but on model formset it prints 2 by default.

这是我的代码。

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})     

模板

{% 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 on this form it gives the following error. Error

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


推荐答案

默认情况下,< a href = https://docs.djangoproject.com/zh-CN/1.8/ref/forms/models/#django.forms.models.modelformset_factory rel = nofollow> modelformset_factory 创建一个额外的表单。如果您不希望使用任何其他形式,请设置 extra = 0

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

The KeyError 是因为您没有在模板中包含表单的 id 字段。您应该具有以下内容:

The KeyError is because you have not included the form's id field in your template. You should have something like:

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

请注意,渲染模板时,您应该传递表单集实例 dir_formset ,而不是类 DirFormSet 。您的视图应类似于

Note that you should be passing the formset instance dir_formset when rendering the template, not the class DirFormSet. Your view should be something like

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

然后应将模板更新为使用 dir_formset 而不是 DirFormSet

then the template should be updated to use dir_formset instead of DirFormSet.

这篇关于模型表单集-默认情况下,模型表单集会渲染一个额外的字段(总共2个字段)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆