我目前正在查看Django documentaion,用于使用post方法(https://docs.djangoproject.com/en/2.1/intro/tutorial04/)创建表单。但是,我在遇到CSRF verification failed. Request aborted
错误时
在views.py
vote()
函数
正在使用的文件是:
views.py:
from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import Question
.
.
.
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk =
request.POST['choice'])
except (KeyError, choice.DoesNotExitst):
return render(request, 'polls/detail.html',{
'question': question,
'error_message': "you didn't select a choice"
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=
(question.id)))
detail.html:
<h1>{{ question.question_text }}</h1>
{%if error_message%}<p><strong>{{error_message}}</strong></p>{%endif%}
<form action="{%url 'polls:vote' question.id%}" method="post">
{% csrf_token %}
{%for choice in question.choice_set.all%}
<input type = "radio" name = "choice" id="choice{{ forloop.counter
}}" value = "{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{choice.choice_text}}
</label><br>
{%endfor%}
<input type="submit" value="vote">
</form>
results.html:
<h1>{{ question.question_text }}</h1>
<ul>
{%for choice in question.choice_set.all%}
<li>{{choice.choice_text}} -- {{choice.votes}}
vote{{choice.votes|pluralize}}</li>
{&endfor&}
</ul>
<a href="{%url 'polls:detail question.id'%}">Vote again?</a>
这些是使用的MIDDLEWARE:
`MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
urls.py:
.
.
.
app_name = 'polls'
urlpatterns = [
path('', views.index, name = 'index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
但我收到此错误: