3

我有一个

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 有什么关系,这样我才能得到例如与“调查”(ForeignKey)相关的第一个答案。使用 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)
4

1 回答 1

5

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

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

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

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

于 2012-12-13T15:31:17.133 回答