Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add a rest API to an existing Python application
after some research I am stuck on my problematic... I explain myself, for a project I develop an application in microservice composed by : Entities that produce data (geolocation data) and send them to a Queueing system A "server" entity that periodically receives data from the Queueing system, performs processing/calculation on it locally. A front-end, which queries the "server" entity on a producer ID, which retrieves the data from the latter and displays them Currently, the infrastructure of the application is functional, with Kubernetes deployment etc. In relation to development, a simulator is functional to replace the entities "that produce". The latter is a multi-threaded application that continuously sends data to the Queue system. The "server" entity that receives is also functional. This last is developed in python, and consists in its operation to connect to system of Queue, to receive data periodically, to treat them by storing locally (will be migrated towards a DB in the future) an object for each ID of the producers. My problem is the following: I want to add a REST API Gateway, to be able to bind it to my "server" entity and to a front-end in React for example. I tried to … -
'Response' object has no attribute 'user'
I am getting error AttributeError: 'Response' object has no attribute 'user' for the below code I have written I am trying to get the user info from the context and create a notification model. I am getting the above error while returning the statement. I don't understand why I am getting this error Model class CourseNotification(models.Model): uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) course = models.ForeignKey('Course.Course', on_delete=models.SET_NULL, null=True) user = models.ManyToManyField('Profile.myUser',null=True) def get_user(self): return [i for i in self.user.all()] def __str__(self): return self.course.course_title View class CourseNotificationView(ModelViewSet): queryset = CourseNotification.objects.all() serializer_class = CourseNotificationSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): if self.request.user.email is not None: profile = myUser.objects.get(email=self.request.user.email) if profile is not None: notification = CourseNotification.objects.filter(user=profile) return notification else: return Response(data={"User": "Unauthorized User"}, status=HTTP_401_UNAUTHORIZED) def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(data=serializer.data) Serializer class CourseNotificationSerializer(serializers.ModelSerializer): class Meta: model = CourseNotification fields = '__all__' def create(self, validated_data): users = self.context['request'].user subject = validated_data['course'] if users is None and subject is None or subject == "": raise serializers.ValidationError({"Invalid": "Subject could not be Invalid"}) checkNotification = self.checkNotification(users, subject) if checkNotification is not None and checkNotification.status_code == 200: return checkNotification validate_subject = self.validateSubject(users, subject) if validate_subject.status_code == 200: return validate_subject get_data … -
How to sum ranks in django-orm annotate
model class ChampionKill(Event): start = models.ForeignKey('self', models.CASCADE, null=True, blank=True, related_name='sequence') damage = models.PositiveIntegerField() damage_contribution = models.FloatField() objects = ChampionKillManager() manager class ChampionKillManager(BaseManager): def get_queryset(self): return super().get_queryset().annotate( avg_damage_contribution=Avg('sequence__damage_contribution'), avg_interval=( Cast(Max('sequence__time') - Min('sequence__time'), models.FloatField()) / F('length') ), rank_damage_contribution=Window(Rank(), order_by=F('avg_damage_contribution').desc()), rank_interval=Window(Rank(), order_by=F('avg_interval').asc()), # total_rank_score=(F('rank_damage_contribution') + F('rank_interval')), # rank_total=Window(Rank(), order_by=F('total_rank_score').asc()), ) When I add "total_rank_score" and "rank_total" in annotete, I get the following error.(I am using sqlite) django.db.utils.OperationalError: misuse of window function RANK() I want to create a value of "total_rank_score" by summing the value of "rank_damage_contribution" and the value of "rank_interval". I need advice. -
Please correct the errors below. in Django admin
every time i try to add a new member to my Django admin , this error will pop up and i know its because of the email but i dont know whats wrong with it also i doesnt set my user as ACTIVE. so here is an image of the error i get image of ERROR this is my MODEL : def create_user(self,email, mobileNumber, name, familyName, password, nationalCode, **other_fields): if not email: raise ValueError('you need a valid email') email = self.normalize_email(email) user = self.model(mobileNumber=mobileNumber, name=name, familyName=familyName, password=password, email=email, nationalCode=nationalCode, **other_fields) user.set_password(password) user.save() return user def create_superuser(self,email, mobileNumber, name, familyName, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email,mobileNumber, name, familyName, password, nationalCode, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50, validators=[validate_name]) familyName = models.CharField(max_length=50, validators=[validate_name]) email = models.EmailField(max_length=50, blank=True) nationalCode = models.IntegerField(null=True, validators=[is_valid_iran_code]) mobileNumber = models.CharField(max_length=11, null=True, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = customMemberManager() USERNAME_FIELD = 'mobileNumber' REQUIRED_FIELDS = ['nationalCode', 'familyName', 'name','email'] def __str__(self): return str(self.name) and this is my admin : … -
Django : Django paths not working as expected
I have a project . I have to reference a json file . My code which is the flashcard.html file : {%include 'header.html' %} <style> {%include 'css/flashcard.css' %} {%include 'css/header.css' %} </style> <div id="content" style="width: 100%; position: relative;"></div> <i class="fas fa-caret-right" style="position: absolute; top: 20%; left: 95%; font-size: 50px;" id="next"></i> <i class="fas fa-caret-left" style="position: absolute; top: 20%; left:5%; font-size: 50px;" id="back"></i> {% for key, value in data.items %} <p>{{ key }} +':'+ {{ value }}</p> {% endfor %} <script> let mydata = {%include 'data.json' %} let frontSideFront = true let cardNum = 0 let totalCards = 2 //var mydata = JSON.parse(data); for(var i = 0 ; i < totalCards ; i++ ){ frontSideFront = true $("#content").append(` <div class="card-container" id="${i}"> <div class="front">${mydata['questions'][i]}</div> <div class="back">sd</div> </div> `) } for(var m = 0 ; m < totalCards ; m++ ){ if (m !== cardNum) { $(`#${m}`).css('visibility', 'hidden'); } } $("#next").click(function (e) { $(`#${cardNum}`).css('visibility', 'hidden'); $(`#${cardNum}`).css('position', 'absolute'); cardNum++ $(`#${cardNum}`).css('visibility', 'visible'); $(`#${cardNum}`).css('position', 'relative'); }); $("#back").click(function (e) { $(`#${cardNum}`).css('visibility', 'hidden'); $(`#${cardNum}`).css('position', 'absolute'); cardNum-- $(`#${cardNum}`).css('visibility', 'visible'); $(`#${cardNum}`).css('position', 'relative'); }); $(".card-container").click((e)=>{ if(frontSideFront){ frontSideFront = false $(".front").css({ "transform": "rotateY(-180deg)", }) $(".back").css({ "transform": "rotateY(0deg)", }) }else{ frontSideFront = true $(".front").css({ "transform": "rotateY(0deg)", }) $(".back").css({ "transform": "rotateY(180deg)", }) } }) </script> … -
Building GUI Using CSS that runs Python
I have started building GUI based App on python Using TKinter,But Tkinter is less flexile(atleast for me) to make a good Design ,So i decided to switch to Web App (that runs on local Host) and heard that CSS is good for Designing.So my question Is Is there a way to run the python code that i have previously written, In the web App that is Designed Using CSS. Eg: In my python project with tkinter,a button click would send a notification Using Firebase Cloud Messaging to my Mobile App,I want to implement the same using the Web App. -
Check the Authorization HTTP Header of every incoming request, Django
I should check the Authorization HTTP Header of every incoming request. In case of missing or invalid Authorization header it i should return an error with HTTP Code 401 Unauthorized. How to make simple authorization header validation? my code: models.py class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def clean(self): self.api_token = Token.objects.create(user=self.user) middleware.py class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_id = request.POST.get('created_by', False) try: api_token = CustomUser.objects.get(user=user_id).api_token except CustomUser.DoesNotExist: api_token = '' response = self.get_response(request) response['Authorization'] = "Bearer " + api_token return response I have tried to write validation in auth.py, but when i write request.headers.get("Authorization",'') list is empty. Tried something like this: auth.py class BearerTokenAuthentication: def get_bearer_token(self, request): **#DOEST WORK** auth = get_authorization_header(request).split() **#EMPTY LIST** auth_header_prefix = api_settings.BEARER_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: return False elif len(auth) > 2: return False return True views.py: @action(methods=['POST'], detail=False) def post(self, request): if BearerTokenAuthentication.get_bearer_token(request): **#DOES NOT WORK** tutorial_serializer = EventSerializer(data=request.data) if tutorial_serializer.is_valid(): tutorial_serializer.save() return Response(tutorial_serializer.data, status=status.HTTP_201_CREATED) return … -
Unable to add token headers to graphene-django using pytest
I am trying to add a token to graphene-django headers using pytest. But It always return that user is anonymous as shown at the end, but it should return user as token is added in fixture. @pytest.fixture def client_query(client): def func(*args, **kwargs): return graphql_query(*args, **kwargs, client=client) return func @pytest.fixture def create_candidate(candidate_factory): candidate = [] for _ in range(5): can = candidate_factory.create() token, __ = Token.objects.get_or_create(user=can.user) candidate.append(can) return candidate # This is the testing @pytest.mark.django_db def test_get_login_candidate(client_query, create_candidate): headers = {"Authorization": f"Token {create_candidate[0].user.auth_token}"} response = client_query( """ query { loginCandidate{ id, } } """, headers=headers, ) result = json.loads(response.content) print(result) output {'errors': [{'message': "'AnonymousUser' object is not iterable", 'locations': [{'line': 3, 'column': 11}], 'path': ['loginCandidate']}], 'data': {'loginCandidate': None}} -
django.core.exceptions.FieldError: Cannot resolve keyword 'field_id' into field. Choices are:...?
django.core.exceptions.FieldError: Cannot resolve keyword 'productcategory_id' into field. Choices are: country, country_id, id, name, vendor I have found one answer. but, that answer can't help me. Can anyone please tell me what is this error and how to solve it? -
creating a checkbox field with a ManyToMany relation
Im trying to add a field called, interested_fields inside my personalInfo model which users can choose from and the choices themselves come from another models' objects with the help of ManyToMany relation between the two models. Here are my models.py codes(I simplified my personal model by removing some other fields like name, age,... in order to make it more readable for you): class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_fields = models.ManyToManyField(Field, blank=True) then, I created a ModelForm like this: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] and created a get and post functions inside my views like this: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) and finally in template, inside the form I added this for loop: {% for field in fields %} <label class="containerq ant-col ant-col-md-6 ant-col-xs-8" > <span> <input type="checkbox" … -
Django: Saving image from URL to ImageField
I have read too many articless but I still haven't found a solution for my problem. I have a Django model with an ImageField on it image = models.ImageField(upload_to='products/%Y/%m/%d') All I need to do is save image from my warehouse the already existing image file path with the ImageField I have code bellow this script do sync with warehouse and I need to download Image and save in my model shop/Book from celery import shared_task from django.core.mail import send_mail import requests from .models import Author, Book, Genre @shared_task def send_mail_task(subject, message, email): send_mail(subject, message, email, ['admin@example.com']) @shared_task def shop_sync(): print('Starting update from warehouse api for database') print('Getting data from api...') url = 'http://warehouse:8001/authors/' print('Clearing data...') response_author = requests.get(url) if response_author.status_code != 200: return response_data_author = response_author.json() while 1: for counter, data in enumerate(response_data_author['results']): Author.objects.get_or_create( id=data['id'], defaults={ 'id': data['id'], 'first_name': data['first_name'], 'last_name': data['last_name'] } ) if response_data_author['next']: response_data_author = requests.get(response_data_author['next']).json() else: break url = 'http://warehouse:8001/genres/' print('Clearing data...') response_genre = requests.get(url) if response_genre.status_code != 200: return response_data_genre = response_genre.json() while 1: for counter, data in enumerate(response_data_genre['results']): Genre.objects.get_or_create( id=data['id'], defaults={ 'slug': data['slug'], 'name': data['name'], } ) if response_data_genre['next']: response_data_genre = requests.get( response_data_genre['next'] ).json() else: break url = 'http://warehouse:8001/books/' print('Clearing data...') response_book = requests.get(url) … -
Django Testing - Accessing Site with authenticated user
I am trying to do a unit test for authenticated user url access, currently I am trying to authenticate a user but I am unable to do so... def setUp(self): self.user = User.objects.create_user(email='test@testmail.com', password='test_password', is_staff=True) self.user.save() self.client = Client() def test_portfolio_url(self): self.client.login(username='test@testmail.com', password='test_password') url = reverse('portfolio') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(resolve(url).func, portfolio) self.assertTemplateUsed(response, 'portfolio.html') -
Django rest framework post requests gets Forbidden (CSRF cookie not set.)
I'm trying to do some post requests to my Django project using DRF but it gives me this error : Forbidden (CSRF cookie not set.) .. here is my code : serializers.py from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username','password','id'] views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer urls.py router.register(r'main_users', UserViewSet) urlpatterns = [ path('api/', include(router.urls)), -
Is there any way to use ajax-select AutoCompleteSelectMultipleField model like ModelMultipleChoiceField
I wanna use ajax-select AutoCompleteSelectMultipleField but I have a problem using typical django methods on it. I was using a custom model based on the django default ModelMultipleChoiceField for many to many select and I used to call queryset on the returned result from it: # form people = CustomizedModelMultipleChoiceField( Person.objects.exclude(is_healthy=True).filter(death_date=None)) # test people_list = form.fields['people'].queryset.values_list('id') but now I want to use AutoCompleteSelectMultipleField for lazy loading and it raises this error: AttributeError: 'AutoCompleteSelectMultipleField' object has no attribute 'queryset' -
Why are changes made with custom javascript not being registered
I have a custom javascript that autofills a CharField when I check a checkbox but when I click "Save" the text from the CharField doesn't save to the database, it's empty. How can I fix this? -
Is it possible to customize individual pages associated with the same template? dynamic URL django
I am working on a blog website and have set up dynamic URLs in Django for each blog article. Is it possible to change the layout of paragraphs and images of specific pages so that there are slight differences between each page? -
I want to make a custom author model with django but ı can't do that :(
I am trying to make a news site with django and there is a special author detail page in the template data structure that I received on the frontend. In the backend, I need to convert this author part to API and integrate it into the site, but the code I wrote does not work properly (I can add one author, but when I try to add the second one, I get a UNIQUE Constraint failed post_author.href error.) How do you think I should follow and what kind of structure should I create? This is my model code from django.db import models from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse #from comments.models import Comment from .utils import get_read_time from django.conf import settings from django.utils import timezone from markdown_deux import markdown from django.utils.text import slugify from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.safestring import mark_safe import uuid # from user_info.models import Profile class GENDER(models.TextChoices): Erkek = "Erkek" Kadın = "Kadın" Diğer = "Diğer" NONE = "Belirtmek İstemiyorum" class Category_Choices(models.TextChoices): BİLİNMEYENLER = '13İlinmeyenler' KİŞİSEL_GELİŞİM = 'Kişisel Gelişim' İLHAM_AL = 'İlham Al' YATIRIM_HABERLERİ = 'Yatırım Haberleri' GİRİŞİMCİLİK = 'Girişimcilik' ENGLİSH_NEWS = 'English News' BAŞARI_HİKAYELERİ = "Başarı Hikayeleri" … -
django.core.exceptions.FieldError: Cannot resolve keyword 'productcategory_id' into field. Choices are: country, country_id, id, name, vendor?
I am trying to use here Django dependent dropdown list. But at the same time, the error occurred. If I make an ajax request click the product category and the dependent dropdown not working togetherly and cannot make an ajax request shows an error. How to resolve this error? Kindly, someone please help. Models.py from django.db import models class ProductCategory(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class SubCategory(models.Model): country = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Vendor(models.Model): designer_name = models.CharField(max_length=100, default='') design_name = models.CharField(max_length=200) description = models.TextField(max_length=5000) productcategory = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True) def __str__(self): return self.designer_name forms.py from django import forms from .models import Vendor, ProductCategory, SubCategory class DesignerForm(forms.ModelForm): class Meta: model = Vendor descr = forms.CharField( widget=forms.Textarea ) fields = ('designer_name','design_name', 'description', 'productcategory', 'subcategory') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = SubCategory.objects.none() if 'productcategory' in self.data: try: productcategory_id = int(self.data.get('productcategory')) self.fields['subcategory'].queryset = SubCategory.objects.filter(productcategory_id=productcategory_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.productcategory.subcategory_set.order_by('name') Views.py from .models import * from django.shortcuts import render, redirect from .forms import * def Products(request): if request.method == 'POST': form = DesignerForm(request.POST) … -
Django, taggit: When I try to filter objects associated with taggit tags, the query is very slow
I have about 300,000 queries, and when I go through objects that are tied together, such as the following The query becomes very slow (about 2-3 seconds). How can I speed up the query? Also, in this case, should I implement the tags in m2m field instead of using dkango-taggit? # models.py from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TagBase class MyCustomTag(TagBase): slug = None created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class TaggedWhatever(GenericUUIDTaggedItemBase): tag = models.ForeignKey( MyCustomTag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items", ) class Video(models.Model): tags = TaggableManager(through=TaggedWhatever, blank=True) def __str__(self): return self.title # views.py MyCustomTag.objects.annotate(count=Count("video")).order_by("-count") Also, just trying to retrieve an object that contains a tag like this will result in a very slow query. A very slow query will be issued. Video.objects.filter(tags__name='tag_name') -
How to use Django's inbuilt authentication with custom forms (html templates)
I am trying to create a website using Django where user can register and login currently I am storing the user registration data in my custom database table. But I am not finding any sold way to do user authentication using the data from my custom tables So I am in search of a way where I can use Django's inbuilt user auth but with my custom forms( html templates) on top Please Help me !! -
django didn't shows the pictures
when i add posts in django admistration it did't show the photos(.jpg) -
Model form is not able to save in database
I am a beginner in Django I want to save a form data in database but i am not able to save, followed some tutorials also. form.py: from django.forms import ModelForm from .models import * class listsForm(ModelForm): class Meta: model = todo fields = "__all__" views.py: from django.shortcuts import render from .models import * from .form import * def index(request): lists = todo.objects.all() form = listsForm() context = { 'lists':lists, 'form':form, } if request.method == 'POST': form = listsForm(request.POST) if form.is_valid: form.save() return render(request, 'index.html', context) models.py: from django.db import models class todo(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) created = models.DateField(auto_now_add=True) def __str__(self): return self.title -
How to get total quantity of each kind of task in Django?
I have 1 table for tasks, those tasks can be in 3 status"todo","in-progress" and "done", I want to calculate total number of each status' task, and put it into an array like ('todo total','progress total','done total'), any idea how can I achieve that? my final goal is to display the 3 subtotal in Chartjs, Thanks in advance. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') # todo_list's content team = models.ForeignKey('Team', on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) project_code = models.CharField(max_length=20) details = models.TextField() def __str__(self): return self.status # return self.team['team'].queryset def update_status(self): if self.status == 'to_do': self.status = 'in_progress' elif self.status == 'in_progress': self.status = 'done' self.save() ''' -
How to add a random serial number generator in models.py of Django project?
I am creating a Asset Management System project using Django. I am simultaneously learning django framework. Now the problem is Suppose I have an Asset whose serial number is not specified that how i generate a random unique serial number for an asset. class Asset(models.Model): asset_type=models.ForeignKey(Asset_type,on_delete=models.CASCADE) asset_name=models.CharField(max_length=50) asset_serial=models.CharField(max_length=20) asset_date_pur=models.DateField() asset_price=models.FloatField() asset_vendor=models.CharField(max_length=50,null=True,blank=True) person_assigned=models.CharField(max_length=50,default=None) department_assigned=models.CharField(max_length=50,default=None) -
How do I get reverse reference in Django template?
Apologies if the title doesn't make much sense. I don't quite understand what I lack in knowledge. I have a Post and Comment models in my Django project. What I'm trying to do is list out all the Blog posts, and show NUMBER OF COMMENTS OF EACH POST. Please see my codes below. models.py class Blog(models.Model): objects = models.Manager() title = models.CharField(max_length=100, blank=True) body = models.CharField(max_length=10000, blank=True) created_at = models.DateField(auto_now_add=False) class Comment(models.Model): objects = models.Manager() post = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comment') views.py def main_page(request): all_blogs = Blog.objects.all() context = { 'blog' : blog, } return render(request, 'main/home.html', context) template {% for b in blog %} <div> <p>{{b.title}}</p> <div> {{WHERE THE NUMBER OF THIS POST'S COMMENTS IS DISPLAYED}} </div> </div> {% endfor %} All I need is the number of the comments, but have no idea how to do it. Is there a way to make this possible in the template? Or do I have to add some codes in views.py? Thanks.