网址:
re_path(r'^detail/(?P<slug>\w+)/$', ProblemDetail.as_view(), name='problem_detail'),
查看:
class ProblemDetail(View):
template_name='problem/problem_detail.html'
form_class=AnswerForm
def get(self,request,slug):
context={'problem':Problem.objects.get(slug=slug),'form':self.form_class()}
return render(request,self.template_name,context)
def post(self,request,slug):
bound_form=self.form_class(request.POST)
obj=Problem.objects.get(slug=slug)
real_answer=obj.answer
if bound_form.is_valid():
if bound_form.cleaned_data['answer'] == real_answer:
return render(request,
'problem/Answerstatus.html',
{'message':'Good Job !'})
else:
return render(request,
'problem/Answerstatus.html',
{'message':'Wrong ! Try Again !'})
模板:
{% extends "problem/base_problem.html" %}
{% block content%}
<h2>{{problem.p_name}}</h2>
<h3>{{problem.difficulty}}</h3>
<p>{{problem.p_description}}</p>
<form action= "{% url 'problem_detail' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" > Check </button>
</form>
{% endblock %}
上面的模板是一个粗略的测试想法(它不是最终模板,需要大量更改,我们知道。)
我收到以下错误:
Reverse for 'problem_detail' with no arguments not found. 1 pattern(s) tried: ['detail/(?P<slug>\\w+)/$']
答案 0 :(得分:1)
在post方法中返回时,应添加slug参数。尝试返回HttpResponseRedirect并将其与args列表中的slug一起返回到您的网址。
return HttpResponseRedirect(reverse('problem_detail', args=[slug]))
答案 1 :(得分:1)
问题似乎出在您的{% url %}
的{{1}}标签中,但是我们不确定,因为您没有在问题中包含该模板。
例如,每次渲染模板时,似乎都需要在模板中包括问题。
problem/Answerstatus.html
,然后在模板中,将子弹包含在return render(request, 'problem/Answerstatus.html', {'problem': obj, 'message':'Good Job !'})
标记中:
{% url %}
答案 2 :(得分:0)
像这样在模型中添加get_absolute_url方法:
def get_absolute_url(self):
return reverse('problem_detail',kwargs={'slug':self.slug})
也在您的模板中:
{% block body-block %}
<h2>{{problem.p_name}}</h2>
<h5>{{problem.difficulty}}</h5>
<p>{{problem.p_description}}</p>
<form action= "{{ problem.get_absolute_url }}" method="post"> # Pay Attention here
{% csrf_token %}
{{ form.as_p }}
<button type="submit" > Check </button>
</form>
{% endblock %}
这将获取url,而正则表达式将匹配。