【问题标题】:Dynamically add form fields based on query results根据查询结果动态添加表单字段
【发布时间】:2014-07-29 01:36:45
【问题描述】:

我有一个模型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>

如果我在Form.__init__ 中设置它们后运行logger.debug(self.fields['questionnaire']),我明白了:

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

【问题讨论】:

  • 你能给我们看看你的显示器吗?
  • @m170897017 抱歉,不确定您的意思,我已经添加了渲染输出和一些调试输出,以防您指的是什么。谢谢:)

标签: python django forms django-1.6


【解决方案1】:

在你的视野中试试这个

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

使用我们在参数中传递的额外字段来初始化我们的表单

formsets:对于您的情况,您可以定义另一个表单问题:

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 简单表单和问题是动态添加问题字段的表单集)您可以查看formsets

【讨论】:

  • 谢谢,您的回答类似于我刚刚找到的jacobian.org/writing/dynamic-form-generation。问题是我在模板的不同区域中专门输出了其他字段。有没有办法专门选择符合字段名称question_%s的字段并在模板中循环遍历它们?
  • 谢谢,用了你的方法,然后在模板里{% for field in form %}{% if "id_question_" in field.auto_id %}...{% endif %}{% endfor %}帮我只选了我需要的字段。
  • 很高兴它成功了,我在论坛中找到了另一个解决方案,您可以尝试 formset,如果您愿意,它会更灵活
  • 是的,拜托,我对表单集太无知了!
  • formsets 是 django 中很棒的功能,可以在功能方面为您提供很大帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多