django view dont show anything - python

I'm working to create an event page in my Django work.
Although I wrote a code to obtain database data when I try to load the front page(from exhibition_view.html), just the exhibition.view_html loads and no article return and does not show in that page.
the weird thing is that seminar_view and exhibition_view are the same, and seminar_view does work!
I tried very much to solve the issue, but had no idea what is happening!
below is my code:
Model.py
from django.db import models
from django.utils import timezone
from tinymce.models import HTMLField
class EventType(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Event Types"
def get_deleted_event_type():
return EventType.objects.get(name='no-category')
class Event(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
EVENT_CHOICES = (
('seminar', 'seminar'),
('exhibition', 'exhibition'),
)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=250,
unique_for_date='publish', allow_unicode=True, unique=True)
body = HTMLField()
publish = models.DateTimeField(default=timezone.now)
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
events = models.ForeignKey(EventType, on_delete=models.SET(get_deleted_event_type))
event_type = models.CharField(max_length=15,
choices=EVENT_CHOICES,
default='seminar')
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
event_index = models.IntegerField()
class Meta:
ordering = ('-publish',)
verbose_name_plural = "Events"
def __str__(self):
return self.title
Views.py
from django.shortcuts import render
from .models import Event
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
def seminar_detail(request, slug):
seminars = Event.objects.get(slug=slug)
context = {
'seminars': seminars
}
return render(request, "seminar_detail.html", context)
def exhibition_detail(request, events, slug):
cr1 = Q(events='2')
cr2 = Q(slug=slug)
exhibitions = Event.objects.get(cr1 & cr2)
context = {
'exhibitions': exhibitions
}
return render(request, "exhibition_detail.html", context)
def seminar_view(request):
criterion1 = Q(status='published')
criterion2 = Q(event_type="seminar")
seminars = Event.objects.filter(criterion1 & criterion2).order_by('event_index')
context = {
'seminars': seminars
}
return render(request, "seminar_view.html", context)
def exhibition_view(request):
criterion3 = Q(status='published')
criterion4 = Q(event_type="exhibition")
exhibitions_view = Event.objects.filter(criterion3 & criterion4).order_by('event_index')
context = {
'exhibitions_view': exhibitions_view
}
return render(request, "exhibition_view.html", context)
exhibition_view.html
{% extends 'base.html' %}
{% load static %}
<head>
<title>{% block title %}exhibitions{% endblock %}</title>
</head>
{% block page_content %}
<div class="page" id="page-container" >
<div class="top-bread">
<div class="breadcrumbs">
<ul>
<li class="home">
home
<span>»</span>
</li>
<li class="socialvoice">
<strong>exhibitions</strong>
</li>
</ul>
</div>
</div>
</div>
<div class="page">
<div class="main-container col1-layout">
<div class="main">
<div class="col-main">
<div class="shopbybrand-list">
<div class="brands">
<ul class="col">
{% for myevent in exhibitions_view %}
<li class="box">
<span>
<a href="{% url 'events:exhibition_view' event.slug %}">
<b>
<h2>{{ myevent.title }}<br/>{{ myevent.created_on.date }}</h2>
</b>
</a>
</span>
<b>
<p>
<p style="text-align: justify;">{{ myevent.body | safe | slice:":400" }}</p>
</p>
<a class="button" href="{% url 'events:exhibition_view' myevent.slug %}">
<span>
<span>ادامه مطلب</span>
</span>
</a>
</b>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
</div>
</div><!-- END page -->
{% endblock %}
and my app urls.py:
from django.urls import path
from . import views
from django.urls import re_path
app_name = 'events'
urlpatterns = [
path('seminar/', views.seminar_view, name="seminar_view"),
path('exhibition/', views.exhibition_view, name="exhibition_view"),
re_path(r'seminar/(?P<slug>[-\w]+)/', views.seminar_detail, name="seminar_detail"),
re_path(r'exhibition/(?P<slug>[-\w]+)/$', views.exhibition_detail, name="exhibition_detail"),
]

Related

ValueError at /category/economy/: Field 'id' expected a number but got 'economy'

I try to add new path and this happen "Field 'id' expected a number but got 'economy'."
in traceback the highlighted line is in the views.py file which i mentioned below.
category_posts = Post.objects.filter(category=cats)
I am sharing my files plz help me to get rid of the issue.
urls.py
urlpatterns = [
path('',views.allpost,name="allpost"),
path('search', views.search, name="search"),
path('contact/', views.contact, name="contact"),
path('success/', views.successView, name="success"),
path('category/<str:cats>/', views.CategoryView, name ="category"),
path('<int:blog_id>/',views.detail,name="detail"),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'."
views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
"category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback
models.py
from django.db import models
class Category(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
title = models.CharField(max_length=255, verbose_name="Title")
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=
True, null=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
public_date = models.DateField(null=True)
public_time = models.TimeField(null=True,default="")
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True)
image = models.ImageField(upload_to='images/',null=True, blank=True)
body = models.TextField()
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['public_date']
def summary(self):
return self.body[:100]
def pub_date(self):
return self.public_date.strftime('%b %e,%y')
# to give layout for time and date
def __str__(self):
return self.title
categories.html
{% extends 'base.html' %}
{%block content%}
<h1> Category: {{ cats }} </h1>
{% for post in category_posts %}
<div class="container mt-3">
<div class="row mb-2">
<div class="col-md-6">
<div class="card flex-md-row mb-4 box-shadow h-md-250">
<div class="card-body d-flex flex-column align-items-start">
<strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong>
<h3 class="mb-0">
<a class="text-dark" href="{% url 'detail' post.id %}">{{post.title}}</a>
</h3>
<div class="mb-1 text-muted">{{ post.public_date }}</div>
<p class="card-text mb-auto">{{ post.summary }}</p>
Continue reading
</div>
<img class="card-img-right flex-auto d-none d-md-block" data-src="holder.js/200x250?theme=thumb" alt="Thumbnail [200x250]" style="width: 200px; height: 250px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20250%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_182c981dfc3%20text%20%7B%20fill%3A%23eceeef%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A13pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_182c981dfc3%22%3E%3Crect%20width%3D%22200%22%20height%3D%22250%22%20fill%3D%22%2355595c%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2256.20000076293945%22%20y%3D%22131%22%3EThumbnail%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>Sorry this page does not exist....</h2>
{% endif %}
{%endblock%}
I am confused it demands. can someone help me to solve it plz.
Its because you are querying it wrong:
So instaed of doing this:
# views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
Try something with this query. I'm supposing you want to query all the posts of a specific category that will be coming from your URL.
from django.shortcuts import get_object_or_404
def CategoryView(request, cats):
# method 1
category_posts = Post.objects.filter(category__title=cats)
# method 2
category = Category.objects.get(title=cats)
category_posts = category.Category.all() # here .Category is the related_name you used in your Post model
# method 3:
category = get_object_or_404(Category, title=cats) # will raise 404 if no category found with the given title
category_posts = category.Category.all()
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
PS: When you don't know what your ForeignKey related_name should be. Then go for the plural name of the model. Like in the current case:
# models.py
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="posts", null=True)
This way we can query like this category_posts = category.posts.all()

django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)'

I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items:
when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error:
NoReverseMatch at /watchlist/
Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$']
my code:
Model.py file
class Post(models.Model):
#data fields
title = models.CharField(max_length=64)
textarea = models.TextField()
#bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)
imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True)
creator = models.ForeignKey(User, on_delete=models.PROTECT)
date = models.DateTimeField(auto_now_add=True)
# for activated the Category
activate = models.BooleanField(default=True)
buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator")
############################### this is the watchers
watchers = models.ManyToManyField(User, blank=True, related_name='favorite')
def __str__(self):
return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}"
urls.py
urlpatterns =[
# Watchlist
path('Post/<int:id>/watchlist_post/change/<str:reverse_method>',
views.watchlist_post, name='watchlist_post'),
path('watchlist/', views.watchlist_list, name='watchlist_list')
path('Post/<int:id>', views.viewList, name='viewList'),
]
views.py
#start watchlist
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
if listing.watchers.filter(id=request.user.id).exists():
is_watched = True
else:
is_watched = False
context = {
'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'Bidform': BidForm(),
# IS_WATCHED method
'is_watched': is_watched
}
return render(request, 'auctions/item.html', context)
#login_required
def watchlist_post(requset, id, reverse_method):
listing = get_object_or_404(Post, id=id)
if listing.watchers.filter(id=requset.user.id).exists():
listing.watchers.remove(requset.user)
else:
listing.watchers.add(requset.user)
if reverse_method == "viewList":
return viewList(requset, id)
return HttpResponseRedirect(reverse(reverse_method))
#login_required
def watchlist_list(request):
user = requset.user
watchers_items = user.favorite.all()
context = {
'watchers_items': watchers_items
}
return render(requset, 'auctions/watchlist.html', context)
HTML FILE: (item.html) this file for showing the post for exapmple : (title/ description/ date etc..)
<!-- check to add to watchlist -->
<div class="col">
{% if is_watched %}
Remove To Watchlist
<!-- remove it -->
{% else %}
Add To Watchlist
{% endif %}
</div>
HTML FILE (layout.html) for adding a link to the navbar for the page
<li class="nav-item">
<a class="nav-link" href="{% url 'watchlist_list' %}">Watchlist</a>
</li>
HTML FILE(whitchlsit page)
{% for post in watchers_items %}
<div class="col-sm-4">
<div class="card my-2">
<img src="{{post.imageurl}}" class="img-fluid">
<div class="card-body">
<div class="text-center py-2">
<h5 class="card-title text-info">{{post.title}}</h5>
<p class="alert alert-info">{{post.textarea}}</p>
<ul class="list-group">
<li class="list-group-item list-group-item-info">category: {{post.category.name}}</li>
<li class="list-group-item list-group-item-info">Price: {{post.price}}$</li>
<li class="list-group-item list-group-item-info">Created by: {{post.creator}}</li>
</ul>
</div>
<!-- Buttons -->
<div class="row">
<div class="col">
View
</div>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Created since:{{post.date}}</small>
</div>
</div>
{% endfor %}
The culprit of this problem is that you are calling "{% url 'viewList' listing.id %}" even though viewList does not exist in your urls.py.
So, you can create one like this:
path("some/path", views.some_func, name="viewList")
EDIT
As the error says, listing.id is empty ({% url 'viewList' listing.id %}). So, you might want to do post.id instead because you are looping with the name of post.

Show data after dropdown selection

I am struggling with my code. I want to show data from a specific user on screen. When the second dropdown is selected with the user from a specific group, I want his records to be shown on screen. But what ever I try, the data stays the same from one user. In a later stadium I want to make an Else and say if there is no data, that there is no data of the person. Should I do something with a jquery, or is there an easier way to solve this?
The first dropdown is the group, the second dropdown the user.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class DisplayGroups(models.Model):
group_name = models.CharField(max_length=200)
def __str__(self):
return self.group_name
class DisplayUsername(models.Model):
username = models.CharField(max_length=100)
def __str__(self):
return self.username
class CijferLijst(models.Model):
name = models.CharField(max_length=200, default='')
vak1 = models.CharField(max_length=200, default='')
cijfer1 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0')
vak2 = models.CharField(max_length=200, default='')
cijfer2 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0')
username = models.ForeignKey(User, on_delete=models.CASCADE, default='')
def __str__(self):
return '%s %s %s %s %s %s'%(self.name, self.vak1, self.cijfer1, self.vak2, self.cijfer2, self.username)
bekijk.html
{% extends 'home/base.html' %}
{% block title %}Cijfers studenten{% endblock %}
{% block javascript %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var $select1 = $('#groupdd1'),
$select2 = $('#userdd1'),
$options = $select2.find('option');
$select1.on('change', function()
{
$select2.html($options.filter('[value="'+this.value+'"]'));
}).trigger('change');
});
</script>
{% endblock %}
{% block content %}
{% if user.is_staff %}
<h1>Studentresultaten</h1>
<select id="groupdd1">
<option disabled="true" selected>Kies een groep</option>
{% for result in DisplayGroups %}
<option>{{result}}</option>
{% endfor %}
</select>
<select id="userdd1">
<option disabled="true" selected>Kies een gebruiker</option>
{% for result in DisplayUsername %}
<option value="{{result.username}}">{{result}}</option>
{% endfor %}
</select>
{% endif %}
<br/>
{% for antwoord in CijferLijst %}
<h2>{{antwoord.name}}</h2>
<div class="container px-4">
<div class="row justify content-start gx-5">
<div class="col-5 border bg-light"><strong>Vaknaam</strong></div>
<div class="col-5 border bg-light"><strong>Cijfer</strong></div>
</div>
<div class="row gx-5 justify-content-start">
<div class="col-5 border bg-light">{{antwoord.vak1}}</div>
<div class="col-5 border bg-light">{{antwoord.cijfer1}}</div>
</div>
<div class="row gx-5 justify-content-start">
<div class="col-5 border bg-light">{{antwoord.vak2}}</div>
<div class="col-5 border bg-light">{{antwoord.cijfer2}}</div>
<div class="col-5 border bg-light">{{antwoord.username}}</div>
</div>
</div>
{% endfor %}
{% endblock %}
views.py
from django.shortcuts import render, redirect
from .models import DisplayGroups, DisplayUsername, CijferLijst
from .forms import Grades
from django.contrib.auth.models import User, Group
# Create your views here.
def index(request):
response = redirect('/login')
return response
def home(response):
return render(response, "home/home.html")
def bekijk(request):
DisplayGroup = Group.objects.all()
print(DisplayGroup)
DisplayNames = User.objects.all()
print(DisplayNames)
Cijfer = CijferLijst.objects.all()
print(Cijfer)
return render(request, "home/bekijk.html",
{"DisplayGroups": DisplayGroup, "DisplayUsername": DisplayNames, "CijferLijst": Cijfer})
def cijfers(request):
if request.method == "POST":
form = Grades(request.POST)
if form.is_valid():
form.save()
print(form)
return redirect('gelukt')
else:
form = Grades()
return render(request, "home/cijfers.html", {"form":form})
def done(response):
return render(response, "home/gelukt.html")
forms.py
from django import forms
from .models import CijferLijst
from django.contrib.auth.models import User
class Grades(forms.ModelForm):
name = forms.CharField(max_length=200)
vak1 = forms.CharField(max_length=200)
cijfer1 = forms.DecimalField(max_digits=3, decimal_places=1)
vak2 = forms.CharField(max_length=200)
cijfer2 = forms.DecimalField(max_digits=3, decimal_places=1)
username = forms.ModelChoiceField(queryset=User.objects.all())
check = forms.BooleanField()
class Meta:
model = CijferLijst
fields = ['name', 'vak1', 'cijfer1', 'vak2', 'cijfer2', 'username']
Thanks in advance.

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>

Categories