【问题标题】:Pre-fill fields in a form with data from a ForeignKey class使用 ForeignKey 类中的数据预填充表单中的字段
【发布时间】:2012-12-13 14:00:11
【问题描述】:

我有一个

class SurveyAnswer(models.Model):
    rel = models.ForeignKey(Survey)
    answer = models.CharField(max_length=150)
    def __unicode__(self):
        return self.answer

现在我想用这个“答案”预先填写表格:

survey = get_object_or_404(Survey, created_by=request.user, pk=question_id)
form_data = {"question": survey.question, "answer1":survey.surveyanswer_set.get(xxx)}
form = SurveyForm(form_data)

我与 xxx 有什么关系,以便我得到例如与“调查”(外键)相关的第一个答案。使用 pk=1 我得到绝对数。

更新:

我已经完成了

{% for i in survey.surveyanswer_set.all %}
    <p><label>Answer {{ forloop.counter }}:</label> <textarea id="id_answer{{ forloop.counter }}" rows="6" placeholder="Type an answer option" cols="45" name="answer{{ forloop.counter }}">{{ i.answer }}</textarea></p>
{% endfor %}

如果有人知道如何在视图中做得更好,请给我一个提示。

更新 2:

这在视图中更好一些(但我认为必须有一个更简单的解决方案):

answers_part1 = []
for i in survey.surveyanswer_set.all():
    answers_part1.extend([i.answer])
answers_part2 = ["answer1", "answer2", "answer3", "answer4"]
answers = dict(zip(answers_part2, answers_part1))
form_data = {"question": survey.question}
form_data.update(answers)
form = SurveyForm(form_data)

【问题讨论】:

    标签: django django-forms django-views


    【解决方案1】:

    根据您的需要,有两种方法可以做到这一点:

    https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

    或者,如果您的表单是 ModelForm,您可以使用实例参数:

    https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多