How to deal with NoReverseMatch Error in Django - python

I am having this error below:
Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'].
I am working on a blog app. When you click on view more article on your dashboard on index page, the post_detail.html should show the full article and allow users to post comments. I keep getting the error posted above once i click on view article.
Here is the post_detail.html code
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ post.content | safe }}</p>
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
{% with comments.count as total_comments %}
<h2>{{ total_comments }} comments</h2>
<p>
{% endwith %} {% for comment in comments %}
</p>
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="POST" action="{% url 'post_detail' %}" style="margin-top: 1.3em;">
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
My models
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank= True, null=True)
updated_on = models.DateTimeField(auto_now= True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-published_date']
def publish(self):
self.published_date=timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
View for the post_detail
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form}
return render(request, 'blog/post_detail.html', context)
url
urlpatterns = [
path('', views.index, name='index'),
#path('', views.PostList.as_view(), name='index'),
path('login', views.login, name= 'login'),
path('logout', views.logout, name= 'logout'),
path('register', views.register, name = 'register'),
path('dashboard', views.dashboard, name = 'dashboard'),
path('posts', views.posts, name = 'posts'),
path('articles', views.articles, name='articles'),
path('prayers', views.prayers,name='prayers' ),
path('prayer_request', views.prayers, name='prayer_request'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'),
name='password_change_done'),
path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'),
name='password_change'),
path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
name='password_reset_complete'),
]
Kindly help with this error.

Following your urls.py you should a pass a slug along your post_detail url.
So in your form, you can not call your url without a slug like this <form method="POST" action="{% url 'post_detail' %}">
Because you can not easily know the id of your new post, maybe should create a different url for creating a new post, like post_create

Related

Django - how to create proper categories and subcategories

I am currently working on a store made in Django and I have a problem because I have a model for Category as well as Subcategory. The problem is that I don't really know what I did wrong, because in the html file I try to call both categories and subcategories, but in each category all subcategories are displayed, instead of belonging to a specific category. I would like to ask for your help, and check, if files below are correctly written. Thanks in advance
models.py
from django.db import models
from django.urls import reverse
# Class model for category
class Category(models.Model):
name = models.CharField(max_length=200,
db_index=True)
slug = models.SlugField(max_length=200,
db_index=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('selcorshop:product_list_by_category',
args=[self.slug])
# Class model for subcategory
class Subcategory(models.Model):
category = models.ForeignKey(Category,
related_name='category',
on_delete=models.CASCADE)
name = models.CharField(max_length=200,
db_index=True)
slug = models.SlugField(max_length=200,
db_index=True)
class Meta:
ordering = ('name',)
verbose_name = 'subcategory'
verbose_name_plural = 'subcategories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('selcorshop:product_list_by_subcategory',
args=[self.slug])
# Class model for product
class Product(models.Model):
subcategory = models.ForeignKey(Subcategory,
related_name='products',
on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('selcorshop:product_detail',
args=[self.id, self.slug])
views.py
from django.shortcuts import render, get_object_or_404
from .models import Category, Subcategory, Product
from cart.forms import CartAddProductForm
# View for product list in site
def product_list(request, category_slug=None, subcategory_slug=None):
category = None
categories = Category.objects.all()
subcategory = None
subcategories = Subcategory.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
subcategory = get_object_or_404(Subcategory, slug=subcategory_slug)
products = products.filter(category=category)
return render(request,
'selcorshop/product/list.html',
{'category': category,
'categories': categories,
'subcategory': subcategory,
'subcategories': subcategories,
'products': products})
# View for single product
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id = id,
slug = slug,
available = True)
# Add to cart button
cart_product_form = CartAddProductForm()
return render(request,
'selcorshop/product/detail.html',
{'product': product,
'cart_product_form': cart_product_form})
urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'selcorshop'
urlpatterns =[
path('', views.product_list, name='product_list'),
path('<slug:category_slug>/', views.product_list, name='product_list_by_category'),
path('<slug:subcategory_slug>/', views.product_list, name='product_list_by_subcategory'),
path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
list.html
{% extends "selcorshop/base.html" %}
{% load static %}
{% block title %}
{% if category %}{{ category.name }}{% else %}Produkty{% endif %}
{% endblock %}
{% block content %}
<div class="row">
<div id="sidebar" class="col-2">
<div class="d-flex flex-column flex-shrink-0 p-3 text-white bg-dark" style="width: 280px;">
<a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="32" fill="currentColor" class="bi bi-list" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z"/>
</svg>
<span class="fs-4">Kategorie</span>
</a>
<hr>
<ul class="nav nav-pills flex-column mb-auto">
<li {% if not category %}class="nav-item" {% endif %}>
Wszystkie
</li>
<div class="dropdown">
**{% for c in categories %}
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<li {% if category.slug == c.slug %} {% endif %}>
{{ c.name }}
</li>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
{% for s in subcategories %}
<a class="dropdown-item" href="#">
<li {% if subcategory.slug == s.slug %} {% endif %}>
{{ s.name }}
</li>
</a>
{% endfor %}
</div>
{% endfor %}**
</div>
</ul>
<!-- <ul class="nav nav-pills flex-column mb-auto">-->
<!-- <li {% if not category %}class="nav-item" {% endif %}>-->
<!-- Wszystkie-->
<!-- </li>-->
<!-- {% for c in categories %}-->
<!-- <li {% if category.slug == c.slug %} {% endif %}>-->
<!-- {{ c.name }}-->
<!-- </li>-->
<!-- {% endfor %}-->
<!-- </ul>-->
</div>
</div>
<div id="main" class="product_list col-10">
<h2>{% if category %}{{ category.name }}{% else %}Produkty{% endif %}</h2>
{% for product in products %}
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'img/no_image.png' %}{% endif %}" alt="Obraz">
</a>
{{ product.name }}<br>
{{ product.price }} zł.
</div>
{% endfor %}
</div>
</div>
{% endblock %}
So after seeing your code I guess you want to create a dropdown menu in which all the subcategory list related to category open right so for that you can call it with related name which you pass in your subcategory model a use it in your HTML like that
{% for c in category_list %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle text-dark" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="font-weight:500">
<strong>{{ c.name }}</strong>
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDarkDropdownMenuLink">
{% for subcategory in c.category.all %}
<li><a class="dropdown-item" href="#">{{ subcategory.name }}</a>
{% endfor %}
</ul>
</li>
{% endfor %}
this has to solve your problem andd tell me if you still got any issue

django.db.utils.OperationalError: no such column: home_post.assign_to_id

I want to assign a task to one of the users who commented on the post. But when I try to go on post_detail.html an error occurs, and i.e.
OperationalError at /home/
no such column: home_post.assign_to_id
PS: I have done python manage.py makemigrations and python manage.py migrate
So, here is the code snippet. I can give more information if needed. Thanks in advance!
views.py
def SaveAssigned(request):
if request.method == "POST":
if request.POST.get('assigned'):
savevalue = Post()
savevalue.assign_to = request.POST.get('assigned')
savevalue.save()
return render(request, 'post_detail.html')
else:
return render(request, 'post_detail.html')
class PostDetailView(DetailView):
model = Post
# template_name = 'home/post_detail.html'
def get_context_data(self, *args, **kwargs):
post_available = get_object_or_404(Post, id=self.kwargs['pk'])
cat_menu = Category.objects.all()
context = super(PostDetailView, self).get_context_data()
context["cat_menu"] = cat_menu
return context
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/comment/', AddCommentView.as_view(), name='add-comment'),
path('add_category/', AddCategoryView.as_view(), name='add-category'),
path('category/<str:cats>/', CategoryView, name='category'),
path('category-list/', CategoryListView, name='category-list'),
]
models.py
class Post(models.Model):
title = models.CharField(max_length = 100)
snippet = models.CharField(max_length= 200)
content = RichTextField(blank=True, null=True)
date_posted = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User, on_delete= models.CASCADE)
category = models.CharField(max_length=255, default='Coding')
assign_to = models.ForeignKey(User,related_name='assign_to', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('home')
post_detail.html
{% extends 'users/base.html' %}
{% block body %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.category }}</small>
<small class="text-muted" style="float: right;">{{ object.date_posted|date:"F d, Y" }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div>
<a class="btn btn-outline-secondary bt-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-outline-danger bt-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
<a class="btn btn-outline-primary bt-sm mt-1 mb-1" style="float: right;" href="">Done</a>
</div>
<form method="POST">
{% csrf_token %}
<select name="assigned">
<option selected disabled="true"> Select User</option>
{% if not post.comments.all %}
<option>NA</option>
{% else %}
{% for comment in post.comments.all %}
<option>{{ comment.author }}</option>
{% endfor %}
{% endif %}
</select>
<input type="submit" value="Assign" name="">
</form>
{% endif %}
<br>
<hr>
<h2>Comment Section</h2>
<br>
{% if not post.comments.all %}
No Comments yet
<br>
Be the first Ont to Comment!
{% else %}
Add a comment
<br>
{% for comment in post.comments.all %}
<strong>
{{ comment.author }} - {{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
<br><br>
{% endfor %}
<hr>
{% endif %}
<br><br>
{% endblock %}
This error occurs when your model does not contain the specific column and you are trying to add the value in that model with a specific column name.
You can solve this by following steps -
Step - 1. python manage.py makemigration
Step - 2. python manage.py migrate

django database is not saving data of contact from details which i have entered

I'm new to dajngo projects and I have created a blog which has app named as "blog".Everything went all right and I stuck at conatct from.when I sumbmit details in contact from and go to djando admin database the contact details are not saved here.
This is my contact.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>contact us</title>
</head>
{% load static %}
<body style="background-image: url('{% static " img/contact.jpg" %}');background-size: cover;">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<div class="container my-3" style="padding:70px 0">
<h3>Contact Us</h3>
<form method="post" action="{% url "contact" %}" > {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group" >
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group" >
<label for="desc">How May We Help You?</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button style=" margin-top: 25px;" type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</body>
</html>
This is post_detail.html
{% extends 'base.html' %} {% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ post.content | safe }}</p>
</div>
</div>
{% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %}
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
<h2>{{ comments.count }} comments</h2>
{% for comment in comments %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="post" style="margin-top: 1.3em;">
<!--{{ comment_form.as_p }}-->
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
This is admin.py
from django.contrib import admin
from .models import Post,Comment
from .models import Contact
from django_summernote.admin import SummernoteModelAdmin
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status', 'created_on')
list_filter = ("status",)
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'body', 'post', 'created_on', 'active')
list_filter = ('active', 'created_on')
search_fields = ('name', 'email', 'body')
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(active=True)
class PostAdmin(SummernoteModelAdmin):
summernote_fields = ('content',)
admin.site.register(Post, PostAdmin)
admin.site.register(Contact)
This is models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
from django.urls import reverse
return reverse("post_detail", kwargs={"slug": str(self.slug)})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
class Contact(models.Model):
msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
email = models.CharField(max_length=70, default="")
phone = models.CharField(max_length=70, default="")
desc = models.CharField(max_length=500, default="")
def __str__(self):
return self.name
This is urls.py
from . import views
from django.urls import include
from django.urls import path
from .feeds import LatestPostsFeed, AtomSiteNewsFeed
urlpatterns = [
path("feed/rss", LatestPostsFeed(), name="post_feed"),
path("feed/atom", AtomSiteNewsFeed()),
path("<slug:slug>/", views.post_detail, name="post_detail"),
path("", views.PostList.as_view(), name="home"),
path("about.html",views.about,name='about'),
path("contact.html",views.contact,name='contact'),
path("blb.html",views.blb,name='blb '),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
This is view.py
from .models import Post
from django.views import generic
from .forms import CommentForm
from django.shortcuts import render, get_object_or_404
from .models import Contact
def about(request):
return render(request,'about.html',{})
def contact(request):
return render(request,'contact.html',{})
def blb(request):
return render(request,'blb.html',{})
def Contact(request):
if request.method == "POST":
name = request.POST.get['name','']
email = request.POST.get['email','']
phone = request.POST.get['phone','']
content = request.POST.get['content','']
contact = Contact(name=name, email=email, phone=phone, content=content)
contact.save()
return render(request, "contact.html")
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by("-created_on")
template_name = "index.html"
paginate_by = 3
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
This is project urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
sitemaps = {
"posts": PostSitemap,
}
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("blog.urls"), name="blog-urls"),
path("summernote/", include("django_summernote.urls")),
path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
enter image description here
[1]: https://i.stack.imgur.com/RCOt4.png
First of all you shoudn`t put the name of your html template in urls.py of your app.
i mean these three lines :
path("about.html",views.about,name='about'),
path("contact.html",views.contact,name='contact'),
path("blb.html",views.blb,name='blb '),
you have to for example replace them with
path('contact/',...)
and for better and cleaner code , it`s better to use forms in your app . create forms.py in your app DIR and import your model in your forms.py like this for example :
from django import forms
from .models import Profile
class {model name (Table name)}(forms.ModelForm):
class Meta:
model = {model name (Table name)}
fields = '__all__'
Replace {model name (Table name)} with your model in your models.py.
then in each input filed in your HTML template, for name attr , you shoud use the same name that uses in your models.py fields.
And in your views.py you should do like this:
form = **{form name}**(request.POST or None, request.FILES)
if form.is_valid():
form.save()
return redirect('**{ somewhere :) }**')
return render(request, 'contact.html', {'form': form})
Hope this Answer could help you ;-)

i want to display the list of pruducts based on the choice of the category chosing -django

so i want to khow what i have to add in the urls.py and in the views.py to add this functionnality: if i click in one of this categories here my categories display some products based on the category chosen.
and this the models.py
class Product(models.Model):
name=models.CharField(max_length=200,null=True)
price=models.DecimalField(max_digits=7,decimal_places=2)
digital=models.BooleanField(default=False,null=True,blank=True)
image=models.ImageField(blank=True,null=True,upload_to ='images/',default="images/default.jpg")
categories = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True, null=True)
def __str__(self):
return self.name
#property
def imageURL(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
else:
return '/static/images/default.png'
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'categories'
ordering = ['-created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
and this is the template :
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<form method="get" action="">
{% for c in active_categories %}
<a class="dropdown-item" href='#'>{{ c.name }}</a>
{% endfor %}
<a class="dropdown-item" href="#">something else</a>
</form>
</div>
This is simplest way. You can change code as per requirement.
urls.py
from . import views # import views.py file
urlpatterns = [
path('product_list/<id>', views.product_list, name='product_list'),
]
views.py
def product_list(request, id):
products = Product.objects.filter(categories__pk=id)
context = {
'products': products,
}
return render(request, 'product_list.html', context)
link template (Check the change in link)
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<form method="get" action="">
{% for c in active_categories %}
<a class="dropdown-item" href="{% url 'product_list' id=c.pk %}">{{ c.name }}</a>
{% endfor %}
<a class="dropdown-item" href="#">something else</a>
</form>
</div>
product_list.html
Your regular html things +
{% for product in products %}
<p>{{ product.name }}</p>
<p>{{ product.price }}</p>
{% empty %} # in case there is no product in this category
<p>No product available for this category</p>
{% endfor %}
I hope this will help. Please comment if get any error.
If you products to load without refreshing the page, you can use ajax. Reply if need that.
You can try this:
views.py
def my_view(request):
category_id = request.GET.get('category_id')
context = {}
if category_id:
products = Product.objects.filter(categories__id=category__id)
context["products"] = products
return render(request, 'template', context)
template
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<form method="get" action="">
{% for c in active_categories %}
<a class="dropdown-item" href='?category_id={{ c.id }}'>{{ c.name }}</a>
{% endfor %}
<a class="dropdown-item" href="#">something else</a>
</form>
</div>

Wrong url in pagination. Django

I want to search by two fields (q1 and q2):
home.html
<form action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search...">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>All locations</option>
<option>RU</option>
<option>Ukraine</option>
<option>USA</option>
</select>
<button> Search </button>
</form>
When I click "search" I go to http://127.0.0.1:8001/search/?q=mos&q2=RU (it's OK)
Then I click "next". I go to
http://127.0.0.1:8001/search/?city=2&q=mos&q2=%20RU (ERROR: "Page not found)
but I want
http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU
How can I fix it? Why do I have "%20" ???
search results.html
<h1>Search Results</h1>
<ul>
{% for city in object_list %}
<li>
{{ city.name }}, {{ city.state }}
</li>
{% endfor %}
</ul>
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=255)
state = models.CharField(max_length=255)
COUNTRY = (
('RU', 'Russia'),
('UKR', 'Ukraine'),
('US', 'USA'),
)
category = models.CharField(max_length=100, choices=COUNTRY, default='RU')
class Meta:
verbose_name_plural = "cities"
def __str__(self):
return self.name
urls.py
urlpatterns = [
path('search/', SearchResultsView.as_view(), name='search_results'),
path('', HomePageView.as_view(), name='home'),
path('city/<int:pk>/', views.city_detail, name='city_detail'),
]
views.py
class HomePageView(ListView):
model = City
template_name = 'cities/home.html'
paginate_by = 3
page_kwarg = 'city'
def city_detail(request, pk):
city = get_object_or_404(City, pk=pk)
return render(request, 'cities/city_detail.html', {'city': city})
class SearchResultsView(ListView):
model = City
template_name = 'cities/search_results.html'
paginate_by = 3
page_kwarg = 'city'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
#print("BBBBBBBBBBBBBBBBb {}".format(context['query2']))
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
#print("AAAAAAAAAAAAAAAAAAAAA", query2, type(query2))
object_list = City.objects.filter(
(Q(name__icontains=query) | Q(state__icontains=query)) & Q(category=query2)
)
return object_list
%20 is the url code for a space. You need to remove the extra spaces in :
previous
# ^
and
next
# ^

Categories