I am trying to add a notifications feature to my social media platform. Part of this involves adding a notifications logo to my navbar at the top of my website which will display the number of unseen notifications a logged-in user has.
When I run my server, I receive a NameError:
NameError
Here is part of my navbar.html:
{% load custom_tags %}
(...)
{% if user.is_authenticated %}
<div class="nav-item dropdown">
<a class="nav-link dropdown-toggle text-dark" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><i class="fas fa-user"></i></a>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="{% url 'profile' request.user.profile.pk %}">Profile</a></li>
<li><a class="dropdown-item" href="{% url 'account_logout' %}">Sign Out</a></li>
</ul>
</div>
<div class="nav-item">
{% show_notifications %}
{% endif %}
</div>
</div>
</nav>
Here is my show_notifications.html:
<div class="dropdown">
<span class="badge bg-primary notification-badge">{{ notifications.count }}</span>
<div class="dropdown-content d-none" id="notification-container">
{% for notification in notifications %}
{% if notification.post %}
{% if notification.notification_type == 1 %}
<div class="dropdown-item-parent">
#{{ notification.from_user }} liked your post
<span class="dropdown-item-close">×</span>
</div>
{% elif notification.notification_type == 2 %}
<div class="dropdown-item-parent">
#{{ notification.from_user }} commented on your post
<span class="dropdown-item-close">×</span>
</div>
{% endif %}
{% elif notification.comment %}
{% if notification.notification_type == 1 %}
<div class="dropdown-item-parent">
#{{ notification.from_user }} liked on your comment
<span class="dropdown-item-close">×</span>
</div>
{% elif notification.notification_type == 2 %}
<div class="dropdown-item-parent">
#{{ notification.from_user }} replied to your comment
<span class="dropdown-item-close">×</span>
</div>
{% endif %}
{% else %}
<div class="dropdown-item-parent">
#{{ notification.from_user }} has started following you
<span class="dropdown-item-close">×</span>
</div>
{% endif %}
{% endfor %}
</div>
</div>
Here is my custom_tags.py:
from django import template
from academiciesocial.models import Notification
register = template.Library()
#register.inclusion_tag('social/show_notifications.html', takes_context=True)
def show_notifications(context):
request_user = context['request'].user
notifiations = Notification.objects.filter(to_user=request_user).exclude(user_has_seen=True).order_by('-date')
return {'notifications': notifications}
The final notifications has been marked as "is not defined (PylancereportUndefinedVariable)".
My Notifications class from my models.py:
class Notification(models.Model):
# 1 = Like, 2 = Comment, 3 = Follow
notification_type = models.IntegerField()
to_user = models.ForeignKey(User, related_name='notification_to', on_delete=models.CASCADE, null=True)
from_user = models.ForeignKey(User, related_name='notification_from', on_delete=models.CASCADE, null=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='+', blank=True, null=True)
comment = models.ForeignKey('Comment', on_delete=models.CASCADE, related_name='+', blank=True, null=True)
date = models.DateTimeField(default=timezone.now)
user_has_seen = models.BooleanField(default=False)
I am fairly new to this so I would greatly appreciate the exact step-by-step answers to the problem :)
there is typo in your code.
It should be "notifications" you made it "notifiations"
Related
I am currently facing this problem with Django ListView. Basically, I need to filter some questions per topic and I would like to paginate the results.
My code is working perfectly about the queryset part (the results are showed correctly) but I am facing a problem with pagination.
Let's say I have so far 8 items in my query, if I choose to paginate_by = 10, it shows me just one page. If, otherwise, I choose to paginate by, let's say, 3, it shows me 3 pages to choose in the template (which is correct) but it shows me ALL the results of the query in my page.
I post some code to be more clear
models.py:
class Tag(models.Model):
name = models.CharField(max_length=300, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def clean(self):
self.name = self.name.capitalize()
def __str__(self):
return self.name
class Question(models.Model):
post_owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=5000, default='')
body = tinymce_models.HTMLField()
tags = models.ManyToManyField(
Tag, related_name='tags')
viewers = models.ManyToManyField(
User, related_name='viewed_posts', blank=True)
views.py:
class TagQuestionsListView(ListView):
template_name = 'main/tag_questions.html'
paginate_by = 20
def get_queryset(self, **kwargs):
tag = Tag.objects.get(name=self.kwargs['name'])
questions = Question.objects.filter(tags=tag)
return questions
def get_contextdata(self, **kwargs):
context = super().get_context_data(**kwargs)
context['tag'] = Tag.objects.get(name=self.kwargs['name'])
context['questions'] = Question.objects.filter(
tags=context['tag'], is_deleted=False)
return context
template:
{% extends 'base.html' %}
{% load humanize %}
{% block title %}Domande su {{tag.name}}{% endblock title %}
{% block content %}
<style>
.text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* number of lines to show */
line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>
<div class="card">
<div class="mt-3">
<h3 class="ms-2" style="display: inline;">Ultime {{ questions.count }} Domande</h3>
{% if request.user.is_authenticated %}
Fai una domanda
{% else %}
Fai una domanda
{% endif %}
</div>
<h5 class="ms-2">{{ total_questions.count }} domande totali </h5>
<hr>
{% for question in questions %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
</div>
<div class="row mt-3">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.previous_page_number }}">Precedente</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Precedente</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li class="page-item {% if page_obj.number == i%} active {% endif %} %} "><a class="page-link" href="?filter={{ filter }}&orderby={{ orderby }}&page={{ i }}">{{i}}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.next_page_number }}">Prossima</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Prossima</a></li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
{% endblock content %}
With this I want my comment converter to answer.
You have to use page_obj instead questions in your template.
<--! ⬇️⬇️⬇️ -->
{% for question in page_obj %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
So, if you define attribute paginate_by , than ListView(django docs) adds a paginator and page_obj to the context. To allow the users to navigate between pages, add links to the next and previous page, in your template.
Im working on my django project. The home page of my project is to show all of my post and category-based post on the bottom after the first part. But my code isnt working and i dont know why. Please help me, im a django noob
#the word Opini is one of my post category
{% for post in blog_posts %}
<div class="card d-inline-flex m-1" style="width: 18rem;">
<a href="{% url 'post-detail' post.pk %}" >
<img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap">
</a>
<h3>{{post.category}}</h3>
<div class="card-body">
<h5 class="card-text text-center">{{ post.post_title }}</h5>
<p class="card-text">{{post.post_content|truncatechars:75|safe }}</p>
</div>
</div>
{% endfor %}
<h1> Opini </h1>
{% for post in blog_posts %}
{% if post.category == "Opini" %}
<div class="card d-inline-flex m-1" style="width: 18rem;">
<a href="{% url 'post-detail' post.pk %}" >
<img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap">
</a>
<h3>{{post.category}}</h3>
<div class="card-body">
<h5 class="card-text text-center">{{ post.post_title }}</h5>
<p class="card-text">{{post.post_content|truncatechars:75|safe }}</p>
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
My Models
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('post_by_category', args=[self.name])
class Post(models.Model):
post_title = models.CharField(max_length=50)
post_img = models.ImageField(upload_to='postImage/')
post_content = RichTextField(blank= True, null = True)
category = models.ForeignKey(Category , on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
post_author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ["-post_date"]
def __str__(self):
return f'{self.post_title}'
When i run the code, only the first page works, when it comes to the second part, nothing appeared
If "Opini" is the category name then you should compare it like this:
{% if post.category.name == "Opini" %}
I created the model post and I want to show all the posts on Web Page using Class-based views but It's not working. the URL is opening but the web page is not showing anything( stuff that is on homepage.html and on _post.html but navbar is there which is coming from _inject.html). The problem is in coding in the template.
Post Model-
class Post(models.Model):
auther = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
heading = models.CharField(max_length=400)
message = models.TextField()
message_html = models.TextField(editable=False)
def __str__(self):
return self.message
def save(self,*args,**kwargs):
self.message_html = misaka.html(self.message)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk})
class Meta:
ordering = ['-created_at']
unique_together = ['auther','message']
Post view-
class ListPosts(generic.ListView):
model = models.Post
template_name = "homepage.html"
homepage.html
{% extends "_inject.html" %}
{% block content %}
<div class="col-md-8">
{% if post.count == 0 %}
<h2>No posts in this group yet!</h2>
{% else %}
<ul>
{% for p in Post.all %}
<h1>p.message</h1>
<li> {% include "_post.html" %} </li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endblock %}
_post.html-
<div class="media">
<h3 class="mr-5">#{{ post.user.username }}</h3>
<div class="media-body">
<strong>{{ p.user.username }}</strong>
<h5>{{ p.message_html|safe }}</h5>
<time class="time">{{ p.created_at }}</time>
<div class="media-footer">
{% if user.is_authenticated and post.user == user and not hide_delete %}
<a href="{% url 'posts:delete' pk=post.pk %}" title="delete" class="btn btn-simple">
<span class="fa fa-remove text-danger" aria-hidden="true"></span>
<span class="text-danger icon-label">Delete</span>
</a>
{% endif %}
</div>
</div>
</div>
Try changing your homepage.html to something like this:
{% extends "_inject.html" %}
{% block content %}
<div class="col-md-8">
{% if post_list %}
{% for post in post_list %}
<h1>{{post.message}}</h1>
<li>{% include "_post.html" %} </li>
{% endfor %}
{% else %}
<h2>No posts in this group yet!</h2>
{% endif %}
</div>
{% endblock %}
Hello Stack Overflow !
I am making a news site in Django as a part of my "internship", I have just started learning web development. I was given a task to make a custom template ( it HAS to be a custom template ) which will render out 3 latest news from a category, and I have to include it as a sidebar on my "article" page.
I tried to write the custom tag, but it's not going to well unfortunately. This is my "last" task for the website, and I'm stuck (like many times before :P )
Here's the thing..everything is working if I include the custom tag on my "list all articles" page, it renders correctly depending on which category I click on.
The thing is, once I try to include my tag into my "single article" page I hit a brick wall. The tag is still working, but is now displaying all of my articles, instead of filtering the articles related to that article's category.
To simplyfiy, If i click on a "health" article to open it, I want the sidebar just to include the articles for the "health" category, I hope that makes sense.
Anyone with a couple of minutes of spare time willing to help me out ? :)
My code :
the custom tag:
from django import template
from news.models import Article
register = template.Library()
#register.inclusion_tag("news/categories.html")
def show_results(article):
article = article.filter()[:3]
return {'article': article}
HTML template for the tag:
{% load article_extras %}
<div class="articles-filter">
<ul>
{% for a in article %}
<img src="{{ a.article_image.url }}" alt="">
<h5>{{ a.title }}</h5>
{% endfor %}
</ul>
</div>
my models :
from django.db import models
from datetime import datetime
from autoslug import AutoSlugField
class Category(models.Model):
category_title = models.CharField(max_length=200, default="")
def __str__(self):
return self.category_title
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_image = models.ImageField('Article Image')
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
img2 = models.ImageField('Article Image 2', default="", blank=True)
img3 = models.ImageField('Article Image 3', default="", blank=True)
img4 = models.ImageField('Article Image 4', default="", blank=True)
img5 = models.ImageField('Article Image 5', default="", blank=True)
img6 = models.ImageField('Article Image 6', default="", blank=True)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('Article', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=datetime.now, blank=True)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
the "single article" template where I am trying to include my custom tag:
{% extends "news-base.html" %}
{% load static %}
{% load article_extras %}
{% block article %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="preloader d-flex align-items-center justify-content-center">
<div class="spinner">
<div class="double-bounce1"></div>
<div class="double-bounce2"></div>
</div>
</div>
{% show_results article %}
<!-- ##### Post Details Area Start ##### -->
<section class="container post-details-area">
<div class="container single-article-div">
<hr class="hr-single">
<h2 class="single-article-titles">{{ article.title }}</h2>
<hr class="hr-single">
<img class="single-article-img" src="{{ article.article_image.url }}" alt="">
<!-- *********************************** -->
<hr class="hr-single">
<p>Category: {{ article.article_category }}</p>
<hr class="hr-single">
<div class="row justify-content-center">
<!-- Post Details Content Area -->
<div class="col-12 col-xl-8">
<div class="post-details-content bg-white box-shadow">
<div class="blog-thumb">
</div>
<div class="blog-content">
<div class="post-meta">
{{ article.pub_date }}
</div>
<h3 class="single-article-titles post-title"> {{ article.description }}</h3>
<hr>
<!-- Post Meta -->
<div class="post-meta-2">
<i class="fa fa-eye" aria-hidden="true"></i> 1034
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 834
<i class="fa fa-comments-o" aria-hidden="true"></i> 234
</div>
<p>{{ article.article_text }}</p>
<hr />
{% include "partials/_thumbnails.html" %}
<hr>
<p>Author: {{ article.author }}</p>
<hr>
{% for comment in article.comments.all %}
<div class="comment">
<div class="date">{{ comment.created_date }}</div>
<strong>{{ comment.author }}</strong>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}
</div>
<!-- Post A Comment Area -->
<div class="post-a-comment-area bg-white mb-30 p-30 box-shadow clearfix">
<!-- Section Title -->
<div class="section-heading">
<h5>LEAVE A REPLY</h5>
</div>
<!-- Reply Form -->
<div class="contact-form-area">
<form action="#" method="post">
<div class="row">
<div class="col-12 col-lg-6">
<input type="text" class="form-control comment-section" id="name" placeholder="Your Name*"
required />
</div>
<div class="col-12 col-lg-6">
<input type="email" class="form-control comment-section" id="email" placeholder="Your Email*"
required />
</div>
<div class="col-12">
<textarea name="message" class="form-control" id="message" cols="30" rows="10"
placeholder="Message*" required></textarea>
</div>
<div class="col-12">
<button class="btn mag-btn comment-section" type="submit">
Submit Comment
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
my views.py:
from django.shortcuts import render, reverse, get_object_or_404
from django.views import generic
from news.models import Article, Category
from .forms import CommentForm
from django.http import HttpResponseRedirect
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Article.objects.order_by("-pub_date").filter(is_published=True)[:6]
class CategoryView(generic.ListView):
template_name = 'news/categories.html'
context_object_name = 'category'
def get_queryset(self):
return Article.objects.filter(article_category__category_title="Politics")
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
context = {'article': article}
return render(request, 'news/article.html', context)
def add_comment_to_article(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})
my "all articles" page:
<div class="container">
{% block articles %}
<!-- ***************************************** -->
<div class="category-filter container">
<ul>
<li class="categories-title">Categories:</li>
<hr class="small-line">
{% for category in categories %}
<li class="category-list">
{{ category.category_title }}
</li>
{% endfor %}
</ul>
</div>
<!-- ***************************************** -->
{% show_results latest_article_list %}
<hr class="hr-style1">
<h2 class="article-list-title">Article List :</h2>
<hr class="hr-style2">
<div class="container list-wrapper">
{% for article in latest_article_list %}
<div class="container">
<div class="well">
<div class="media">
<a class="pull-left" href="{% url 'news:article' article.id %}">
<img class="media-object" src="{{ article.article_image.url }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ article.title }}
</h4>
<p class="text-right">{{ article.author }}</p>
<p>{{ article.description }}</p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ article.pub_date }}
</span></li>
<li>|</li>
<span><i class="glyphicon glyphicon-comment"></i> 2 comments</span>
<li>|</li>
<li>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</li>
<li>|</li>
<li>
<span><i class="fa fa-facebook-square"></i></span>
<span><i class="fa fa-twitter-square"></i></span>
<span><i class="fa fa-google-plus-square"></i></span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Thank you so much for taking the time to read this.
Have a good day !
Your changed code wouldn't work at all on the single article page; you would get an AttributeError.
The problem is that you are in your list view you are passing the queryset, latest_article_list, but in the single article view you are passing that single article. You can't filter an article, you can only filter a queryset.
Really it seems that the thing you want to do is to pass a category. There's no reason to pass the latest article list to that template tag; you can just get the articles directly in the tag. But from the single article view you want to get the articles with the same category. So, make the parameter category, and make it optional.
#register.inclusion_tag("news/categories.html")
def show_results(category=None):
articles = Article.objects.all()
if category:
articles = articles.filter(category=category)
return {'article': article[:3]}
Now from the list view you can just call the tag without arguments:
{% show_results %}
whereas from the single view you can pass the article category:
{% show_results article.category %}
I built a django powered webapps,where I used a model field called average CGPA(avg_cgpa) which is a DecimalField in Django model. Also I used a for loop on controller/template to generate all separate data about a student.Now my intention is to compare avg_cgpa data for every row of model to generate a new tag.Where it will be print different result for each student.
Like, if avg_cgpa > 2.00 it will be print pass,otherwise fail !
I did tried as you have seen on template but its not working,please come up with your helpfull answer.
(Django model here)
class Management(models.Model):
student_id = models.CharField(max_length=100)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
father_name = models.CharField(max_length=200)
mother_name = models.CharField(max_length=200)
Present_address = models.TextField(max_length=400)
Permanent_address = models.TextField(max_length=400)
contact = models.CharField(max_length=11)
avg_cgpa = models.DecimalField(max_digits=20,decimal_places=2)
def __str__(self):
return self.student_id
(Here is the template)
{% load static %}
{% include 'base.html' %}
{% block content %}
{% include 'navbar.html' %}
{% include 'banner.html' %}
<div class = "container">
<div class="row">
{% for x in student %}
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title"><strong>ID : </strong> {{ x.student_id }}</h5>
<hr class="my-4">
<img class="card-img-top" src="{% static "images/hat.png" %}"><hr class="my-4">
<h6 class="card-subtitle mb-2 text-muted"><strong><i class="far fa-user-circle"></i> </strong> {{ x.first_name }} {{ x.last_name }}</h6>
<hr class="my-4">
<p class="card-text">Father's Name : <strong>{{ x.father_name }}</strong></p>
<p class="card-text">Mother's Name : <strong>{{ x.mother_name }}</strong></p>
<p class="card-text">Address : <strong>{{ x.Permanent_address }}</strong></p>
<p class="card-text"><strong><i class="fas fa-phone"></i> {{ x.contact }}</strong> </p>
<p class="card-text">Avg CGPA : <strong>{{ x.avg_cgpa }}</strong></p>
{% if x.avg_cgpa > "2" %}
<p class="card-text">Condition : <strong>Pass</strong></p>
{% endif %}
</div>
</div>
</br>
</div>
{% endfor %}
</br>
</div>
{% include 'footer.html' %}
{% endblock%}
I did tried if condition within for loop,but no result as outcome.Is it possible to retrieve data by comparing model data in django ?
I would consider adding a property to your model that returns whether it is a pass or not
class Management(models.Model):
#property
def passed(self):
return self.avg_cgpa > 2
This can then be used in the template {% if x.passed %}, it can also be used in other parts of your code and is a bit more readable