Django templates don't show my all parameters - python

I have problem. I want create relationship in model Django. I would like every user to have a different product price. The product must be assigned to the user. It must is to display only after logging in. Unfortunately, the template does not show all parameters.
offers/models.py
class Product(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=50)
weight = models.FloatField()
description = models.TextField(blank=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
is_published = models.BooleanField(default=True)
list_date = models.DateField(default=datetime.now, blank=True)
def __str__(self):
return self.title
class UserProduct(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
price = models.FloatField()
is_published = models.BooleanField(default=True)
list_date = models.DateField(default=datetime.now, blank=True)
def __str__(self):
return str(self.user.username) if self.user.username else ''
Products are to be displayed for logged in users.
offers/views.py
def index(request):
context = {
'products': Product.objects.order_by('category').filter(is_published=True)
}
return render(request, 'offers/products.html', context)
def userproduct(request):
context = {
'userproduct': UserProduct.objects.filter(user_id=request.user.id),
'userproduct1': Product.objects.all()
}
return render(request, 'offers/userproducts.html', context)
My template show only title, and price.
offers/userproducts.html
<!-- Offers -->
<section class="text-center mb-4 py-4">
<div class="container">
<div class="row">
{% if user.is_authenticated %}
{% if userproduct %}
{% for product in userproduct %}
<!--Grid column-->
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="{{ product.photo.url }}" class="card-img-top" alt="">
<a href="{% url 'product' product.id %}">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<h6 class="grey-text">{{ product.category }}</h6>
<h5>
<strong>
{{ product.title }}
</strong>
</h5>
<h4 class="font-weight-bold colores">
<strong>{{ product.price }}</strong>
</h4>
</div>
</div>
</div>
<!--Grid column-->
{% endfor %}
{% else %}
<div class="col-sm-12 sm-12">
<p>No Products Available XD</p>
</div>
{% endif %}
{% endif %}
</div>
</div>
</section>

The userproduct queryset that you are iterating over belongs to UserProduct model which doesn't have the fields you're looking for.
This is how it should be:
<!-- Offers -->
<section class="text-center mb-4 py-4">
<div class="container">
<div class="row">
{% if user.is_authenticated %}
{% if userproduct %}
{% for product in userproduct %}
<!--Grid column-->
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="{{ product.title.photo.url }}" class="card-img-top" alt="">
<a href="{% url 'product' product.title.id %}">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<h6 class="grey-text">{{ product.title.category }}</h6>
<h5>
<strong>
{{ product.title.title }}
</strong>
</h5>
<h4 class="font-weight-bold colores">
<strong>{{ product.price }}</strong>
</h4>
</div>
</div>
</div>
<!--Grid column-->
{% endfor %}
{% else %}
<div class="col-sm-12 sm-12">
<p>No Products Available XD</p>
</div>
{% endif %}
{% endif %}
</div>
</div>
</section>
If you need a field from Product model, you should get the Product instance which is title. So:
Price: product.price
Title: product.title.title (product.title also works because of your __str__ function.)
Category: product.title.category
Photo: product.title.photo
And so on ...

Related

How can I display in the chat list those with whom I corresponded earlier?

I have a chat code in which I want to display and suggest only those users with whom there has already been a correspondence, that is, both incoming and outgoing messages, and not all registered users.
html code:
<div class="container" style="height: 75%;">
<div class="card bg-dark h-100 border-light">
<div class="card-body h-100">
<div class="row h-100">
<div class="col-md-4 border-right h-100">
<div class="list-group bg-dark" id='user-list'>
{% for u in users %} {% if not u.id == 1 and not u.id == user.id %}
<a class="list-group-item {% if u.id != chat_id %}bg-dark{% else %}bg-primary{% endif %} text-white" href="{% url 'chat-home' %}?u={{u.id}}">
<div>
<p>{{u.first_name}} {{u.last_name}} ({{u.username}})</p>
</div>
</a>
{% endif %} {% endfor %}
</div>
</div>
<div class="col-md-8 h-100">
{% if not chat_id > 0 %}
<div class="h-100 d-flex flex-column justify-content-center align-items-center">
<h3>Начните общение!</h3>
<p><small class="text-muted">Выберете человека, чтобы написать ему.</small></p>
</div>
{% else%}
<div id="chat-box-field" class="h-100">
<div class="chat-box" style="height:80%">
{% for chat in chats %} {% if chat.user_from == user %}
<div class="p-2 w-100 d-flex justify-content-end">
<div class=" chat-bubble ml-2 mb-2 bg-primary text-light rounded" data-id="{{chat.id}}">
<p>{{chat.message}}</p>
<div class="d-flex justify-content-between"><small>Ты</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
</div>
</div>
{% else %}
<div class="p-2 w-100 d-flex justify-content-start">
<div class="chat-bubble mr-2 mb-2 bg-light text-dark rounded" data-id="{{chat.id}}">
<p>{{chat.message}}</p>
<div class=" d-flex justify-content-between"><small>От</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
</div>
</div>
{% endif %} {% endfor %}
</div>
<div class="chat-box-form border-top p-2" style="height:20%">
<div class="w-100 h-100">
<form action="" id="chat-submit" class="h-100 d-flex ">
<input type="hidden" name="user_from" value="{{ user.id }}">
<input type="hidden" name="user_to" value="{{ chat_id }}">
<div class="col-md-10 h-100">
<textarea name="message" id="" class="h-100 w-100 form-control" placeholder="Написать"></textarea>
</div>
<button class="button btn btn-primary h-100 w-100 justify-content-center align-items-center d-flex">Отправить</button>
</form>
</div>
</div>
</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
views.py:
def get_messages(request):
chats = chatMessages.objects.filter(Q(id__gt=request.POST['last_id']),Q(user_from=request.user.id, user_to=request.POST['chat_id']) | Q(user_from=request.POST['chat_id'], user_to=request.user.id))
new_msgs = []
for chat in list(chats):
data = {}
data['id'] = chat.id
data['user_from'] = chat.user_from.id
data['user_to'] = chat.user_to.id
data['message'] = chat.message
data['date_created'] = chat.date_created.strftime("%b-%d-%Y %H:%M")
print(data)
new_msgs.append(data)
return HttpResponse(json.dumps(new_msgs), content_type="application/json")
def send_chat(request):
resp = {}
User = get_user_model()
if request.method == 'POST':
post =request.POST
u_from = UserModel.objects.get(id=post['user_from'])
u_to = UserModel.objects.get(id=post['user_to'])
insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'])
try:
insert.save()
resp['status'] = 'success'
except Exception as ex:
resp['status'] = 'failed'
resp['mesg'] = ex
else:
resp['status'] = 'failed'
return HttpResponse(json.dumps(resp), content_type="application/json")
models.py:
class chatMessages(models.Model):
user_from = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="+")
user_to = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="+")
message = models.TextField()
date_created = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.message
Please tell me how it can be implemented. I don't quite understand how to set a condition for checking for messagesm
You probably need to change the related name first on the model:
class chatMessages(models.Model):
user_from = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="sent")
user_to = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="received")
message = models.TextField()
date_created = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.message
And then to get all messages the user has received:
messages = request.user.received.all()
(Or User.objects.get(id=my_user_id).received.all())
To get all the users which the user has corresponded with, you can then do:
pk_list = messages.values("user_from__pk").distinct()
correspondents = get_user_model().objects.filter(pk__in=list(pk_list))
Sidenote:
In your views, you are getting the user model.
User = get_user_model()
But you don't do anything with it in this view:
def send_chat(request):

How to combine multiple models into one view template in django

I have two models
class Post(models.Model):
title = models.CharField(max_length=100)
body = RichTextField(max_length=1000000)
created_at = models.DateTimeField(default=datetime.now, blank = True)
image = ResizedImageField(size=[250, 200], upload_to='img')
and
class Politics(models.Model):
title = models.CharField(max_length=100)
body = RichTextField(max_length=1000000)
created_at = models.DateTimeField(default=datetime.now, blank = True)
image = ResizedImageField(size=[250, 200], upload_to='img',blank = True)
I want to combine them both into one template view and render them on the index.html
Here is my view function
def index(request):
politics = Politics.objects.all()
return render(request,
'index.html',
{'politics':politics, 'posts': Post.objects.all()})
index.html (posts part)
<section id="posts" class="posts">
<div class="container" data-aos="fade-up">
<div class="row g-5">
{% for post in posts reversed %}
{% if forloop.counter < 5 %}
<div class="post-entry-1 col-lg-2 box mx-1">
<img src="{{post.image.url}}" class="post_img">
<div>
<div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_at}}</span></div>
<h2>{{post.title}}</h2>
</div>
<p class="mb-4 d-block">{{post.body|truncatewords:75}}</p>
<div class="d-flex align-items-center author">
<div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div>
<div class="name">
<h3 class="m-0 p-0">OlePundit</h3>
</div>
</div>
</div>
(politics part)
<div class="row">
{% for politic in politics%}
{% if forloop.counter < 11 %}
<div class="post-entry-1 col-2 mx-1">
<img src="{{politic.image.url}}" alt="" class="post_img">
<div class="post-meta">
<span class="date">{{politic.category}}</span>
<span class="mx-1">&bullet;</span>
<span>{{politic.created_at}}</span>
</div>
<h2 class="mb-2">{{politic.title}}</h2>
<span class="author mb-3 d-block">Ole Pundit</span>
<p class="mb-4 d-block">{{politic.body| safe | truncatewords:20}}</p>
</div>
{% endif %}
{% endfor %}
</div>
However, only the 'politics' object is being rendered. What could be wrong?
try this or the problem will be in template file
def index(request):
politics = Politics.objects.all()
posts = Post.objects.all()
return render(request,
'index.html',
{'politics':politics, 'posts': posts})

How to filter data in django template?

i have a django model as follows in which i defined categories
CATEGORY_CHOICES = (
('BS', 'Best Selling'),
('TP', 'Trending Product'),
('RP', 'Related Products'),
('NA', 'New Arrival'),
('F', 'Featured'),
('OS', 'on sale'),)
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("core:product", kwargs={
'slug': self.slug
})
def get_add_to_cart_url(self):
return reverse("core:add-to-cart", kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse("core:remove-from-cart", kwargs={
'slug': self.slug
})
**and in my Django home page there are multiples sections based on categories like trending product, on sale, featured, new arrivals etc ** what I wanted is to filter data based on that categories and show to the respective section and for that, I registred a template as follows:
#register.filter
def in_category(Item, category):
return Item.filter(category=category)
and on my home template i tried to use this filter as follows:
{% for object_list in object_list|in_category:Featured %}
<div class="col-3">
<div class="custom-col-5">
<div class="single_product">
<div class="product_thumb">
<a href="{{ item.get_absolute_url }}" class="primary_img"><img src="{{ item.image.url }}"
alt="product1"></a>
<a href="{{ item.get_absolute_url }}" class="secondary_img"><img src="{{ item.image.url }}"
alt="product1"></a>
<div class="quick_button">
<a href="{{ item.get_absolute_url }}" data-toggle="modal" data-target="#modal_box"
data-placement="top" data-original-title="quick view">Quick
View</a>
</div>
</div>
<div class="product_content">
<div class="tag_cate">
Ring, Necklace,
Earrings
</div>
<h3>{{ item.title }}</h3>
<div class="price_box">
<span class="old_price">Rs. 45654</span>
<span class="current_price">{% if item.discount_price %}
{{ item.discount_price }}
{% else %}
{{ item.price }}
{% endif %}</span>
</div>
<div class="product_hover">
<div class="product_ratings">
<ul>
<li><i class="ion-ios-star-outline"></i>
</li>
<li><i class="ion-ios-star-outline"></i>
</li>
<li><i class="ion-ios-star-outline"></i>
</li>
<li><i class="ion-ios-star-outline"></i>
</li>
<li><i class="ion-ios-star-outline"></i>
</li>
</ul>
</div>
<div class="product_desc">
<p>This is a gold ring with diamond and Lorem ipsum
dolor sit amet.</p>
</div>
<div class="action_links">
<ul>
<li><a href="#" data-placement="top" title="Add to Wishlist" data-toggle="tooltip"><span
class="ion-heart"></span></a></li>
<li class="add_to_cart"><a href="#" title="Add to Cart">Add
to Cart</a></li>
<li><i class="ion-ios-settings-strong"></i>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
but django says it is an error VariableDoesNotExist at /
Failed lookup for key [Featured] in
can sombody help me with this thanks in advance.
You can use simple for loop and condition
{% if item.category == "Featured" %}
---------html for featured categ---
{% endif %}
{% if item.category == "onsale" %}
---------html for onsale categ---
{% endif %}
.
.
.
{% endfor %}```

Please how can get the number of listings in a category, i have tried

I have a django app and I need to count the number of listings in a category (as defined by the models below):
here is my complete model
class Category(models.Model):
name = models.CharField(max_length=500)
icon = models.ImageField(upload_to='photos/icons/%Y/%m/%d/')
def __str__ (self):
return self.name
class Listing(models.Model):
name = models.CharField(max_length=300)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=False, null=True)
email = models.EmailField(max_length=300)
description = RichTextField(blank=False, null=False)
photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/')
photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
location = models.CharField(max_length=500, null=True)
phone_number = models.CharField(max_length=11, default = "#")
website = models.CharField(max_length=150, blank=True, default="#")
facebook = models.CharField(max_length=150, blank=True, default="#")
instagram = models.CharField(max_length=150, blank=True, default="#")
opening_time = models.CharField(max_length=7)
closing_time = models.CharField(max_length=7)
is_published = models.BooleanField(default=False)
posted_date = models.DateTimeField(auto_now_add=True)
user_id = models.IntegerField(blank=True)
def __str__ (self):
return self.name
here are my views
from django.shortcuts import render
from listings.models import Listing
from listings.models import Category
from testimonies.models import Testimony
from our_team.models import Team_Mate
from testimonies.models import Testimony
from django.db.models import Count
def index(request):
this part is working perfectly.
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
category = request.GET.get('category')
categories = Category.objects.all()[:7]
counting listings in a category
count_cate = Category.objects.all()
cate_count = count_cate.count()
if category == None:
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
else:
listings = Listing.objects.filter(Category__name=category)
here is my context
context ={
'listings': listings,
'categories': categories,
'cate_count': cate_count,
}
return render(request, 'pages/index.html', context)
Here is my html where I want the number of listings in category to show
{% extends 'base.html' %}
{% load static %}
{% block content %}
<!-- ======= Intro Section ======= -->
<div class="header">
<div class="header-content display-table">
<div class="table-cell">
<div class="container">
<h1 class="header-title text-light text-uppercase pb-3">Explore Bonny Island</h1>
<h3 class="text-light">Find. Connect. Share</h3>
<div class="search mt-3 px-0 py-1 mx-0">
<form action="{% url 'search' %}" method="GET">
{% csrf_token %}
<div class="row d-flex justify-content-center container p-0 m-0 px-1">
<input type="text" name="keywords"
class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5"
placeholder=" Keyword">
<input type="text" name="location"
class="form-control col-lg-3 col-md-12 mx-2 py-4 col-sm-12 my-2 border border-5"
placeholder=" Location">
<input type="text" name="category" value="{{ query }}" list="category"
class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5"
placeholder=" Category (All)">
<datalist id="category">
{% for categories in categories %}
<option>{{ categories.name }}</option>
{% endfor %}
</datalist>
<button type="submit"
class="btn search-bt col-lg-2 col-md-12 mx-2 col-sm-12 py-2 px-2 font-weight-bold my-
2">Search</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div><!-- End Intro Section -->
<!-- ======== most popular categories ========= -->
<section class="main">
<div class="discover pb-1 m-0">
<h2>Explore Categories</h2>
<div class="container">
<div class="row justify-content-around m-0 p-0 pt-3">
{% for category in categories %}
{% if category %}
<div class="col-lg-3 col-md-6 py-2">
<a href="{% url 'listings' %}?category={{ category.name }}" class="card category">
<div class="d-flex justify-content-between align-items-start px-3 m-0 py-2">
<div class="category-name-icon p-0 m-0">
<span class="text-dark font-weight-bold"><img class="category-icon" src="{{
category.icon.url }}">
{{category.name}}</span>
</div>
<div class="category-list-number text-muted font-weight-bold">{{cate_count}}</div>
</div>
</a>
</div>
{% endif %}
{% endfor %}
<div class="col-lg-3 col-md-6 py-2">
<a href="{% url 'category' %}" class="card category" data-bs-toggle="collapse"
href="#collapseExample"
role="button" aria-expanded="false" aria-controls="collapseExample">
<div class="d-flex justify-content-between = px-3 m-0 py-2">
<i class="font-weight-bold py-1 text-secondary">More Categories...</i>
</div>
</a>
</div>
</div>
</div>
</section> <!-- ======== most popular categories end ======== -->
<!-- STRUCTURING THE POPULAR LISTINGS CONTENT-->
<section id="popularListings" class="container mb-5 py-5">
<!-- Popular listenings head title-->
<div class="sectionTitle d-flex justify-content-between align-items-baseline">
<div class="mainTitleContents">
<h2 class="titleText h2 text-blue">Popular Listings</h2>
<p class="subTitleText mb-2">Explore businesses on the island.</p>
</div>
<div class="filterOption">
All Listings
</div>
</div>
<!-- MAIN POPULAR LISTINGS ROW CONTENT-->
<div class="popularListingsRows row py-2">
{% if listings %}
{% for listing in listings %}
<div class="customCard p-1 m-0 col-lg-3 col-md-4 col-sm-6 mt-sm-3">
<div class="card">
<div class="card-header p-0">
<div class="blank rounded" style="background-image: url('{{
listing.photo_main.url }}'); background-repeat: no-repeat;
background-size:cover; width:100%; height: 15em; background-
position:center-top" ;></div>
</div>
<div class="card-body">
<div class="content-details">
<h3 class="m-0 mt-1 mb-2 cardTitle">{{ listing.name }}</h3>
<p class="cardSubTitle">
{%autoescape off%}
{{ listing.description|striptags|truncatechars:100 }}
{%endautoescape%}
</p>
<a href="{% url 'listing' listing.id %}" class="btn btn-sm bg-blue text-
light rounded-none">Read More</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p class="text-dark">No listings Available</p>
</div>
{% endif %}
</div>
</section>
{% endblock %}
How can I make this code work as intended?
You should call the count method on the list of objects like...
if category == None:
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
else:
listings = Listing.objects.filter(category__name=category).count()
Please ensure where you have Category__name=category you must allow this to match your model field category.
In your html:
<!-- ======= Intro Section ======= -->
<form action="{% url 'search' %}" method="GET">
{% csrf_token %}
<div class="row d-flex justify-content-center container p-0 m-0 px-1">
...
<!--<input type="text" name="category" value="{{ query }}" list="category" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)">-->
<!-- Remove value="{{ query }}" -->
<input type="text" name="category" list="categories" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)">
<!-- Should be category in categories instead of categories in categories -->
<datalist id="categories">
{% for category in categories %}
<option value="{{ category.name }}"> <!-- Setting the value here... -->
{% endfor %}
</datalist>
...
</div>
</form>
I solved the it by calling the name of the category i want to count but am still to look for a way to count it without specifying the category name.
cate_count = Listing.objects.filter(category__name="Catering services").count()

Django Adding Pagination To Search Form Page

How do I add pagination to this form's search functionality?
By default, on page refresh, the HTML template for loop shows all the results for all the courses. When the user types in criteria into the form, the form filters the course results template for loop based on what the user typed. Is there a way on page refresh to show only a set limit of course results on the page instead of all of them? Then when a user searches/filters, that pagination limit of X number of course results on a page will still need to show but still applied to the search criteria/filter.
HTML:
<form id='courseform' action="." method="get">
<div class="form-row">
<div class="form-group col-12"> {{ form.title__icontains }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__gte.label_tag }} {{ form.visited_times__gte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__lte.label_tag }} {{ form.visited_times__lte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.created_at__gte.label_tag }} {{ form.created_at__gte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.created_at__lte.label_tag }} {{ form.created_at__lte }} </div>
<div class="form-group col-md-2"> {{ form.skill_level.label_tag }} {{ form.skill_level }} </div>
<div class="form-group col-md-2"> {{ form.subjects.label_tag }} {{ form.subjects }} </div>
</div>
<script src='https://www.google.com/recaptcha/api.js?render=6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N'></script>
<div class="g-recaptcha" data-sitekey="6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N"></div>
<button type="submit" class="btn btn-primary form-control">Search</button>
<p>This site is protected by reCAPTCHA and the Google
<a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/privacy">Privacy Policy</a> and
<a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/terms">Terms of Service</a> apply.
</p>
</form>
<!--Used to have {{ object.subjects }} next to -->
{% for object in object_list %}
<a class="course_list_link" href="{{ object.get_absolute_url }}"> <p class = "course_list_border"> <strong> {{ object }} </strong> <br/> <br/> {{ object.description }} <br/><br/> {{ object.skill_level }}   {{ object.created_at }}   Views: {{ object.visited_times }}  
{% for sub in object.subjects.all %}
{{ sub.name }}
{% endfor %} </p> </a>
{% endfor %}
Views.py:
class CourseListView(ListView):
template_name = 'courses/course_list.html'
​
def get_queryset(self):
return Course.objects.all()
​
def get(self, request, *args, **kwargs):
form = CourseForm(request.GET)
queryset = self.get_queryset()
if form.is_valid():
queryset = queryset.filter(**{k: v for k, v in form.cleaned_data.items() if v})
self.object_list = queryset
return self.render_to_response(self.get_context_data(form=form,object_list=queryset,))
Forms.py:
class CourseForm(forms.Form):
title__icontains = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control col-12', 'autocomplete':'off', 'id':'title_contains', 'type':'search', 'placeholder': 'Course Name'}), required=False)
visited_times__gte = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'view_count_max', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)])
visited_times__lte = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'view_count_min', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)])
created_at__gte = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'date_max','type':'date', 'placeholder': 'mm/dd/yyy'}), required=False)
created_at__lte = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'date_min', 'type':'date', 'placeholder': 'mm/dd/yyy'}), required=False)
skill_level = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'skill_level'}), choices = ([('',''), ('Beginner','Beginner'), ('Intermediate','Intermediate'),('Advanced','Advanced'), ]), required=False)
subjects = forms.ModelChoiceField(queryset=Subject.objects.all().order_by('name'), empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'subjects'}), required=False)
# the new bit we're adding
def __init__(self, *args, **kwargs):
super(CourseForm, self).__init__(*args, **kwargs)
self.fields['title__icontains'].label = "Course Name:"
self.fields['visited_times__gte'].label = "Min Views:"
self.fields['visited_times__lte'].label = "Max Views:"
self.fields['created_at__gte'].label = "Min Date:"
self.fields['created_at__lte'].label = "Max Date:"
self.fields['skill_level'].label = "Skill Level:"
self.fields['subjects'].label = "Subject:"
self.fields['subjects'].queryset = Subject.objects.filter()
Models.py:
class Subject(models.Model):
SUBJECT_CHOICES = ()
name = models.CharField(max_length=20,choices=SUBJECT_CHOICES)
def __str__(self):
return self.name
​
class Meta:
ordering = ('name',)
​
class Course(models.Model):
​
SKILL_LEVEL_CHOICES = (
('Beginner', 'Beginner'),
('Intermediate', 'Intermediate'),
('Advanced', 'Advanced'),
)
​
slug = models.SlugField()
title = models.CharField(max_length=120)
description = models.TextField()
allowed_memberships = models.ManyToManyField(Membership)
created_at = models.DateTimeField(auto_now_add=True)
subjects = models.ManyToManyField(Subject)
skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True)
visited_times = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('courses:detail', kwargs={'slug': self.slug})
#property
def lessons(self):
return self.lesson_set.all().order_by('position')
​
class Meta:
ordering = ('title',)
I tried following some tutorials Django docs one but not sure how to embed that pagination code to mine.
https://docs.djangoproject.com/en/3.0/topics/pagination/
I would appreciate if anyone could help me with this.
Please edit to include your code.
In the page you linked to, read this section:
https://docs.djangoproject.com/en/3.0/topics/pagination/#paginating-a-listview
You just need to add this to your ListView
paginate_by = N
then add
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
next
last »
{% endif %}
</span>
</div>
to course_list.html.
Serach form (html) :
<!-- Search Form -->
<form class="navbar-search navbar-search-dark form-inline mr-3 d-none d-md-flex ml-lg-auto" action="{% url 'search' %}" method="get">
<div class="form-group mb-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search Tasks" aria-label="Search" name="q">
<button class="btn btn-outline-white my-2 my-sm-0" type="submit">Search</button>
</div>
</form>
views.py
class SearchView(ListView): # taskları arama sonucu listeliyoruz
model = Task
template_name = 'task/search.html'
paginate_by = 5
context_object_name = 'task'
def get_queryset(self):
query = self.request.GET.get("q")
if query:
return Task.objects.filter(
Q(title__icontains=query) | Q(content__icontains=query) | Q(tag__title__icontains=query)).order_by(
'id').distinct()
return Task.objects.all().order_by('id')
In whichever field you want to use pagination, write the code there (example category_detail.html) :
<div class="card-footer py-4">
{% if is_paginated %}
<nav aria-label="...">
<ul class="pagination justify-content-end mb-0">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active">
<a class="page-link" href="#"> {{ i }} </a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?page={{ i }}">{{ i }}<span class="sr-only">(current)</span></a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
I hope the examples worked for you.

Categories