我有一个
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)
答案 0 :(得分:5)
根据您的需要,有两种方法可以做到这一点:
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
或者,如果您的表单是ModelForm,则可以使用实例参数:
https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/