Page not found (404) on django - django

I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know.
This is my code for urls
from django.urls import path
from django.views.generic.detail import DetailView
from django.views.generic import *
from main import models, views
app_name = 'main'
urlpatterns = [
path('', views.home, name='home'),
path('about_us/', views.about_us, name='about_us'),
path('contact-us/', views.ContactUsView.as_view(), name='contact_us'),
path(
"products/<slug:tag>/",
views.ProductListView.as_view(),
name="products"
),
path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'),
]
my code for views
from django.views.generic.edit import FormView
from .forms import ContactForm
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.shortcuts import get_object_or_404
from main import models
class ProductListView(ListView):
template_name = "main/product_list.html"
paginate_by = 4
def get_queryset(self):
tag = self.kwargs['tag']
self.tag = None
if tag != "all":
self.tag = get_object_or_404(
models.ProductTag, slug=tag
)
if self.tag:
products = models.Product.objects.active().filter(
tags=self.tag
)
else:
products = models.Product.objects.active()
return products.order_by("name")
then my browser
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products
Using the URLconf defined in booktime.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about_us/ [name='about_us']
contact-us/ [name='contact_us']
products/<slug:tag>/ [name='products']
product/<slug:slug>/ [name='product']
^media/(?P<path>.*)$
The current path, products, didn’t match any of these.

You have to create a path to url ending with "products/". You create url just to sent with parameter "tags". "products/slug:tag/"
So, add 'products/' to your urls path the url below and you'll access with 'http://127.0.0.1:8000/products/'
path(
"products/",
views.ProductListView.as_view(),
name="products"
)

Related

Page Not Found 404 Django & Python

I am having the following error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in Decoder.urls, Django tried these URL patterns, in this order:
form.html [name='form1']
hl7 [name='hl7']
The empty path 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.
Its my first time writing code using Django
`from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('hl7rest.urls')),
]`
and this other file
from . import views
from django.urls import path
urlpatterns = [
path('form.html', views.render_form_View, name='form1'),
path('hl7', views.hl7_web_view ,name='hl7'),
]
Your paths don' t match the request.
You can create a TemplateView subclass for render your template:
Views
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = "display_form.html"
Url patterns
urlpatterns = [
path('', HomePageView.as_view(), name='home')
]

Page not found for the template returned by TemplateResponse in Django

I have an app which is called sitepages which have three models I wanna pass their objects to a html page called listing.html which is inside templates/sitepages
the sitepages urls.py contains:
from django.views.generic import TemplateView
from django.urls import include
from django.urls import path
from sitepages import views
app_name = "sitepages"
urlpatterns = [
path("news-events-listing/", views.view, name='listing'),
]
the sitepages/views.py:
from .models import Listing, Details1, Details2
from django.template.response import TemplateResponse
def view(request):
return TemplateResponse(request, 'sitepages/listing.html', {
'first_pages': Details1.objects.all(),
'seconde_pages': Details1.objects.all(),
'listing_page': Listing.objects.first(),
})
in the root urls.py I added:
path("", include("sitepages.urls", namespace='sitepages'))
when I put in any template the following:
Listing
it redirects me to the url /news-events-listing but no page is found and it gives me 404 error...what am I doing wrong? why the template is not returned? I should mention that I'm using wagtail for the whole site (I don't know if it's related)
In your root urls.py, make sure your new line
path("", include("sitepages.urls", namespace='sitepages'))
appears before the path("", include(wagtail_urls)) line. The wagtail_urls pattern matches any URL path and passes it to Wagtail to be handled as a Wagtail page, so any patterns after it will never be reached.

Django writing view with sudomain

With my (Django v 1.17) project I am using django-subdomains.
I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html.
My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404).
Hete is my code:
settings.py
INSTALLED_APPS = [
'subdomain'
]
SUBDOMAIN_URLCONFS = {
'subdomain': 'subdomain.urls',
}
subdomain/urls.py
from django.conf.urls import url, include
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$example', views.example, name='example'),
]
subdomain/views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
def index(request):
template = loader.get_template('subdomain/index.html')
return HttpResponse(template.render())
def example(request):
template = loader.get_template('subdomain/example.html')
return HttpResponse(template.render())
Error:
Page not found (404)
Request Method: GET
Request URL: https://subdomain.domain.com/example
Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^$example [name='example']
The current path, econ, didn't match any of these.
Please advise how to fix this issue and write view for sub-domain.
This is unrelated to django-subdomains. The dollar should be at the end of the regex.
url(r'^example$', views.example, name='example'),
The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.

Django does not match urls

I've been working on a django web app (using Django 1.3), a web catalogue of products, and it was working fine until I was asked to add a custom admin site. I'm fully aware of the Django admin site, but the client is very old-fashioned, and is tech-ignorant so I have to make a "for dummies" version admin site. The root urlconf:
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
from store.models import Category
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^^$', TemplateView.as_view(
template_name='homepage.html',
get_context_data=lambda: {
'crumb': 'home',
'category_list':Category.objects.all()
}
),
name='home'),
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/img/favicon.ico'}),
url(r'^store/', include('store.urls', app_name='store', namespace='store')),
)
And the urlconf for the store app:
from django.conf import settings
from django.conf.urls.defaults import *
from store import views
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
)
and the original views:
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from store.models import Category, Brand, Product
def get_brands(request):
q = request.GET.get('q')
if q is not None:
category = get_object_or_404(Category, slug__iexact=q)
try:
brands = category.brands.all()
except:
brands = []
template = 'infobox.html'
data = {
'category': category,
'brands': brands,
}
return render( request, template, data )
class GalleryView(ListView):
context_object_name = 'product_list'
template_name = 'store/gallery.html'
def get_queryset(self):
self.category = get_object_or_404(Category, slug__iexact=self.args[0])
try:
brand = Brand.objects.get(slug__iexact = self.args[1])
self.brand_name = brand.name
except:
#no brand is specified, show products with no brand
if self.category.category_products.filter(brand__isnull=True):
#if there are products with no brand, return those
return self.category.category_products.filter(brand__isnull=True)
else:
#if all products have a brand, return the products of the first brand
all = self.category.brands.all()
if all:
brand = all[0]
self.brand_name = brand.name
return brand.brand_products.all()
else:
raise Http404
else:
#brand is specified, show its products
return Product.objects.filter(category=self.category, brand=brand)
def get_context_data(self, **kwargs):
context = super(GalleryView, self).get_context_data(**kwargs)
category = self.category
category_brands = self.category.brands.all()
context['category_list'] = Category.objects.all()
context['category'] = category
context['crumb'] = category.name
context['category_brands'] = category_brands
try:
context['brand'] = self.brand_name
except:
context['brand'] = None
return context
Now, my custom admin app was working fine on my local dev environment, but when I added the new urls and views to prod, Django doesn't seem to match any of the new urls. The original views and urls still work, but none of the new urls get matched and I just keep getting a 404 Not Found error.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
url(r'^$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^test/', views.test, name='test'),
url(r'^admin/', include(admin_urls, namespace='admin')),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
)
Note that not even the simple '/store/test/' url does not get matched. I'm not really sure why Django isn't matching my urls, and any help is appreciated.
I'm not exactly sure what was happening since all of my templates linked to other pages using the {% url %} tag, but I think the reason my urls were getting muddled up was because I was using the r'^(\w+)/$' regex, so it was matching any word. I simply moved the urlconfs with the (\w+) rule to the bottom of urls.py, and refactored them to be a little more specific and they were gold again.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
As you mentioned in the comments, removing login_required fixes the problem. Here's what the django docs have to say about the decorator:
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example:
/accounts/login/?next=/polls/3/.
If the user is logged in, execute the view normally
[...] Note that if you don't specify the login_url parameter, you'll
need to map the appropriate Django view to settings.LOGIN_URL.
In other words, it goes to a default url you can override in settings.LOGIN_URL.
Now here's what I think happened - I think you defined your own login here:
url(r'^login/$', views.admin_login, name='login'),
And because the login_required in the new urls pointed at the default url, which doesn't exist it returned 404. However, when you configured the login_required views after your other urls:
url(r'^login/$', views.admin_login, name='login'),
...
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
it worked. Why is that? You didn't overrid LOGIN_URL here right? But you sort of did - because at this point, you redefined the namespace 'login' to point to your own view. Now this isn't mentioned anywhere in the docs, but it makes sense, and looking at the default admin templates you can see this is the namespace being used.
Does that make sense to you?

view does not exist when trying to include a built in login/logout system in django views

The code is
#urls.py
from django.conf.urls import patterns, url
from employees import views
from schdeules import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
url(r'^accounts/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
url(r'^accounts/profile/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
)
#views.py
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
#login_required
def home(request):
welecome = 'hai welcome to opas'
context = {'temp_var': welecome}
return render(request, 'schdeules/home.html')
and iam getting an error
Exception Type: ViewDoesNotExist at /opas/
Exception Value: Could not import django.views.generic.simple.redirect_to. Parent module django.views.generic.simple does not exist.
i want to use django default login and logout modules.
if successfully logged in then i want to redirect to home page.
Thanks in advance.
The function-based generic view redirect_to was deprecated in Django 1.3, and removed in Django 1.5. Use the class-based generic view RedirectView instead.
from django.views.generic.base import RedirectView
urlpaterns = ('',
...
url(r'^accounts/$', RedirectView.as_view(url='/')),
url(r'^accounts/profile/$', RedirectView.as_view(url='/')),
)
Note that you don't have to include url patterns for /accounts/ and /accounts/profile/. You may be better to set LOGIN_REDIRECT_VIEW in your settings, so that users are redirected straight to the home page after logging in.
LOGIN_REDIRECT_VIEW = 'home' # using a named url pattern requires Django 1.5 or later