Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Tutorial: 'detail' is not a valid view function or pattern name

Tags:

python

django

I am using Windows XP, Python 3.4 and Django 2.0.2

I am new to Django and am trying to follow the instructions in

https://docs.djangoproject.com/en/2.0/intro/tutorial04/

the Django tutorial. The most likely mistake that I made is that I did not cut and paste code in the right places. It would be helpful to me (and possibly others) if the writers of the tutorial had a reference to the complete list of the py and html files at each stage (not just part of the code).

I have the following error:

http://127.0.0.1:8000/polls/

` NoReverseMatch at /polls/
Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Django Version: 2.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.
Exception Location: C:\programs\python34\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632
Python Executable: C:\programs\python34\python.exe
Python Version: 3.4.3
Python Path:
['Y:\mysite\mysite',
'C:\WINDOWS\system32\python34.zip',
'C:\programs\python34\DLLs',
'C:\programs\python34\lib',
'C:\programs\python34',
'C:\programs\python34\lib\site-packages']
Server time: Thu, 6 Dec 2018 15:35:56 -0600
Error during template rendering

In template Y:\mysite\mysite\polls\templates\polls\index.html, error at line 4
Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.

1   {% if latest_question_list %}
2       <ul>
3       {% for question in latest_question_list %}
4           <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
5       {% endfor %}
6       </ul>
7   {% else %}
8       <p>No polls are available.</p>
9   {% endif %}

`

The end of the error stream read

    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail'
is not a valid view function or pattern name.
[06/Dec/2018 15:35:57] "GET /polls/ HTTP/1.1" 500 127035
Not Found: /favicon.ico
[06/Dec/2018 15:35:58] "GET /favicon.ico HTTP/1.1" 404 2078


Following the tutorial, I have the following files:

Y:\mysite\mysite\polls\models.py

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text


Y:\mysite\mysite\polls\urls.py

from django.urls import path

from . import views
app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]


Y:\mysite\mysite\polls\views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question
from django.views import generic

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.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
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)
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    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 HttpResponseRedirect 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,))


Y:\mysite\mysite\polls\templates\polls\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>


Y:\mysite\mysite\polls\templates\polls\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 %}
`  


Y:\mysite\mysite\polls\templates\polls\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>


CAN ANYONE TELL ME WHAT I AM DOING WRONG?

All my HTML and PY files were cut and pasted from the Django Tutorial. If someone suggests a change in either an HTML of PY file, it would be very helpful if that person list the complete modified files (not just the changes).
Thanks!!

like image 371
Bob Avatar asked Dec 08 '18 03:12

Bob


1 Answers

instead of

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

Use

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

Because the polls app's urls are included in urlpatterns in the urls.py(which resides ins same folder as settings.py) with name polls like this:

urlpatterns = [
    ...
    path('', include('polls.url', name='polls')
]
like image 141
ruddra Avatar answered Sep 24 '22 15:09

ruddra