the goal of my code is to make a school management system where the admin can log in and add teachers to their respective classes that they are leading and be able to add students to their respective classes and then take the attendance of those students present on any given day. however, I am having an issue where the form to add the student to the class isn't rendering when I click on the add student button. I have been searching but can't seem to find the error in my code, I am new to Django so any help will be appreciated. the closest I got was to make the modal show up but the fields to select the student from to add to the class wasn't showing
models
class Teacher(models.Model):
first_name = models.CharField(max_length=60, blank=False, null=False)
last_name = models.CharField(max_length=80, blank=False, null=False)
address = models.CharField(max_length=120, blank=True, null=True)
contact = models.CharField(max_length=10, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
birth = models.CharField(max_length=20, blank=True, null=True)
gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True)
comment = models.TextField(max_length=10000, blank=True, null=True)
def __str__(self):
return f"{self.first_name + ' ' + self.last_name}"
class Student(models.Model):
student_code = models.CharField(max_length=250, blank=True, null=True)
first_name = models.CharField(max_length=20, blank=False, null=False)
last_name = models.CharField(max_length=20, blank=False, null=False)
address = models.CharField(max_length=120, blank=True, null=True)
contact = models.CharField(max_length=10, blank=True, null=True)
admission = models.CharField(max_length=20, blank=True, null=True)
birth = models.CharField(max_length=20, blank=True, null=True)
parents = models.CharField(max_length=200, blank=False)
gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True)
comment = models.TextField(max_length=10000, null=True, blank=True)
passport = models.ImageField(null=True,blank=True, default='default.png', upload_to="profile/")
def __str__(self):
return f"{self.first_name + ' ' + self.last_name}"
def save(self, *args, **kawrgs):
super().save(*args, **kawrgs)
img = Image.open(self.passport.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.passport.path)
class Room(models.Model):
form_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
school_year = models.CharField(max_length=250)
level = models.CharField(max_length=250)
name = models.CharField(max_length=250)
def __str__(self):
return "[" + self.level + "] " + self.level + '-' + self.name
class ClassStudent(models.Model):
classIns = models.ForeignKey(Room, on_delete=models.CASCADE)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
def __str__(self):
return self.student.student_code
def get_present(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(
classIns=_class, student=student, type=1).count()
return present
except:
return 0
def get_tardy(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(
classIns=_class, student=student, type=2).count()
return present
except:
return 0
def get_absent(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(classIns= _class, student=student, type = 3).count()
return present
except:
return 0
class Attendance(models.Model):
classIns = models.ForeignKey(Room, on_delete=models.CASCADE, default=' ')
student = models.ForeignKey(Student, on_delete=models.CASCADE, default=' ')
attendance_date = models.DateField(default=' ')
type = models.CharField(max_length=250, choices=[(
'1', 'Present'), ('2', 'Tardy'), ('1', 'Absent')], default=' ')
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.classIns.name + " " + self.student.student_code
views
# create a classroom
login_required()
def class_view(request):
form = ClassRoomForm()
if request.method == 'POST':
form = ClassRoomForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data.get('name')
messages.success(request, f'{name} was Successfully Added')
return redirect('classroom')
classes = Room.objects.all()
return render(request, 'school/class_view.html', {"form": form, 'classes': classes})
#show all the classroom created
#login_required
def class_detail(request,pk):
_class = Room.objects.filter(id=pk).first()
students = ClassStudent.objects.filter(classIns =_class).all()
print(students)
context = {
'class': _class,
'students': students
}
return render(request, "school/class_info.html", context)
#passes the form responsible for adding student to the classroom
#login_required
def save_class_student(request):
form = SaveClassStudent()
if request.method == 'POST':
form = SaveClassStudent(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Student has been added successfully.")
redirect('class_detail')
return render(request, 'school/class_info.html', {'form': form})
forms
class ClassRoomForm(forms.ModelForm):
school_year = forms.CharField(max_length=250,help_text = "School Year Field is required.")
level = forms.CharField(max_length=250,help_text = "Level Field is required.")
name = forms.CharField(max_length=250,help_text = "Class Name Field is required.")
class Meta:
model = Room
fields = ('form_teacher', 'name', 'level', 'school_year')
class SaveClassStudent(forms.ModelForm):
classIns = forms.IntegerField()
student = forms.IntegerField()
class Meta:
model = ClassStudent
fields = ('classIns', 'student')
def clean_classIns(self):
cid = self.cleaned_data['classIns']
try:
classIns = Room.objects.get(id=cid)
return classIns
except:
raise forms.ValidationError("Class ID is Invalid.")
def clean_student(self):
student_id = self.cleaned_data['student']
_class = Room.objects.get(id=self.data.get('classIns'))
student = Student.objects.get(id=student_id)
try:
cs = ClassStudent.objects.get(classIns=_class, student=student)
if len(cs) > 0:
raise forms.ValidationError(
f"Student already exists in the Class List.")
except:
return student
HTML template for the form
{% extends 'school/dashboard.html' %}
{% load static %}
{% load widget_tweaks %}
{% load humanize %}
{% block title%}
<title>Class Information</title>
{% endblock %}
{% block page%}Class Info{% endblock %}
{% block card%} {%endblock%}
{% block table %}
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card card-default rounded-0 shadow ">
<div class="card-header">
<div class="d-flex w-100 align-items-center justify-content-between">
<h4 class="card-title fw-bold">Class Information</h4>
<div class="tools">
<button type="button" class="btn btn-secondary border rounded-0 bg-gradient btn-sm"
id='print_attendance_report'><i class="fa fa-print"></i> Print Attendance Report</button>
<a href="#addModal" data-bs-toggle="modal"> <button type="button" class="btn btn-primary rounded-0 bg-gradient btn-sm" id='add_new'><i
class="fa fa-plus"></i> Add Student</button></a>
</div>
</div>
</div>
<div class="card-body">
<div class="container-fluid">
<fieldset id="class-details">
<legend>Class Details</legend>
<div class="row">
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">School Year:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.school_year }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Level:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.level }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Name:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.name }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Faculty:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.form_teacher}}</p>
</div>
</div>
</div>
</div>
</fieldset>
<hr>
<fieldset>
<legend>Class Student List</legend>
<table class="table tables-bordered" id="student-list">
<colgroup>
<col width="10%">
<col width="25%">
<col width="25%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
</colgroup>
<thead>
<tr>
<th class="text-ceter">#</th>
<th class="text-ceter">Student Code</th>
<th class="text-ceter">Student Name</th>
<th class="text-ceter">Total Tardy</th>
<th class="text-ceter">Total Absent</th>
<th class="text-ceter">Total Present</th>
<th class="text-ceter">Actions</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr class="">
<td class="text-center">{{ forloop.counter }}</td>
<td>{{ student.student.student_code }}</td>
<td>{{ student.student.first_name }} {{student.student.last_name }}</td>
<td class="text-center">{{ student.get_present|intcomma }}</td>
<td class="text-center">{{ student.get_tardy|intcomma }}</td>
<td class="text-center">{{ student.get_absent|intcomma }}</td>
<td class="text-center">
<button class="btn btn-outline-danger btn-sm delete-data" type="button"
data-id="{{ student.pk }}" title="Delete">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</fieldset>
</div>
</div>
</div>
</div>
{% endblock %}
{% block content%}
<!-- Modal -->
<div class="modal fade" id="addModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Add Student To Class</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form class="row g-3" method="post">
{% csrf_token %}
<div class="col-md-6 form-group">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control" %}
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary">Place</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Here are a few recommendations. Firstly, within your forms.py you're re-creating the existing fields and that's not necessary. For example:
class ClassRoomForm(forms.ModelForm):
# school_year = forms.CharField(max_length=250,help_text = "School Year Field is required.")
# level = forms.CharField(max_length=250,help_text = "Level Field is required.")
# name = forms.CharField(max_length=250,help_text = "Class Name Field is required.")
# There's no need to re-create the above since they're in the Room model already.
class Meta:
model = Room
fields = ('form_teacher', 'name', 'level', 'school_year')
# What you need to do is to use the widget attribute on the Class Meta to set the help_text and the max_length.
widgets = {
'name': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='Class Name Field is required.'),
'level': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='Level Field is required.'),
'school_year': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='School Year Field is required.'),
}
You could take that approach for the other forms you have as well.
Secondly, since you mentioned that the save_class_student method is passing the form, I'd suggest using {{ form.student }} if you want to render the form field of the form you're passing to the template.
<form class="row g-3" method="post">
{% csrf_token %}
...
<label class="form-label">Student</label>
{{ form.student }}
...
</form>
However, I think you might want to pass the form from the class_detail method since you want it to be displayed with the existing class information based on what you have in your template. With this, you could have the save_class_student method to handle the post request instead of trying to pass the form from there. For example:
#login_required
def class_detail(request,pk):
_class = Room.objects.filter(id=pk).first()
students = ClassStudent.objects.filter(classIns =_class).all()
# The classroom data: Initilizer
data = {
'classIns': _class # To set the classroom on the form since you'll be displaying on the student field.
}
form = SaveClassStudent(initial=data)
context = {
'class': _class,
'students': students,
'form': form,
}
return render(request, "school/class_info.html", context)
Then within the html file, you can have the form's action calling the url for the save_class_student method.
<form class="row g-3" method="post" action="{% url 'save_class_student url here' %}">
{% csrf_token %}
...
<label class="form-label">Student</label>
{{ form.student }}
...
</form>
Related
Null value or empty value saved with each refresh, even click button submit duplicate value, please find the following models and views file. please look at envlope button in the image that is submit button which create another model db called Emails.
fdisply.html
{% for i in obj %}
<tr>
{% if i.id %}
<th scope="row">{{forloop.counter0|add:obj.start_index}}</th>
<td>{{i.institution}}</td>
<td>{{i.fullname}}</td>
<td>{{i.email}}</td>
<td>{{i.contact}}</td>
<td>{{i.position}}</td>
<td><img src={{i.uploaddata.url}} class="img-fluid img-thumbnail" alt={{i.fullname}} style="width:100px; height: 60px"></td>
<td>
<i class="fa-regular fa-pen-to-square"></i>
<form action="{% url 'delete' i.id %}" method="POST" class="d-inline">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa-regular fa-trash-can"></i>
</button>
</form>
<!-- sent data -->
<form method="POST" class="d-inline">
{% csrf_token %}
<div class="d-none">
<input type="text" name="email" id="email" class="form-control w-50 form-row" value="{{i.useremail}}" required>
<input type="text" name="password" id="password" class="form-control w-50 form-row mt-1" value="{{i.userpassword}}" required>
</div>
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa-solid fa-envelope-circle-check"></i>
</button>
</form>
</td>
</tr>
{% endif %}
{% endfor %}
models.py
class EmailDb(models.Model):
institution = models.CharField(max_length=300, blank=True, null=True)
fullname = models.CharField(max_length=50, blank=True, null=True)
contact = models.IntegerField()
email = models.CharField(max_length=300, blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
uploaddata = models.FileField(upload_to='appointment_letter')
useremail = models.CharField(max_length=100, blank=True, null=True)
userpassword = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.fullname
class EmailS(models.Model):
ename = models.CharField(max_length=100, blank=True, null=True)
epassword = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.ename
Also added views.py where i have a business logic.
views.py
def EAdmin(request):
obj = EmailDb.objects.all().order_by('id')
# paginator
paginator = Paginator(obj, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
print(page_obj.start_index)
total_page = page_obj.paginator.num_pages
#
emaild = EmailDb.objects.all()
# POST Request
email = request.POST.get('email', '')
password = request.POST.get('password', '')
data = EmailS(ename=email, epassword=password)
data.save()
#amrit
context = {'obj': page_obj, 'lastpage': total_page, 'totalPagelist': [n+1 for n in range(total_page)], 'em': emaild, 'email':email, 'password': password}
return render(request, 'NEC/fdisplay.html', context)
Hi everyone I'm trying to create an auction system with Django.
But when I go to the item profile, Django sends me an error:
Exception Value:
The 'image' attribute has no file associated with it.
auction.html
{% extends "base.html" %}
{% block content %}
{% load static %}
<div class="page-header">
<h1>OPEN AUCTIONS</h1>
</div>
<div class="container">
<div class="row">
{% for item in auction %}
<div class="col-sm-4">
<div class="card border-secondary" style="width: 25rem;">
<div class="card-header">
Auction {{item.id}}
</div>
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
<div class="card-body">
<h3 class="card-title" style="text-align:center" >{{ item.object }}</h3>
<p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br>
End: {{ item.close_date }}</p>
<form method="POST">
{% csrf_token %}
<input type="number" name='auct_id' value={{item.id}} readonly>
<button type="submit" class="btn btn-primary btn-sm">Go</button>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this:
view.py
#login_required(login_url="login")
def auction(request):
if request.user.is_superuser:
messages.error(
request, "super user can access to admin/ and new_auction page only"
)
return redirect("new_auction")
auction = Auction.objects.filter(active=True)
for data in auction:
check = check_data(data.close_date)
if check is False:
data.active = False
data.save()
check_winner(
request, data.id
)
check_prof = check_profile(
request
)
if check_prof is True:
return redirect("profile")
auctions_open = Auction.objects.filter(active=True)
if request.method == "POST":
form = request.POST
auct_ids = form["auct_id"]
auct_id = int(auct_ids)
request.session["selected_id"] = auct_id
return redirect("betting")
else:
return render(request, "auction/auction.html", {"auction": auctions_open})
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
# Create your models here.
class Auction(models.Model):
object = models.CharField(max_length=50)
description = models.CharField(max_length=256, default="")
image = models.ImageField(upload_to="media/", null=True, blank=True)
open_date = models.DateTimeField(auto_now_add=True)
close_date = models.DateTimeField()
total_bet = models.IntegerField(default=0)
open_price = models.FloatField(
default=0,
)
close_price = models.FloatField(default=0)
winner = models.CharField(max_length=256, default="")
active = models.BooleanField(default=True)
json_details_file = models.TextField(default="")
tx = models.CharField(max_length=256, default="")
def __str__(self):
return self.object
settings.py
MEDIA_ROOT = os.path.join((BASE_DIR), "media")
MEDIA_URL = "/media/"
According to your model field image, you must give different name instead of media to upload_to.
Let's give different name to upload_to:
image = models.ImageField(upload_to="images/", null=True, blank=True) #here added images instead of media
And in your template:
instead of this:
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
Try this way:
<img src="/media/{{ item.image }}" class="card-img-top" width="250" height="180">
And now that images will display.
Note: don't forget to migrate after modifying upload_to="images/"
so the basic goal of my project is to allow teachers and admin to login to the system and take attendance for the students. my new issue is that i have a view function that is suppose to check to see if students student is already added to the respective class and if they are it will exclude them from the drop down menu and display the students who aren't in the class but it not doing that instead it is showing me a blank drop down menu. the way i have it set up is that the admin clicks the add student button then it will convert a .html page to modal which brings up the list of students to select from. When i add the form responsible for saving the student to the class in the Django admin it work perfect but i cant seem to get it to work in the user section Ui. I am new to Django and this is my first project so any help is really appreciated
Views
#check to see if students already exist in class and display those who aint to be added
#login_required
def manage_class_student(request, classPK=None):
if classPK is None:
messages.warning(request,'Class ID is Unknown')
else:
context['classPK'] = classPK
_class = Room.objects.get(id=classPK)
# print(ClassStudent.objects.filter(classIns = _class))
students = Student.objects.exclude(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student').distinct()).all()
context['students'] = students
return render(request, 'manage_class_student.html', context)
#save the students to the respective class after being selected
#login_required
def save_class_student(request):
form = SaveClassStudent()
if request.method == 'POST':
form = SaveClassStudent(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Student has been added successfully.")
redirect('class_detail')
else:
messages.error(request, 'Error Adding student in class')
template with the form to show the available students
<!-- Modal -->
<div class="modal fade" {% block modal-id %} id="addModal{{class.pk}}" {% endblock%} data-bs-backdrop="static"
data-bs-keyboard="false" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="addModalLabel"> {% block modal-title%}<i class="fas fa-plus"></i> Add
Student To Class{% endblock%}</h6>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="container-fluid">
<form {% block action %} action="{% url 'save-class-student' %}" {% endblock%} method="post">
{% csrf_token %}
<div class="modal-body">
<input type="hidden" name="classIns" value="{{ classPK }}">
<div class="form-group mb-3">
<label for="student" class="control-label">Student</label>
<select name="student" id="student" class="form-select rounded-0 select2" required>
<option disabled selected></option>
{% for student in students %}
<option value="{{ student.id }}">{{ student }}</option>
{% endfor %}
</select>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
What triggers the modal
<div class="tools">
<button type="button" class="btn btn-secondary border rounded-0 bg-gradient btn-sm"
id='print_attendance_report'><i class="fa fa-print"></i> Print Attendance Report</button>
<a data-bs-toggle="modal" data-bs-target="#addModal{{class.pk}}"> <button type="button"
class="btn btn-primary rounded-0 bg-gradient btn-sm" id='add_new'><i class="fa fa-plus"></i>
Add Student</button></a>
</div>
form that save students to classroom
class SaveClassStudent(forms.ModelForm):
classIns = forms.IntegerField()
student = forms.IntegerField()
class Meta:
model = ClassStudent
fields = ('classIns', 'student')
def clean_classIns(self):
cid = self.cleaned_data['classIns']
try:
classIns = Room.objects.get(id=cid)
return classIns
except:
raise forms.ValidationError("Class ID is Invalid.")
def clean_student(self):
student_id = self.cleaned_data['student']
_class = Room.objects.get(id=self.data.get('classIns'))
student = Student.objects.get(id=student_id)
try:
cs = ClassStudent.objects.get(classIns=_class, student=student)
if len(cs) > 0:
raise forms.ValidationError(
f"Student already exists in the Class List.")
except:
return student
I have been getting this error, and I didn't know what I did wrong in the code, I checked everything and I still cant figure it out. I also try getting the specific post object in the database by id, i mean doing something like "post = Post.objects.get(id=id)" in post function in my views.py, but i got the same error.
Any help will be appreciated.
this is my models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField()
def __str__(self):
return self.user.username
class Category(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
overview = models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
comment_count = models.IntegerField(default=0)
views_count = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True)
thumbnail = models.ImageField()
featured = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'id': self.id})
my urls
from django.urls import path
from blog.views import home, blog, post
app_name = 'blog'
urlpatterns = [
path('', home, name='home-page'),
path('blog/', blog, name='blogs'),
path('post/<id>/', post, name='post-detail'),
]
my blog.html template
<div class="container">
<div class="row">
{% for post in queryset %}
<div class="post col-xl-6">
<div class="post-thumbnail">
<img src="{{post.thumbnail.url}}" alt="..." class="img-fluid">
</div>
<div class="post-details">
<div class="post-meta d-flex justify-content-between">
<div class="category">
{% for cat in post.categories.all %}
{{cat}}
{% endfor %}
</div>
</div>
<a href="{{post.get_absolute_url}}">
<h3 class="h4">{{post.title}}</h3>
</a>
<p class="text-muted">{{post.overview}}</p>
<footer class="post-footer d-flex align-items-center">
<a href="#" class="author d-flex align-items-center flex-wrap">
<div class="avatar">
<img src="{{post.author.profile_pic.url}}" alt="..." class="img-fluid">
</div>
<div class="title">
<span>{{post.author.user.username}}</span>
</div>
</a>
<div class="date"><i class="icon-clock"></i>{{post.timestamp|timesince}} ago</div>
<div class="comments meta-last"><i class="icon-comment"></i>{{post.comment_count}}</div>
</footer>
</div>
</div>
{% endfor %}
</div>
<!-- Pagination -->
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if queryset.has_previous %}
<li class="page-item">
<a href="?page={{queryset.previous_page_number}}" class="page-link">
<i class="fa fa-angle-left"></i>
</a>
</li>
{% endif %}
<li class="page-item">{{queryset.number}}</li>
{% if queryset.has_next %}
<li class="page-item">
<a href="?page={{queryset.next_page_number}}" class="page-link">
<i class="fa fa-angle-right"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
my views.py
from django.shortcuts import render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from blog.models import Post, Category
from marketing.models import Signup
def home(request):
featured_posts = Post.objects.filter(featured=True)
latest_posts = Post.objects.order_by('-timestamp')[:3]
if request.method == 'POST':
email = request.POST['email']
new_signup = Signup()
new_signup.email = email
new_signup.save()
context = {
'featured_posts': featured_posts,
'latest_posts': latest_posts
}
return render(request, 'index.html', context)
def blog(request):
post_list = Post.objects.all()
latest_posts = Post.objects.order_by('-timestamp')[:3]
categories = Category.objects.all()
paginator = Paginator(post_list, 4)
page_number = request.GET.get('page')
try:
queryset = paginator.get_page(page_number)
except PageNotAnInteger:
queryset = paginator.get_page(1)
except EmptyPage:
queryset = paginator.get_page(paginator.num_pages)
context = {
'post_list': post_list,
'queryset': queryset,
'latest_posts': latest_posts,
'categories': categories,
}
return render(request, 'blog.html', context)
def post(request, id):
context = {}
return render(request, 'post.html', context)
In your models.py change the get_absolute_url as follow. You need to include the app name also before calling any specific url from an app.
def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'id': self.id})
I have two models SubCategory and Product i created a listview with model set to SubCategory and reference its related product set in template but items are not being loaded don't know what I have missed
models
class SubCategory(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=300)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=120)
price = models.FloatField()
image = models.ImageField(upload_to='pdt_imgs/')
sku = models.IntegerField()
available = models.BooleanField(default=True)
discount = models.IntegerField(default = 0)
category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
def __str__(self):
return self.name
Template in which I tried to reference product items related to subcategories
<div class="ps-block__categories">
<h3>Clothing & <br> Apparel</h3>
<ul>
{% for subcategory in object_list %}
<li>{{ subcategory.name }}</li>
{% endfor %}
</ul><a class="ps-block__more-link" href="#">View All</a>
</div>
<div class="ps-block__slider">
<div class="ps-carousel--product-box owl-slider" data-owl-auto="true" data-owl-loop="true"
data-owl-speed="7000" data-owl-gap="0" data-owl-nav="true" data-owl-dots="true" data-owl-item="1"
data-owl-item-xs="1" data-owl-item-sm="1" data-owl-item-md="1" data-owl-item-lg="1" data-owl-duration="500"
data-owl-mousedrag="off"><img src="{% static 'img/slider/home-3/clothing-1.jpg' %}" alt=""><a href="#"><img
src="{% static 'img/slider/home-3/clothing-2.jpg' %}" alt=""></a><a href="#"><img
src="{% static 'img/slider/home-3/clothing-3.jpg' %}" alt=""></a></div>
</div>
<div class="ps-block__product-box">
{% for product in object.product_set.all %}
<div class="ps-product ps-product--simple">
<div class="ps-product__thumbnail"><a href="product-default.html"><img src="{{ product.image.url }}"
alt=""></a>
{% if product.discount > 0 %}
<div class="ps-product__badge">-{{ product.discount }}%</div>
{% endif %}
{% if product.available == False %}
<div class="ps-product__badge out-stock">Out Of Stock</div>
{% endif %}
<ul class="ps-product__actions">
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Read More"><i
class="icon-bag2"></i></a></li>
<li><a href="#" data-placement="top" title="Quick View" data-toggle="modal"
data-target="#product-quickview"><i class="icon-eye"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Add to Whishlist"><i
class="icon-heart"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Compare"><i
class="icon-chart-bars"></i></a></li>
</ul>
</div>
<div class="ps-product__container">
<div class="ps-product__content" data-mh="clothing"><a class="ps-product__title"
href="product-default.html">{{ product.name }}</a>
<div class="ps-product__rating">
<select class="ps-rating" data-read-only="true">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="2">5</option>
</select><span>01</span>
</div>
<p class="ps-product__price sale">UGX{{ product.price }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
For now I cant load product items despite trying reference them as related objects of subcategory