Page not found (404) Request Method: - django

please help me. I don't know why can't see the detail of product when i click a product. both first list work good just when i need to see detail of product in second list(filtered list) an 404 error shows.
thanks
here is my code below:
my urls:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
]
views:
from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.views import generic
from .models import Category, Product
class HomeView(generic.ListView):
model = Category
template_name = 'home.html'
class ProductListView(generic.ListView):
template_name = 'product_list.html'
def get_queryset(self):
self.category = get_object_or_404(Category, title=self.kwargs['category'])
return Product.objects.filter(category=self.category)
class ProductDetailView(generic.DetailView):
model = Product
template_name = 'product_detail.html'
product_list.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
{% for product in product_list %}
<a href="{% url 'shop:product-detail' product.pk %}">
<div class="card bg-light mb-3" style="max-width: 18rem;">
<div class="card-header">{{ product.title }}</div>
<img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}">
<div class="card-body">
<p class="card-text">{{ product.description }}</p>
</div>
</div>
</a>
{% endfor %}
{% endblock %}
product_detail.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
<h1>thid</h1>
{{ product.name }}
{% endblock %}

Even if the you visit /categories/1, it will use the ProductListView, since the str path converter also accepts a sequence of digits. You can swap the paths, so:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
]
Then for /categories/1, it will match with <int:pk> as 1, and thus fire the ProductDetailView.

Related

Why I can not display two listviews in one template?

I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site.
So I made listviews for listing the two HeroListView and NotificationListView for that.
But the second one is not appearing in the page.
Please tell me how to solve this issue.
This is the models.py file
from django.db import models
class Hero(models.Model):
image = models.ImageField(upload_to="heros/")
class Notification(models.Model):
notification = models.CharField(max_length=200)
This is the views.py file.
from django.views.generic import ListView
from .models import Hero, Notification
class HeroListView(ListView):
model = Hero
template_name = "home.html"
context_object_name = "hero_list"
class NoticficationListView(ListView):
model = Notification
template_name = "home.html"
context_object_name = "notification_list"
this is the app/urls.py file
from django.urls import path
from .views import HeroListView, NoticficationListView
urlpatterns = [
path("", HeroListView.as_view(), name="home"),
path("", NoticficationListView.as_view(), name="home"),
]
this is the project/urls.py file
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("heros.urls")),
path("", include("products.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends '_base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
{% load static %}
<div class="container mt-4">
<div id="carouselExampleControls" class="carousel carousel-dark slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{% static 'images/hero2.jpg' %}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% for hero in hero_list %}
<div class="carousel-item">
<img src="{{ hero.image.url }}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% endfor %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="div">
{% for note in notification.list %}
<p>{{ note.notification }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
please tell me how to solve this issue.
You can do it this way
class HeroListView(ListView):
model = Hero
template_name = "home.html"
def get_context_data(self):
context = super(HeroListView, self).get_context_data()
context['hero_list'] = Hero.objects.all()
context['notification_list'] = Notification.objects.all()
return context
You can't access two or multiple views at the same time, so in your case, you can remove NoticficationListView and use only HeroListView to render both hero_list and notification_list

why I can't get the PasswordResetDoneView page?

when I submit my Email form from PasswordResetView page the email appears via URL as following: http://127.0.0.1:8000/account/password-change/?email=medoabdin%40gmail.com and not directing me to PasswordResetDoneView page and I get no error.
how can I show PasswordResetDoneView message page
urls.py
from django.urls import path
from . import views
from django.contrib.auth.views import (
LoginView,
LogoutView,
PasswordResetView,
PasswordResetDoneView)
from django.urls import reverse_lazy
app_name = 'account'
urlpatterns = [
# /account/login/
path('login/', LoginView.as_view(template_name='account/login.html'), name='login'),
# /account/logout/
path('logout/', LogoutView.as_view(template_name='account/logout.html'), name='logout'),
# /account/register/
path('register/', views.register, name='register'),
# /account/view-profile/
path('view-profile/', views.view_profile, name='view_profile'),
# /account/password-change/
path('password-change/', PasswordResetView.as_view(template_name='account/password_change_view.html', success_url=reverse_lazy('account:password_change_done'), email_template_name='account/reset_password_email.html'), name='password_change'),
# /account/password-change/done/
path('password-chane/done/', PasswordResetDoneView.as_view(template_name='account/password_change_done.html'), name='password_change_done'),
]
password_change_done.html
{% extends 'base.html' %}
{% block title %} Success Message {% endblock %}
{% block body %}
{% if not user.is_authenticated %}
<div class="password-change-done">
<div class="container">
<h1 class="text-primary"> The Password Has Been Sent </h1>
<p class="lead text-success"> Check your email and following the rest of record until you can go back your own email. </p>
<p class="lead text-success"> You need to follow the instructions to get what you want. </p>
</div>
</div>
{% endif %}
{% endblock %}
password_change_view.html
{% extends 'base.html' %}
{% block title %} Chnage your Passowrd {% endblock %}
{% block body %}
{% if not user.is_authenticated %}
<div class="password-change">
<div class="container">
<div class="my-form">
<form class="post">
{{ form.as_p }}
<button type="submit" class="btn btn-success">Go</button>
</form>
</div>
</div>
</div>
{% endif %}
{% endblock %}
settings.py
urlpatterns = [
path('', include('index.urls')),
path('account/', include('account.urls')),
path('admin/', admin.site.urls),
path('', include('django.contrib.auth.urls')),
]
Put method="post" in form tag and also {% csrf_token %}, probably because of GET method same view is rendering and form_valid is not invoking.

Signup page upon submission leads to error Django

I have built a site, where the user upon successful signup should be redirected to the login page. However it is not occurring so. Attached below are the relevant files:
Signup page html:
{% extends "base.html" %}
{% load bootstrap4 %}
{% block content %}
<div class="container">
<h1>Sign Up</h1>
<form method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Sign Up</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'),
path('logout/', auth_views.LogoutView.as_view(), name="logout"),
path('signup/', views.SignUp.as_view(), name="signup"),
]
views.py:
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"
Any help is appreciated. Thank you.

I want to use paginator by using class based view on django

As I mentioned at Title I want to use paginator.
I coded as Django Docs introduced but it's not work.
What is the reason??
This is my View
from django.shortcuts import render_to_response
from django.views.generic import CreateView, ListView, UpdateView, DetailView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article
class ArticleListView(ListView):
model = Article
def listing(request):
article_list = Article.objects.all()
paginator = Paginator(article_list, 7)
page = request.GET.get('page')
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.num_pages)
return render_to_response('blog/article_list.html', {'articles': articles})
and the following is my urls
from django.conf.urls import patterns, url
from .views import ArticleCreateView, ArticleUpdateView, ArticleListView, ArticleDetailView
urlpatterns = patterns('',
url(r'^list/$', ArticleListView.as_view(), name='list'),
)
the last is my template
{% extends 'base.html' %}
{% block title %} list {% endblock %}
{% block content %}
<p>
new
</p>
{% for article in article_list %}
<div id="article">
<div id="author">
<p>{{ article.author }}</p>
</div>
<div id="time">
<p>{{ article.created }}</p>
</div>
<div id="body">
<p>{{ article.body }}</p>
</div>
<div id="edit">
modify
</div>
</div>
{% endfor %}
{% for article in articles %}
{{ article.full_name|upper }}<br>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if articles.has_previous %}
pre
{% endif %}
<span class="current">
Page {{ articles.number }} of {{ articles.paginator.num_pages }}
</span>
{% if articles.has_next %}
next
{% endif %}
</span>
</div>
{% endblock %}
what is problem??
I think server cannot dectect def listing in class based view

Django http404 error urlconf confusion

I was really confused why I was receiving Http404 error. To be more clear heres my code:
My app named books
views.py
from django.shortcuts import render_to_response
from django.http import Http404
from django.template import RequestContext
from books.models import *
def index(request):
title = 'Book Gallery'
books = Book.objects.all().order_by('-id')
lang_list = Lang.objects.all().order_by('-lang')
template = 'books/index.djhtml'
context = {'books': books, 'title': title, 'lang_list': lang_list}
return render_to_response( template, context, context_instance=RequestContext(request) )
def by_book_slug(request, bookslug):
slug = bookslug
try:
book = Book.objects.get(slug=slug)
except:
raise Http404
title = book.name
template = 'books/singlebook.djhtml'
context = {'book': book, 'title': title}
return render_to_response( template, context, context_instance=RequestContext(request) )
def by_lang_slug(request, langslug):
filter = langslug
try:
language = Lang.objects.get(slug=filter)
except:
raise Http404
lang_list = Lang.objects.all().order_by('-lang')
books = Book.objects.filter(lang=language).order_by('-id')
title = language
template = 'books/by_language.djhtml'
context = {'books': books, 'title': title, 'filter': filter, 'lang_list': lang_list}
return render_to_response( template, context, context_instance=RequestContext(request) )
urls.py inside my book app folder
from django.conf.urls import patterns, include, url
from books import views
urlpatterns = patterns('',
url(r'(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
url(r'(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
url(r'^$', views.index, name='book_gallery'),
)
link that pertains to langslug url conf works but those links for bookslug url conf does not work. When I try to switch them down and up, one of them work and the other one is not.
I really don't know what is happening here. Any help will be a great help. Thanks.
the index template of my books app
{% extends 'base.djhtml' %}
{% block title %} | Gallery{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
{% endblock %}
{% block content_header %}
{% endblock %}
{% block content_body %}
<div class="row">
<div class="span3">
<strong>filtered by >
{% if filter %}
{{ filter }}
{% else %}
All
{% endif %}
</strong>
<ul class="nav nav-list">
<li class="nav-header">Filter</li>
<li class="nav-header
{% if not filter %}
active
{% endif %}
">All</li>
{% for list in lang_list %}
<li class="nav-header
{% if filter == list.slug %}
active
{% endif %}
">
{{ list.lang }}
</li>
{% endfor %}
</ul>
</div>
<div class="span9">
{% for book in books %}
<div class="span3">
<a href="{{ book.book_cover.url }}">
<img alt="{{book.name}}" src="{{ book.thumbnail.url }}" />
</a>
<h4>{{book.name}}</h4>
<p>{{book.desc|truncatewords:15}}</p>
View more...
</div>
{% endfor %}
</div>
</div>
{% endblock %}
The by_language template for my book app
{% extends 'base.djhtml' %}
{% block title %} | Gallery{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
{% endblock %}
{% block content_header %}
{% endblock %}
{% block content_body %}
<div class="row">
<div class="span3">
<strong>filtered by >
{% if filter %}
{{ filter }}
{% else %}
All
{% endif %}
</strong>
<ul class="nav nav-list">
<li class="nav-header">Filter</li>
<li class="nav-header
{% if not filter %}
active
{% endif %}
">All</li>
{% for list in lang_list %}
<li class="nav-header
{% if filter == list.slug %}
active
{% endif %}
">
{{ list.lang }}
</li>
{% endfor %}
</ul>
</div>
<div class="span9">
{% for book in books %}
<div class="span3">
<a href="{{ book.book_cover.url }}">
<img alt="{{book.name}}" src="{{ book.thumbnail.url }}" />
</a>
<h4>{{book.name}}</h4>
<p>{{book.desc|truncatewords:15}}</p>
View more...
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I have included a raise Http404 method when specified slug does not match to any query in the database. The thing I was confused about is, when I try to switch langslug and bookslug urlconf, links that are associated to one of these url works and the other is not.
Based on your url, if I put value on it even though they have different view, the result would be:
urlpatterns = patterns('',
# http://localhost:8000/English/
url(r'(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
# http://localhost:8000/YourBook/
url(r'(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
# http://localhost:8000/
url(r'^$', views.index, name='book_gallery'),
)
Have you notice it, they have the same pattern so the first view execute is the by_lang_slug. So if you change the order the other one will be executed first. The best thing to do about it is to have a unique url name.
urlpatterns = patterns('',
# http://localhost:8000/lang/English/
url(r'lang/(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
# http://localhost:8000/book/YourBook/
url(r'book/(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
# http://localhost:8000/
url(r'^$', views.index, name='book_gallery'),
)
Now they are different....