クエリ結果に基づいて動的にフォームフィールドを追加します
-
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 Simple Formと質問は、動的に質問フィールドを動的に追加するための採用値です)寓話
所属していません StackOverflow