无法通过表单POST子对象包含对其父对象的外键引用

时间:2013-11-29 22:28:18

标签: django django-forms

请参阅下面的支持信息。我正在尝试使用Django创建一个简单的Q& A演示。我试图在我的answer_question_form发布的答案中包含父问题pk作为外键。我可以通过url将问题pk传递给我的表单视图(url是/ qa / answer / [qid]其中qid是正在回答的问题的pk),但是视图帖子失败,并且找不到“/ qa”的url / answer /“我怀疑是因为我不知道在帖子请求中不包含问题pk而我的观点是试图发布到/ qa / answer / xxx?

models.py

class Question(models.Model):
    question = models.CharField(max_length=200)
    post_date = models.DateTimeField(default=datetime.now())

class Answer(models.Model):
    question = models.ForeignKey(Question)
    answer = models.CharField(max_length=200)
    post_date = models.DateTimeField(default=datetime.now())

views.py

def answer_question(request, qid):
    if request.method == 'POST': 
         form = AnswerForm(request.POST) 
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/qa/')
    else:
        form = AnswerForm(initial={'question': qid}) # Pass parent question id

    return render(request, 'qa/answer_question_form.html', {'form': form,}) 

forms.py

class AnswerForm(ModelForm):
    class Meta:
    model = Answer
    fields = ['question','answer']

urls.py

url(r'^$',               views.index,           name='index'),
url(r'^answers/(\d+)/$', views.answers,         name='answers'),
url(r'^ask/$',           views.ask_question,    name='ask'),
url(r'^answer/(\d+)/$',  views.answer_question, name='answer'),

表单模板

<form action="/qa/answer/" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Post your Question" />
</form>

0 个答案:

没有答案