I made a blog app in which I want to add pagination both on home page and category page. but after a lot of efforts I didn't get how to use it in the category page. I use 2 parameters in category view and I don' know how to fix it now. whenever I click on category "That page number is not an integer" displays.
views.py:
def allpost(request):
postData = Post.objects.all()
paginator = Paginator(postData, 5) # Show 5 contacts per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'posts.html', {'page_obj': page_obj})
def CategoryView(request, cats='category__title'):
category_posts = Post.objects.all()
paginator = Paginator(category_posts, 5)
# We don't need to handle the case where the `page` parameter
# is not an integer because our URL only accepts integers
try:
category_posts = paginator.page('cats')
except EmptyPage:
# if we exceed the page limit we return the last page
category_posts = paginator.page(paginator.num_pages)
return render(request, 'categories.html', {'category_posts': category_posts})
urls.py:
path('category/<str:cats>/', views.CategoryView, name ="category"),
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 %}
{% include 'pagination.html' %}
{%endblock%}
pagination.html
<div class="container mt-3">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="/?page=1">First</a></li>
<li class="page-item"><a class="page-link" href="/?page={{ page_obj.previous_page_number }}">Previous</a></li>
{% endif %}
<li class="page-item"><a class="current" href="/?page={{ page_obj.number }} of {{ page_obj.paginator.num_pages }}">1</a></li>
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="/?page={{ page_obj.next_page_number }}">Next</a></li>
<li class="page-item"><a class="page-link" href="/?page={{lastpage}}">Last</a></li>
{% endif %}
</div>
I am very confused already in category views function to use parameter issue. so that I didn't use that code in pagination.html.
===== in view.py ======
from django.core.paginator import Paginator
def HomeView(request):
show_data = VehicleModel.objects.all() # Queryset For pagiantion
# Pagination code start
paginator = Paginator(show_data, 3, orphans=1)
page_number = request.GET.get('page')
show_data = paginator.get_page(page_number)
# Pagination code end
context = {'page_number':page_number}
return render(request,'dashboard.html',context)
===== in html file ======
<!-- Pagination Block with page number -->
<div class="container mt-5">
<div class="row float-right ">
<span class="m-0 p-0">
{% if carset.has_previous %} # <!-- For Previous Button -->
<a class="btn btn-outline-info" href="?page={{carset.previous_page_number}}&ok=#ok">Previous</a>
{% endif %}
<span>{% for pg in carset.paginator.page_range %} # <!-- For Page Numbers Buttons -->
{% if carset.number == pg %}
<a href="?page={{pg}}" class="btn btn-sm btn-primary">
<span class="badge">{{pg}}</span>
</a>
{% else %}
<a href="?page={{pg}}" class="btn btn-sm btn-secondary">
<span class="badge">{{pg}}</span>
</a>
{% endif %}
{% endfor %}</span>
{% if carset.has_next %} # <!-- For Next Button -->
<a class="btn btn-outline-info" href="?page={{carset.next_page_number}}&ok=#ok">Next</a>
{% endif %}
</span>
</div>
</div>
=========== Your code is like this ==============
here you passed the category parameter in the function so must pass the category title with the calling URL of this CategoryView(request, cats='category__title') function
def CategoryView(request, cats='category__title'):
category_posts = Post.objects.all()
paginator = Paginator(category_posts, 5)
with this CategoryView(request, cats='category__title') you want all Posts ???
def
CategoryView(request, cats='category__title'):
category_posts = Post.objects.filter(cats__title = cats)
paginator = Paginator(category_posts, 5)
ator = Paginator(category_posts, 5)
I'm pretty new to the Django backend framework. I have been able to easily query data, but now I'm trying to filter that data. When I run the application it will load the landing page and other pages, but when I try to naviagate to the FRReports page I get
"Error during template rendering
In template C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html, error at line 16
'webdart' is not a registered namespace"
Any ideas or guidance?
urls.py
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.DocRepositoryListView.as_view(), name='webdart-documents_FRReports'),
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'),
#path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
.
.
.
views.py
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
class DocRepositoryListView(ListView):
model = DocRepository
template_name = 'webdart/FRReports.html'
def get_context_data (self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset())
return context
class documents_FRReports(DetailView):
model = DocRepository
template_name = 'webdart/FRReports.html'
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', {'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
def data_mcv(request):
return render(request, 'webdart/mcvHTML.html');
def data_viewer(request):
return render(request, 'webdart/viewerHTML.html');
def data_multiSiteReport(request):
return render(request, 'webdart/multiSiteReport.html');
def documents_antennaBias(request):
pdfPath = DocRepository.objects.all()
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "RTS Range Bias":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
test = "reversed"
return render(request, 'webdart/antennaBias.html', {'pdfPath': pdfPath,'test': test, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#def documents_FRReports(request):
# return render(request, 'webdart/FRReports.html')
.
.
.
filters.py
import django_filters
from webdart.models import DocRepository
class DocRepositoryFilter(django_filters.FilterSet):
class Meta:
model = DocRepository
fields = ('file_location',)
models.py
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
def __str__(self):
return self.file_location
class Meta:
managed = False
db_table = 'doc_repository'
base.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/main.css' %}" />
<meta charset="utf-8">
<title>{% block title %}WeB DARt{% endblock %}</title>
<link rel="icon" href="{% static 'media/wd.png' %}" type="image/x-icon">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"></script>
<div class="CUI_banner_top">CUI</div>
</head>
<body class="test_margin" {% block data_status %}{% endblock %}>
<nav class="navbar navbar-expand-md bg_home ">
<div class="container-fluid ">
<div class="">
<div class="row aaa">
<img src="{% static 'media/logo.png' %}">
<!-- WeB DARt
<p class="nav_logo ">Web Based Data Analysis and Repository</p>
</div>
-->
</div>
</div>
<button class="navbar-toggler bg-light btn-sm py-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="text-dark bg-light h6">Menu</span>
</button>
<div class="collapse navbar-collapse px-4 nav_center" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="">
<a class="nav-link bg_home px-4 dropdown_hover" aria-current="page" href="{% url 'webdart-home' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link bg_home px-4 dropdown_hover" href="{% url 'webdart-data' %}">Data</a>
</li>
<div class="collapse navbar-collapse px-4 dropdown show ">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_documents()">Documents</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-documents_antennaBias' %}">Antenna Bias</a>
<a class="dropdown-item" href="{% url 'list' %}">F&R Reports</a>
<a class="dropdown-item" href="{% url 'webdart-documents_IERSBulletinA' %}">IERS Bulletin A</a>
<a class="dropdown-item" href="{% url 'webdart-documents_IERSBulletinB' %}">IERS Bulletin C</a>
<a class="dropdown-item" href="{% url 'webdart-documents_NRF' %}">NRF</a>
<a class="dropdown-item" href="{% url 'webdart-documents_OCNBandwidth' %}">OCN Bandwidth Limits</a>
<a class="dropdown-item" href="{% url 'webdart-documents_ONDLC' %}">ONDLC</a>
<a class="dropdown-item" href="{% url 'webdart-documents_ORL' %}">ORL</a>
<a class="dropdown-item" href="{% url 'webdart-documents_RAPID' %}">RAPID</a>
<a class="dropdown-item" href="{% url 'webdart-documents_SystemAvail' %}">System Availability</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_schedule()">Schedule</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-schedule_launch' %}">Launch Schedule</a>
<a class="dropdown-item" href="{% url 'webdart-schedule_maintenance' %}">Maintenance Schedule</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show test">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_support()">Support</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-support_help' %}">Help</a>
<a class="dropdown-item" href="{% url 'webdart-support_contact' %}">Contact</a>
<a class="dropdown-item"href="{% url 'webdart-support_networkRequest' %}">Network Request</a>
</div>
</div>
</ul>
</div>
Documents
Antenna Bias
F&R Reports
IERS Bulletin A
IERS Bulletin C
NRF
OCN Bandwidth Limits
ONDLC
ORL
RAPID
System Availability
FRReports.html
{% extends 'webdart/base.html' %}
{% load static %}
{% block title %} WeB DARt - Home {% endblock %}
{% block content %}
<div class="container " >
<div class="row" >
<div class="col-md-6 offset-md-4 my-5 ">
<h1 class="text-decoration-underline">
F&R Report Documents
<h1>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
</tr>
</table>
</div>
{{ filter.form }}
<ul>
{% for element in filter.qs %}
<li>
a{{ element.file_location }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I think that your error is in your template tag {% url 'webdart:detail' element.id %}. I believe that when you use the {% url %}, the first argument you give to it is the name of a path in your urlpatterns. If your link is trying to go to your path:
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports')
Then your template tag should be something like:
{% url 'webdart-documents_FRReports' element.id %}
Sadly, I wasn't able to get it working with the code originally used. I was able to do filtering within views.py:
"""
Views for webdart.
"""
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
def docRepo(request):
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
if request.method == "GET" and len(request.get_full_path().split("?")) > 1 and "page" not in request.get_full_path().split("?")[1]:
if "choice=date_newToOld" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
elif "choice=date_oldtoNew" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('date_on_doc')
elif "choice=date_range" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("&"))
greaterThanDate = request.get_full_path().split("&")[1].split("=")[1]
lessThanDate = request.get_full_path().split("&")[2].split("=")[1]
print("----------------" + greaterThanDate + lessThanDate)
pdfPath = DocRepository.objects.all().filter(date_on_doc__lte=lessThanDate)
pdfPath = pdfPath.filter(date_on_doc__gte=greaterThanDate)
pdfPath = pdfPath.order_by("-date_on_doc")
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "F and R Reports":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
return render(request, 'webdart/FRReports.html', {'pdfPath': pdfPath, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', {'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
And then I was able to manipulate that view within the template (I created a template below called document_static.html so I can just include it in the other document pages:
{% load static %}
<div class="container no_margin" >
<div class="row" >
<div class="pagination d-flex flex-row-reverse">
<span class="step-links ">
{% if contacts.has_previous %}
<a class="page_button" href="?page=1"><<</a>
<a class="page_button" href="?page={{ contacts.previous_page_number }}"><</a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}
</span>
{% if contacts.has_next %}
<a class="page_button" href="?page={{ contacts.next_page_number }}">></a>
<a class="page_button" href="?page={{ contacts.paginator.num_pages }}">>></a>
{% endif %}
<div class="show filter_div dropup">
<a class="filter_button" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">⩸</a>
<div class="dropdown-menu navDrop filter_drop" aria-labelledby="navbarDropdown">
<p>Sort by:</p>
<form method="GET">
<input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>
<label class="" for="date_newToOld">Date - New to old</label>
<br />
<input type="radio" id="date_oldtoNew" name="choice" value="date_oldtoNew" />
<label for="date_oldtoNew">Date - Old to new</label>
<br />
<input type="radio" id="date_range" name="choice" value="date_range" />
<label class="" for="date_range">Date range</label>
<div class="date_range">
<label class="" for="date_range">Start date</label>
<input type="date" id="start" name="date" value="{% now "Y-m-d" %}" min="2000-01-01" max="{% now "Y-m-d" %}">
<label class="" for="date_range">End date</label>
<input type="date" id="start" name="date" value="{% now "Y-m-d" %}" min="2000-01-01" max="{% now "Y-m-d" %}">
</div>
</select>
<div class="filter_button_submit_center">
<input class="filter_button_submit" type="submit" value="Filter">
</div>
</form>
</div>
</div>
</span>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
<th>Comments</th>
</tr>
<tr>
{% for o in contacts %}
{% if 0 < forloop.counter and forloop.counter < viewsPerPage %}
<td><a id="open" class="p-0 m-0 fw-bold doc_link">{{ o.title }} </a></td>
<td>{{ o.date_on_doc }}</td>
<td>
<button type="button" class="doc_comments_btn" data-toggle="modal" data-target="#antennaCommentBoxTest{{ forloop.counter0 }} ">Comments</button>
<div class="modal fade document_comment_modal" id="antennaCommentBoxTest{{ forloop.counter0 }}">
<div class="modal-dialog">
<div class="modal-content">
<div style="justify-content: center; display: block;" class="modal-header">
<button type="button" class="doc_comment_close_btn" data-dismiss="modal">×</button>
<h3 id="antennaCommentBoxTest{{ forloop.counter0 }}"><b style="font-size: 75%;">{{ o.title }} - Comments</b></h3>
</div>
<div class="modal-body">
<p class="doc_comment_feed" id="commentFeed">This document has no comments yet.</p>
<form>
<textarea id="newCommentBlock" rows="5" class="doc_comment_textarea" placeholder="Add a Comment" required></textarea>
<br><button type="button" class="doc_comment_submit_btn" onclick="postComment()">Post</button><br>
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</table>
</div>
</div>
Here is a document page (IERSBulletinA.html):
{% extends 'webdart/base.html' %}
{% load static %}
{% block title %} WeB DARt - Home {% endblock %}
{% block content %}
<div class="container " >
<div class="row " >
<div class="col-md-6 offset-md-4 my-5">
<h1 class="text-decoration-underline">IERS Bulletin A Documents<h1>
</div>
</div>
</div>
{% include "webdart/document_static.html" %}
{% endblock %}
And here is urls.py for anybody interested:
"""
Definition of urls for webdart.
"""
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
from django.views.generic import ListView, DetailView
from django.views import View
from .models import DocRepository
from django.http import HttpResponse
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.docRepo, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
path('IERSBulletinB/', views.documents_IERSBulletinB, name='webdart-documents_IERSBulletinB'),
path('NRF/', views.documents_NRF, name='webdart-documents_NRF'),
path('OCNBandwidth/', views.documents_OCNBandwidth, name='webdart-documents_OCNBandwidth'),
path('ONDLC/', views.documents_ONDLC, name='webdart-documents_ONDLC'),
path('ORL/', views.documents_ORL, name='webdart-documents_ORL'),
path('RAPID/', views.documents_RAPID, name='webdart-documents_RAPID'),
path('SystemAvail/', views.documents_SystemAvail, name='webdart-documents_SystemAvail'),
path('launch/', views.schedule_launch, name='webdart-schedule_launch'),
path('maintenance/', views.schedule_maintenance, name='webdart-schedule_maintenance'),
path('help/', views.support_help, name='webdart-support_help'),
path('contact/', views.support_contact, name='webdart-support_contact'),
path('networkRequest/', views.support_networkRequest, name='webdart-support_networkRequest'),
path('accountDetails/', views.user_accountDetails, name='webdart-user_accountDetails'),
path('signOut/', views.user_signOut, name='webdart-user_signOut'),
path('timeOut/', views.user_timeOut, name='webdart-user_timeOut'),
path('accountRequest/', views.user_accountRequest, name='webdart-user_accountRequest'),
path('', AboutView.as_view(template_name="data-stationData")),
]
And an excerpt from models.py too, because why not:
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
class Meta:
managed = False
db_table = 'doc_repository'
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 %}```
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()