Я проверяю django впервые после урока [https://docs.djangoproject.com/en/2.0/intro/tutorial03/]
Когда я изменяю жестко заданный URL с:
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
на:
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
Я получаю сообщение об ошибке:
Мои файлы urls.py:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
# ex:/polls/5/
path('<int:question_id>/', views.detail, name='datail'),
# ex: /polls/5/results/
path('<int:question_id>/vote/', views.vote, name='vote'),
# ex: /polls/vote/
path('<int:question_id>/results/', views.results, name='results'),
]
Мои файлы views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question,Choice
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question':question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question':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.DoesNotExist):
# Redisplay the question voting form
return render(request, 'polls/detail.html',{
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes +=1
selected_choice.save()
# Always return an HttpRespinsedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list':latest_question_list}
return render(request, 'polls/index.html', context)
Мои файлы index.html:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'detail' question_id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Мои файлы details.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>
Итак, я запутался в Удаление жестко закодированных URL-адресов вшаблоны не работает.Может ли кто-нибудь помочь мне?Большое спасибо!