Django:如何使用formset extra更改标签?

2024-05-23 21:35:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用formset生成额外字段,但是我不知道如何更改formset生成的额外字段的标签。在

我的代码:

class GetMachine(forms.Form):
    Number_of_Lines = forms.IntegerField(max_value=4)

class GetLine(forms.Form):
    beamline_name = forms.CharField(max_length=15, label='Name of Beamline-%i')

def install(request):
    MachineFormSet = formset_factory(GetMachine, extra=1)
    formset = MachineFormSet()
    if request.method == 'POST':
#        formset = MachineFormSet(request.POST) 
#        if formset.is_valid(): # All validation rules pass
        line_no = request.POST['form-0-Number_of_Lines']
        GetLineFormSet = formset_factory(GetLine, extra=int(line_no))
        formset = GetLineFormSet()
        return render_to_response('install.html', { 'formset': formset, 'action': 'step1'})
    return render_to_response('install.html', { 'formset': formset, })    

在安装.html模板:

^{pr2}$

例如,如果“行数”=2,那么我期望下一个带有标签的表单

Name of Beamline-1:
Name of Beamline-2:

Tags: installofnameformnumberrequesthtmlforms
2条回答

假设您希望第一个表单的结果确定第二个表单的字段数及其标签,您可能需要查看Django form wizards。但是这里有一个简单的、非表单向导(而且可能不太理想/不易维护)的方法,使用formset的__init__方法来修改表单标签*:


在表单.py公司名称:

# File: forms.py
from django import forms
from django.forms.formsets import BaseFormSet


# What you've called 'GetMachine'
class MachineForm(forms.Form):
    no_of_lines = forms.IntegerField(max_value=4)


# What you've called 'GetLine'
class LineForm(forms.Form):
    beamline_name = forms.CharField(max_length=15, label='Name of Beamline')


# Create a custom formset and override __init__
class BaseLineFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseLineFormSet, self).__init__(*args, **kwargs)
        no_of_forms = len(self)
        for i in range(0, no_of_forms):
            self[i].fields['beamline_name'].label += "-%d" % (i + 1)

在视图.py公司名称:

^{2}$

在网址.py公司名称:

from django.conf.urls import url, patterns
from views import get_no_of_lines, line_form


urlpatterns = patterns('',
     url(r'^$', get_no_of_lines, name='get_no_of_lines'),
     url(r'^line_form/(?P<no_of_lines>\d{1})$', line_form, name='line_form'),
)

得到_行.html公司名称:

<form method="POST">
{% csrf_token %}
{{ machine_form }}
</form>

线路_表单.html公司名称:

<form method="POST">
{% csrf_token %}
{{ formset.as_p }}

我之所以说这种方法可能不是最好的方法,是因为您必须验证传递给line_form视图的no_of_lines(可能是>;4,因此您必须在这里执行验证并引入验证逻辑,而不是将其放在一个地方—表单)。如果您需要在第一个表单中添加一个新字段,那么您可能最终不得不修改代码。因此,我建议研究form wizards。在


我认为,完成此行为的唯一方法是在将窗体集传递到模板之前调整视图中的窗体集。在

您可以迭代不同的表单和标签,并相应地更改它们的值。在

另一个可能的解决方案是将默认标签设置为“束线名称-”。 在你的模板中做一些类似的事情

{% for field in form %}
    <td>{{ field.label_tag }}{{ forloop.counter1 }}</td> 
{% endfor %}

相关问题 更多 >