Я следил за документацией django и создавал простое приложение для опроса. Я наткнулся на следующее сообщение об ошибке:Страница не найдена (404) Метод запроса: t GET URL-адрес запроса: t http://127.0.0.1:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
MySite/MySite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
MySite/опросы/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/опросы/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
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):
return render(request, 'polls/details.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,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
Эта ссылка http://127.0.0.1:8000/polls/ показывает пустую страницу с 3 пуль. (У меня есть 3 вопроса в моей базе данных, а их идентификаторы - 5,6,7, потому что я удаляю и добавляю вопросы.)
Мой администратор отлично работает!
Я новичок в Django и искал и спрашивал, и на какое-то время застрял на нем.
Теперь, когда вы разместили свой шаблон, я вижу, что у вас есть опечатка. Это должно быть 'question.question_text', а не' question.question_test'. – Alasdair
Спасибо, сэр @Alasdair за ваше драгоценное время. Я не знал, что ошибка была в этом файле. –
Это новая ошибка, которую я получаю, когда я нажимаю на голосование после выбора! Исключение Тип: \t TypeError Exception Значение: \t голос() получил неожиданный аргумент ключевое слово 'рк' Exception Расположение: \t /usr/local/lib/python3.4/dist-packages/django/core/handlers/base. py в get_response, строка 147 –