Django Http404 message not showing up - python

I am currently on Django documentation part 3 where I have to create the polls app. However, when I make a request to the url having path like http://127.0.0.1:8000/polls/3/, I was supposed to get the message 'Question does not exist.' But I don't.
Here is my code
polls/views.py
from django.http import HttpResponse, HttpResponseNotFound, Http404
from django.shortcuts import render
from .models import Question
# Create your views here.
def index(request):
# - sign to get more recent, list is ordered from 0 to 4
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:
return HttpResponseNotFound("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
The error is
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/3/
Raised by: polls.views.detail
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
polls/ <int:question_id>/ [name='detail']
The current path, polls/3/, matched the last one.

Try changing raise Http404("Question does not exist") to return HttpResponseNotFound("Question does not exist")
You can set debug=false , provide a message to Http404 and then it will appear in the standard 404 debug template. Find more details here.

Related

NoReverseMatch at /blog/redirect2

I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match
this is my urls.py code :
app_name = 'blog'
urlpatterns = [
# path('about', views.about, name = 'about'),
path('about.html', views.about, name='about'),
path('home.html', views.home, name='home'),
# path('home', views.home, name ="home")
path('redirect', views.redirect_view),
path('redirection_fct',views.redirection_fct, name='redir_fct'),
#redirection par la fonction as_view
path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')),
path('redirect2', views.redirect_view1),
]
and this is my views file :
def about(request):
return render(request, 'about.html', {})
def home(request):
return render(request, 'home.html', {})
#redirection par HttpResponseRedirect
def redirect_view(request):
return HttpResponseRedirect("redirection_fct")
def redirect_view1(request):
return redirect('redir_fct')
def redirection_fct(request):
return render(request, 'redirection.html', {})
Is there something wrong with my URLs pattern or it is the render one?
Is this the urls.py on your app? How do you include it on your project urls.py, if you have a namespace for it, then you probably need something like:
def redirect_view1(request):
return redirect('blog:redir_fct')
You can try running from a django shell:
from django.urls import get_resolver
print(get_resolver().reverse_dict.keys())

Unable to get django declared app routes working as pages

I am creating an Django app and am facing issues with routes not being identified. It is the same DJango poll app I am trying to create but the documentation code does not work. Here is my code below:
djangoproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^simpleapp/', include('simpleapp.urls')),
url(r'^admin/', admin.site.urls),
]
simpleapp/views.py
from django.shortcuts import render
from django.http import HttpResponse, request
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
simpleapp/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /simpleapp/
# url('', views.index, name='index'),
# ex: /simpleapp/5/
url('<int:question_id>/', views.detail, name='detail'),
# ex: /simpleapp/5/results/
url('<int:question_id>/results/', views.results, name='results'),
# ex: /simpleapp/5/vote/
url('<int:question_id>/vote/', views.vote, name='vote'),
]
If I un-comment the first url of '' path of simpleapp/urls.py code, all the pages shown are '' path. However, if I keep the url '' path commented, then the routes give me the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/simpleapp/34/
Using the URLconf defined in simple_django.urls, Django tried these URL patterns, in this order:
^simpleapp/ <int:question_id>/ [name='detail']
^simpleapp/ <int:question_id>/results/ [name='results']
^simpleapp/ <int:question_id>/vote/ [name='vote']
^admin/
The current path, simpleapp/34/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I was unable to get the path() imported using django.conf.urls or django.urls. url() was successful. I am using python version 3.6.7 and Django version 2.1.5. What am I missing?
You are using path syntax, not regexes, in your simpleapp/urls.py. Change it to:
urlpatterns = [
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'),
]
Your project URLs are using regexes, so you shouldn't change those, although you might want to make them consistent.
You define routes like Django 1.x
url(r'^simpleapp/', include('simpleapp.urls')),
url(r'^admin/', admin.site.urls),
This is Django 1.x type route definition
In Django 2 you must define routes like this:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
In Django 2 routes define without regular expression
See docs for route define in Django 2

Adding paths in Django to create more views

I am following the tutorial on the Django website. I try and replicate this:
My code is as follows:
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, film_id):
return HttpResponse("You're looking at film %s." % film_id)
def results(request, film_id):
response = "You're looking at the results of film %s."
return HttpResponse(response % question_id)
def vote(request, film_id):
return HttpResponse("You're commenting on film %s." % film_id)
films/urls.py
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
# url(r'^$', views.index, name='index'),
# ex: /polls/
path('', views.index, name='index'),
# ex: /films/5/
path('<int:film_id>/', views.detail, name='detail'),
# ex: /films/5/results/
path('<int:film_id>/results/', views.results, name='results'),
# ex: /films/5/vote/
path('<int:film_id>/vote/', views.vote, name='vote'),
]
With this I am getting ERR_CONNECTION_REFUSED. If I comment out all the paths leaving only the index url, and also comment out from django.urls import path a page displays, but that is where I was at before trying to add more views.
You are referring to the documentation for newer Django version as path() did not exist in older versions. You can select the documentation version by clicking on the Documentation version button at the bottom right here.

Django first app

I have some problems with my first django app (its name is magghy). I'm at the start of development. So, I have:
magghy/urls.py:
from django.conf.urls import *
from magghy import views
from . import views
app_name = 'magghy'
urlpatterns = [
# esempio: /magghy/
url(r'^$', views.index, name='index'),
#esempio: /magghy/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /magghy/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /magghy/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
In magghy/views.py:
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Choice, Question
from django.template import loader
from django.urls import reverse
#visualizzare domande e argomento specifico - collegare con modulo magghy.urls
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
#visualizzare pagina html secondo schema index.html oppure html 404 (eccezione)
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('magghy/index.html')
context = RequestContext (request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
#visualizzare pagina 404
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})
In mysite/urls.py:
from django.conf.urls import *
from django.contrib import admin
from magghy import views
urlpatterns = [
url(r'^magghy/', views.detail),
url(r'^admin/', include (admin.site.urls)),
]
The page http://127.0.0.1:8000/admin/ works perfectly!
The page http://127.0.0.1:8000/magghy/ doesn't work
The page http://127.0.0.1:8000/magghy/5 doesn't work
In both case the terminal logs are:
Internal Server Error: /magghy/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: detail() takes exactly 2 arguments (1 given)
Please, can you help me? Thanks a lot!
Adri
mysite/urls.py is linking directly to the detail view, rather than including the app URLs. It should be:
urlpatterns = [
url(r'^magghy/', include('magghy.urls')),
url(r'^admin/', include (admin.site.urls)),
]

Django couldn't find urlpath

I tried to go 127.0.0.1:8000/poll/ it doesn't open, but I can go to /poll/20/result.
I just add other urls of poll and base url-> /poll/ stop to be opened.
Before I add to detail,result,vote function/url there were no problem to open index of poll.
Here are my codes:
In view.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, World. You are at the poll index.")
def detail(request, poll_id):
return HttpResponse("You are looking at poll %s" %poll_id)
def results(request, poll_id):
return HttpResponse("You are looing at the results of poll %s" % poll_id)
def vote(request, poll_id):
return HttpResponse("You are voting on poll %s" %poll_id)
In Polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns( '',
url(r'^Ş', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<poll_id>\d+)/results/$', views.results,name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
In mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'sign_ups.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
In your MySite.urls,
you have mentioned the polls url as polls and given the url as poll.
Change any one of those to get the app working.

Categories