URL Error in Django,Page not found 404 - django

This is my views.py :
from django.http import Http404
from django.shortcuts import render
from .models import Album
def index(request):
all_albums = Album.objects.all()
return render(request, 'music/index.html', {'all_albums': all_albums})
def detail(request, album_id):
try:
album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
raise Http404("Album does not exist")
return render(request, '/music/detail.html', {'album': album})
This is my music\urls.py :
from django.conf.urls import url
from . import views
urlpatterns = (
url(r'^$', views.index, name='index'),
url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'),
)
When I am running this code, I am getting the error as :

As stacktrace said you are trying to open http://127.0.0.1/music/id/1 page not http://127.0.0.1/music/1 but there is no such urp pattern in your urls.py. You need try to open http://127.0.0.1/music/1 or add new pattern:
url(r'^id/(?P<album_id>[0-9]+)/$', views.detail, name='detail')
to see http://127.0.0.1/music/id/1 page.

Related

Django Sitemap is not working gives error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name."

I'm trying to implement a Sitemap for my app and I get the error
"Reverse for 'index' not found. 'index' is not a valid view function or pattern name."
even though these views are set up.
What could cause this? I have no problem with dynamic sitemaps, just the static one.
My views.py
def front_page(request):
return render(request, 'django_modules_testing_app/front_page.html', {})
def about_us(request):
return render(request, 'ihgr_app/about_us.html', {})
def index(request):
return render(request, 'django_modules_testing_app/index.html', {})
urls.py
from django.urls import path
from . import views
from . import blocks
from django.contrib.sitemaps.views import sitemap
from .sitemaps import DjangoModulesTestingApp
app_name = 'django_modules_testing_app'
sitemaps = {
'main_app':DjangoModulesTestingApp
}
urlpatterns = [
path('', views.front_page, name='front_page'),
path('', views.index, name='index'),
path('', views.about_us, name='about_us'),
path('category_details/<slug:slug>/', blocks.category_details, name='category_details'),
path('search_website/', views.SearchWebsite.as_view(), name='search_website'),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap')
]
sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(item)
You've to specify your app name inside reverse(...) like this
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(f"django_modules_testing_app:{item}")

My django admin page gives Page not found (404)

my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404)
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page
project urls
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
path('account/', include('account.urls', namespace = 'account')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
store urls
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.product_all, name='product_all'),
path('<slug:slug>', views.product_detail, name='product_detail'),
path('shop/<slug:category_slug>/', views.category_list, name='category_list'),
]
store views
from urllib import request
from django.shortcuts import get_object_or_404, render
from store.context_processors import categories
from .models import Category, Product
def product_all(request):
products = Product.products.all()
return render(request, 'store/home.html', {'products': products})
def category_list(request, category_slug=None):
category = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category)
return render(request, 'store/products/category.html', {'category': category, 'products': products})
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
return render(request, 'store/products/single.html', {'product': product}) ```
context_processors.py wicht i have includet in my project settings
from .models import Category
def categories(request):
return {
'categories': Category.objects.all()
}
This is the code that causes the error
path('<slug:slug>', views.product_detail, name='product_detail'),
Change it to
path('detail/<slug:slug>/', views.product_detail, name='product_detail'),
The product_detail just overwrites the admin URL

Why am I getting error 404 in my django project when everything seems correct?

I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py:
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
basket/urls.py:
from django.urls import path
from . import views
app_name = 'basket'
urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
I am getting an error:
Page not found(404)
Request Method:GET
Request URL:http://127.0.0.1:8000/basket/
Raised by:store.views.product_detail
this is my store/views.py:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}
return render(request, 'store/products/detail.html', context)
please help me solve this problem i've been stuck on this for a long time.
Try this way if you want to avoid 404 error:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')
return render(request, 'store/products/detail.html', context
)

How to make custom 404 page for the Detail view with <int:pk>, if the instance not found?

so the error is Page not found(404) when I am requesting the instance that does not exist. I would like to customize the 404 page, instead of displaying the general error.
Here is my new_wiki/urls
from django.urls import path
from . import views
from .views import IndexView, InstanceView, AddPostView, EditPost
urlpatterns = [
# path('', views.index, name="index")
path('', IndexView.as_view(), name="index"),
path('instance/<int:pk>', InstanceView.as_view(), name="instance"),
path('create_post/', AddPostView.as_view(), name="create_post"),
path('instance/edit/<int:pk>', EditPost.as_view(), name="edit_post")
]
And my InstanceView class
class InstanceView(DetailView):
model = Post
template_name = 'new_wiki/instance.html'
I have tried to use the solution from Django documentation:
def detail(request, post_id):
try:
p = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
raise Http404("Poll does not exist")
return render(request, 'new_wiki/instance.html', {'post': p})
but it is still returning the same 404 page. Thank you
You can just render a page with a 404 status:
def detail(request, post_id):
try:
p = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return render(request, 'new_wiki/404error.html', status=404)
return render(request, 'new_wiki/instance.html', {'post': p})
If you want to specify a custom 404 page in general, you specify the handler404 [Django-doc] in the urls.py:
from django.urls import path
from . import views
from .views import IndexView, InstanceView, AddPostView, EditPost
urlpatterns = [
# path('', views.index, name="index")
path('', IndexView.as_view(), name="index"),
path('instance/<int:pk>', InstanceView.as_view(), name="instance"),
path('create_post/', AddPostView.as_view(), name="create_post"),
path('instance/edit/<int:pk>', EditPost.as_view(), name="edit_post")
]
handler404 = views.handler404
In the view you can then analyze the exception parameter and return a specific
# app/views.py
from django.http import HttpResponseNotFound
def handler404(request, exception):
data = exception.args
if data:
return HttpResponseNotFound(data[0])
return HttpResponseNotFound('some text')
This then works if you set the DEBUG setting [Django-doc] to False:
# settings.py
DEBUG = False
In that case the handler will be invoked when you raise a Http404.
Please use get_object_or_404 method
from django.shortcuts import get_object_or_404
def detail(request, post_id):
p = get_object_or_404(Post,pk=post_id)
return render(request, 'new_wiki/instance.html', {'post': p})
Please check this is working.

why it shows error that from . views can't be imported

music/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<album_id>[0-9)+$', views.detail, name='detail'),
]
followed by views.py code
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>this is something</h1>")
def detail(request, album_id):
return HttpResponse("<h2> details of album " + str(album_id)+"</h2>")
the main url website is built correctly..