How can I deal with this django Page not found error (404)

I am building this django app using a tutorial and I am up to part 4 https://docs.djangoproject.com/en/dev/intro/tutorial04/

The app displays the main poll and when you click on it, it displays some options and a button to vote. enter image description here

The problem is when I click on the vote. The page display was not found. I think the problem is with the redirect, but I don't know where to point the problem. The first page contains index.html, which displays the questions, and then detail.html, which displays the selection and question. I know when I click on the vote it goes back to the app url and urlconf does the view function and the view function does the results.

My detail.html

 <h1>{{ poll.question }}</h1>

 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

 <form action="/myapp/{{ poll.id }}/vote/" method="post">
 {% csrf_token %}
 {% for choice in poll.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>

      

My urls.py inside myapp:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings

from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
    url(r'^$', 'index'),
    url(r'^(?P<poll_id>\d+)/$', 'detail'),
    url(r'^(?P<poll_id>\d+)/results/$', 'results'),
    url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)

      

My views.py:

from django.http import HttpResponse
from myapp.models import Poll ,choice
from django.template import Context, loader
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('myapp/index.html', {'latest_poll_list': latest_poll_list})

def results(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('myapp/results.html', {'poll': p})

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('myapp/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    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('myapp.views.results', args=(p.id,)))

def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('myapp/detail.html', {'poll': p},
                           context_instance=RequestContext(request))

      

My .html results:

<h1>{{ poll.question }}</h1>

<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="/myapp/{{ poll.id }}/">Vote again?</a>

      

Thanks for helping me. This will be my first breakthrough app if I can get it to work.

My main url:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/', include('myapp.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

      

enter image description here

+3


source to share


2 answers


Unlock the myapp bit of the form action.

It should be

<form action="polls/{{poll.id}}/vote" method="post">

      

This matches the regex in urls.py file -

url(r'^polls/', include('myapp.urls')),

      

and then in myapp.urls -



url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),

      

Function include

means django is trying to match^polls/(?P<poll_id>\d+)/vote/$

If you look at the error page you are getting, you can see the URL that django is trying to match (none of them contain "myapp", it should be a poll).

IMPORTANT

As you continue through the tutorial, you will see that your templates should not be hardcoded (as jpic rightly points out). At this point, you need to change the action of the form to {% url 'polls:vote' poll.id %}

.

+2


source


Don't print URLs

You should not print the url anywhere - just like for file system paths. Not only are you killing the kittens, you are also making your code less robust!

Reverse urls instaed!

Read the backlinks for starters and using named URLs for the main dish and {% url%} templatetag for the dessert.

During digestion, you will be the master of the Django url system))



Read the tutorial

In the tutorial you linked, they don't url encode:

{% url 'polls:vote' poll.id %}

      

This is the way !!!

Make sure you don't have a hardcoded url in your templates and your problem will go away.

+6


source







All Articles