所以我试图关注django docs- https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/#using-formmixin-with-detailview
基本上我正在使用django进行stackoverflow克隆。 人们可以提出问题,可以用答案回答
现在我可以使它工作,如果我提供一个链接,将他们带到一个单独的页面提交他们的答案。但那很糟糕。我希望答案表格在问题页面上
基于我来到此代码的文档
urls.py -
url(r'^view/(?P<pk>\d+)/$',views.QuestionDetail.as_view(),name='detail'),
views.py -
class QuestionDetail(View):
def get(self, request, *args, **kwargs):
view = QuestionDisplay.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = Answer.as_view()
return view(request, *args, **kwargs)
(我相信)应该为一个帖子请求呈现一个视图,为获取请求呈现另一个视图
class QuestionDisplay(generic.DetailView):
model = Question
template_name = 'questions/question_detail.html'
def get_context_data(self, **kwargs):
context = super(QuestionDisplay, self).get_context_data(**kwargs)
context['form'] = AnswerForm()
return context
^这部分工作正常
class Answer(SingleObjectMixin, FormView):
template_name = 'questions/question_detail.html'
form_class = AnswerForm
model = Answer
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
return super(Answer, self).post(request, *args, **kwargs)
def get_success_url(self):
return reverse('questions:detail', kwargs={'pk': self.object.pk})
^问题(我认为)当我尝试在页面上提供的表单中提交答案时,我得到404页面找不到错误。具体
找不到页面(404) 请求方法:POST 请求网址:http://127.0.0.1:8000/questions/view/8/ 提出者:questions.views.QuestionDetail
编辑使其有效 -
class QuestionDetail(View):
def get(self, request, *args, **kwargs):
view = QuestionDisplay.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
pk = kwargs['pk']
view = add_answer_to_question(request, pk)
return redirect('questions:detail', pk=kwargs['pk'])
def add_answer_to_question(request, pk):
question = get_object_or_404(Question, pk=pk)
if request.method == "POST":
form = AnswerForm(request.POST)
if form.is_valid():
answer = form.save(commit=False)
answer.question = question
answer.user_id = request.user.id
answer.save()
return redirect('questions:detail', pk=question.pk)
else:
form = AnswerForm()
return render(request, 'answers/_answer_form.html', {'form': form})
答案 0 :(得分:0)
如果您使用ModelForm
,则可以尝试此操作,错误与方法get_success_url
有关。
from django.core.urlresolvers import reverse_lazy
def get_success_url(self):
return reverse_lazy('questions:detail', kwargs={'pk': self.instance.pk})
,您必须在urls.py中设置app_name='questions'
。