根据查询结果动态添加表单字段
-
20-12-2019 - |
题
我有一个模型 Question
其中包含问题列表。对于查询该表的结果,我想创建一个 CharField。这是我最初的尝试,没有出现错误,但没有显示任何内容:
def __init__(self, **kwargs):
super(QuestionnaireForm, self).__init__(**kwargs)
self.fields['questionnaire'] = dict()
questions = Question.objects.all()
for question in questions:
self.fields['questionnaire']['question' + str(question.pk)] = forms.CharField(widget=forms.TextInput(attrs=dict(placeholder=_("Answer"))), label=_(question))
在我的模板中我正在尝试:
<div class="questionnaire">
<h2>{% trans "Questionnaire" %}</h2>
{% if form.questionnaire %}
{% for question in form.questionnaire %}
<div class="row">
{% include "core/includes/field.html" with field=question %}
</div>
{% endfor %}
{% endif %}
</div>
在我的渲染输出中,我只看到:
<div class="questionnaire">
<h2>Questionnaire</h2>
</div>
如果我跑 logger.debug(self.fields['questionnaire'])
将它们设置后 Form.__init__
我懂了:
DEBUG {'question1': <django.forms.fields.CharField object at 0x7ff76473d550>, 'question3': <django.forms.fields.CharField object at 0x7ff76473d990>, 'question2': <django.forms.fields.CharField object at 0x7ff76473d890>}
解决方案
在你看来尝试这个
def myview(request):
questions = Question.objects.all()
if request.method == 'POST':
form = MyForm(request.POST, extra=questions)
if form.is_valid():
pass
else:
form = MyForm(extra=questions)
return render(request, "template", { 'form': form})
在 forms.py 中
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(LoginForm, self).__init__(*args, **kwargs)
for question in extra:
self.fields['question_%s' % extra.id] = forms.CharField(widget=forms.TextInput())
使用我们在参数中传递的额外字段来初始化我们的表单
表单集:对于您的情况,您可以定义另一个表单问题:
class QuestionForm(forms.Form):
question = forms.CharField()
看法:
def myview(request):
questions_rows = Question.objects.all().count()
QuestionFormSet = formset_factory(QuestionForm,extra=questions_rows)
if request.method == 'POST':
myform = LoginForm(request.POST,prefix='myform')
questions = QuestionFormSet(request.POST,prefix='question')
if myform.is_valid() and questions.is_valid():
pass
else:
myform = LoginForm(prefix='myform')
questions = QuestionFormSet(prefix='question')
return render(request, "template", { 'myform': myform,'questions':questions})
您可以看到我们使用多种表单(myform 简单表单和问题是动态添加问题字段的表单集)您可以检查 形式集
不隶属于 StackOverflow