Django: Page not found (404) - python

So I'm going through the Django tutorial, using version 1.8
When I go to the page that should display the index, which is at
http://127.0.0.1:8000/
I get a 404 error which says
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in forumtest.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these.
These are my urls pages.
forumtest/urls.py :
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
I'm also creating an app called polls with it's own urls.py
polls/urls.py :
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
This is my views page :
polls/views.py :
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Choice,Question
# Create your views here.
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 vote(request,question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except(KeyError,Choice.DoesNotExist):
#redisplay the question voting form
return render(request,'polls/detail.html',{
'question':p,
'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=(p.id,)))
I have no idea how to fix an issue like this, so if anyone can help that would be great.
Thanks.

The error message shows you what is wrong. You have defined urls under /polls/, so that is the address you should go to.

Related

Can't render template, getting page not found (404) Django

I can't seem to find the error, site works fine but when I request http://127.0.0.1:8000/test I get the 404 error, I feel so stupid I'm really stuck on this, please help:(
Error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/test
Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
login [name='login']
logout [name='logout']
register [name='register']
posts-json/ [name='posts-view-json']
^network/static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, test, 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.
This is my urls
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
from .views import post_view_json, profile_test_view
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("test/", profile_test_view, name="test"),
# endpoints
path("posts-json/", post_view_json, name="posts-view-json")
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It's a social website and I'm trying to render the posts and user's profiles on a page.
My views
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.core import serializers
from .models import User, Post, Profile
def index(request):
qs = Post.objects.all()
context = {
'hello': 'hello world!',
'qs':qs,
}
return render(request, "network/index.html", context)
def post_view_json(request):
qs = Post.objects.all()
data = serializers.serialize('json', qs)
return JsonResponse({'data': data})
def profile_test_view(request):
profile = Profile.objects.get(user=request.user)
return render(request, "network/profile_test.html", {'profile':profile})
You have a trailing slash in urls.py but not in the URL you are calling.
Either change urls.py like this:
...
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("test", profile_test_view, name="test"), # <-- NOTE: I removed the slash here
# endpoints
path("posts-json/", post_view_json, name="posts-view-json")
]
...
or call http://127.0.0.1:8000/test/ <-- NOTE: slash added

Django return home page in get absolute url

My PostCreateView
class PostCreateView(CreateView):
model = Posts
template_name = "blog/post_form.html"
fields = ["author", "title", "content"]
My urls
urlpatterns = [
path('', views.home, name='blog-home'),
path('about/', views.about, name='blog-about'),
path("post/new/", PostCreateView.as_view(), name="post-create"),
]
Once I do a post my site crashes since I need to specify a get_absolute_url. I just want to return to the home page but trying
redirect("") fails with error
NoReverseMatch at /post/new/
Reverse for '' not found. '' is not a valid view function or pattern name.
How can I return to the homepage ?
You need to redirect to the view with the given name, so:
redirect('blog-home') # since name='blog-home'
or if you work with a class-based view which has a FormMixin like a CreateView, UpdateView, etc. you reverse with:
from django.urls import reverse
class PostCreateView(CreateView):
# …
def get_success_url(self):
return reverse('blog-home')

Using the URLconf defined,Django tried these URL patterns

I'm doing tutorial "Movie rental" and i got error.
Using the URLconf defined in vidly.urls, Django tried these URL patterns, in this order:
Using the URLconf defined , Django tried these URL patterns, in this order:
1.admin/
2.movies/ [name='movie_index']
3.movies/ <int:movie_id [name='movie_detail']
The current path, movies/1, didn't match any of these.
my code is(from main urls.py):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('movies/', include('movies.urls'))
]
from mysite i.e movies(urls.py)
from . import views
from django.urls import path
urlpatterns = [
path('', views.index, name='movie_index'),
path('<int:movie_id', views.detail, name='movie_detail')
]
from views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Movie
def index(request):
movies = Movie.objects.all()
return render(request, 'movies/index.html', {'movies': movies})
def detail(request, movie_id):
return HttpResponse(movie_id)
What i'm doing wrong?
In your movies.urls you forgot to close URL parameter.
path('<int:movie_id>/', views.detail, name='movie_detail')
Instead you did,
path('<int:movie_id', views.detail, name='movie_detail')
You're missing a closing >/.
path('<int:movie_id>/', views.detail, name='movie_detail')

Django url.py regex not working

I am trying to catch all URLs from the safer app and send them to a catch all view; for example:
http://127.0.0.1:8000/saferdb/123
http://127.0.0.1:8000/saferdb/12
I think I have an issue with my reg ex in url.py:
from django.conf.urls import url
from . import views
app_name = 'saferdb'
urlpatterns = [
url(r'^/$', views.index, name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
]
Views.py is the sample code from the django tutorial:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.all()[:5]
output = ', '.join([q.DOT_Number for q in latest_question_list])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
I noticed that /saferdb/ will not work unless the reg ex contains a slash:
r'^/$' instead of r'^$' as shown in the django tutorial.
Please add '/' at the end of url in root urls.py of 'safer' app, something similar to this:
url(r'^saferdb/', include('saferdb.urls', namespace='saferdb'))

Django 1.9.1 NoReverseMatch when using django.auth

I'm trying to learn django by following the book "Django by Example" and probably due to conflicting versions i'm running into this problem when trying to use django.auth together with some URL settings in
settings.py.
Im getting totally frustrated by now since i have no idea how to even begin debugging this error. Any help or advice would be much appreciated
Here's the relevant part of the settings.py file
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
app views.py:
from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
urls.py
from django.conf.urls import url
from . import views
app_name = 'account'
urlpatterns = {
url(r'^$', views.dashboard, name='dashboard'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
}
Main urls.py :
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/', include('account.urls')),
]
Error Message
updated settings.py :
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')
When you use app_name that sets up a namespace that will be used when you include() that urls.py somewhere else.
So there's no url with the name "login", instead it's called "account:login", and that's the name you have to pass to reverse().
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')
Relevant docs: URL namespaces and included URLconfs
If you are using django-extensions (you should), you can use the management command show_urls to get a nicely formatted list of all the url routes that are registered in your project.

Categories

Resources