I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic cick in image here
Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page My code is here.
models.py
from django.db import models
from django.db.models.base import ModelState
# Create your models here.
class Course(models.Model):
faculty = models.CharField(max_length=100)
class Semester(models.Model):
sem = models.CharField(max_length=100)
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return F"Semester {self.sem} at Faculty {self.faculty}"
class Subject(models.Model):
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
sem = models.ForeignKey(Semester, on_delete=models.CASCADE)
subject_name = models.CharField(max_length=100)
def __str__(self):
return str(self.id)
views.py
from django.shortcuts import render
from django.views import View
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from .forms import CustomerRegistrationForm
from .models import Course, Semester, Subject
# Create your views here.
def home(request):
return render(request, 'app/home.html')
def faculty(request):
course = Course.objects.all()
return render(request, 'app/faculty.html', {'course':course})
class SemesterView(View):
def get(self, request,id):
obj = Course.objects.get(id=id)
print(obj)
semobj = Semester.objects.filter(faculty=obj)
print(semobj)
subobj = Subject.objects.filter(faculty=obj)
print(subobj)
return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj})
semester.html
{% extends 'app/base.html' %}
{% load static %}
{% block semester %}
<div class="bsc-csit">
<div class="container">
<div class="row" style="margin-top:90px; padding-top:20px;">
{% for so in semobj %}
<div class="col-md-3">
<div class="bsccsit-box">
<h3 style="color: black">{{so.sem}}</h3>
<ul>
{% for suo in subobj %}
<li><a href="">1.{{suo.subject_name}}</a></li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock semester %}
CodePudding user response:
Try replacing the following in your template:
{% for subject in so.subject_set.all %}
<li><a href="">{{ forloop.counter }}. {{subject.subject_name}}</a></li>
{% endfor %}
You can get all Subject
's from a specific semester via subject_set.all
.
You can also use {{ forloop.counter }}
to provide a enumerative number with the associated subject.