Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add students to class in by teacher in one click in Django rest framework
I have models named Student and Teacher. Teacher will be able to see all the students through get api (students name). Now the requirement is, by just clicking one button on the side of the list of student name, teacher should be able to add the student to his class. How to associate students to teacher in this cases. Because same students can be added to other class by other teacher as well. class Student(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="student", on_delete=models.CASCADE) college_name = models.CharField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name class Teacher(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="teacher", on_delete=models.CASCADE) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name -
Django with reportlab pdf
The following code works and prints pdf as required, but everything prints on single page only, how I can automatically generate new pages when data builds up, seeking an advice def pdf_view(request): buf = io.BytesIO() c = canvas.Canvas(buf) c.setPageSize(landscape(A4)) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) rows = [] users = User.objects.filter(is_staff=False) for user in users: rows.append(( user.username, user.email, user.first_name, user.last_name, )) table = Table(rows, colWidths=46 * mm) table.setStyle([ ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 0), (-1, -1), "LEFT"), ]) table.wrapOn(c, width, height) table.drawOn(c, 10 * mm, 10 * mm) styles = getSampleStyleSheet() ptext = "Member List" custom_style = ParagraphStyle( "Normal", fontName="Helvetica-Bold", fontSize=16, parent=styles['Heading2'], alignment=1, spaceAfter=14 ) p = Paragraph(ptext, custom_style) p.wrapOn(c, 100 * mm, 100 * mm) p.drawOn(c, 100 * mm, 195 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='members.pdf') -
django model formset how to make formset from two tables(or with one to one field)
I would like to make page to verify users, simple page, just username and checkbox near. what i getting how look it now id like make ModelChoiceField look like simple username text, or ModelChoiceField disabled. My code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='id пользователя', related_name='model') phone = models.CharField(max_length=30, verbose_name='Номер телефона', blank=True) city = models.CharField(max_length=36, blank=True, verbose_name='Город') is_verified = models.BooleanField(default=False, verbose_name='Проверен') published_news = models.IntegerField(default=0, verbose_name='Количество опубликованных новостей') class UserVerifyView(View): def get(self, request): template_name = 'app_users/verify.html' formset = UserVerifyFormSet() context = {'title': 'Верификация', 'formset': formset} return render(request, template_name, context) {% block content %} <div class="container"> {% csrf_token %} {{ foromset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} </div> {% endblock %} -
How to unittest test Django ModelForms with kwargs
I am trying to write unit tests for a Django ModelForm. This form's init method has been overridden so as to access the current user in the kwargs variable. However, anytime I run the test, it always brings this error form = UserCreationForm(data={'email': 'test@email.com', File "C:\Users\CODING\django\project1\bookapp\forms.py", line 45, in __init__ self.current_user = kwargs.pop('current_user') KeyError: 'current_user' views.py @method_decorator([login_required], name='dispatch') # Only logged in users can access the page class BookCreateView(CreateView): template_name = "new_book.html" model = Book def get_form_kwargs(self): kwargs = super(BookCreateView, self).get_form_kwargs() kwargs['current_user'] = self.request.user return kwargs forms.py class BookCreationForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'isbn', 'author') def __init__(self, *args, **kwargs): self.current_user = kwargs.pop('current_user') # Line 45 super().__init__(*args, **kwargs) # Some removed code tests def test_save(self): new_user = get_user_model().objects.create_user( email='test1@email.com', password='secret', first_name='John', last_name='Doe', ) user = get_user_model().objects.get(id=1) # This tests the save method form = BookCreationForm(data={'email': 'test@email.com', 'first_name': 'John', 'last_name': 'Doe', 'current_user': user, }) book = form.save() Anytime I run the test, it fails because of that KeyError -
How is this pluralize not working on Django template?
Was working on Django, following the documentation I got stuck at this point, for some reason pluralize isn't working well on my template where I specified it. Ask if more part of code is required. Consider telling what's wrong in here??? Views Output screen -
Django two websites hosted with Apache, urls do not work at one of them
I did set up two websites (hosted locally). I'm on windows so config may look odd. WSGIPythonHome "C:/var/www/magazyn/env39" WSGIPythonPath "C:/var/www/magazyn/venv/Lib/site-packages;C:/var/www/magazyn/rootkat/" ServerName www.magazyn-stolarz.pl LoadFile "C:/Python39/python39.dll" LoadModule wsgi_module "C:/var/www/magazyn/env39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIScriptAlias /awizacje "C:/var/www2/awizacje/rootkat/awizacje/wsgi.py" WSGIScriptAlias / "C:/var/www/magazyn/rootkat/magazyn/wsgi.py" <Directory "C:/var/www2/awizacje/rootkat/awizacje/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /statica "C:/var/www2/static/" <Directory "C:/var/www2/static/"> Require all granted </Directory> <Directory "C:/var/www/magazyn/rootkat/magazyn/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/var/www/static/" <Directory "C:/var/www/static/"> Require all granted </Directory> With that configuration base site works perfectly ("pc-name/") but the second one ("pc-name/awizacje") does not. Main url works like it should but every button sends me to ("pc-name/button-url") and not ("pc-name/awizacje/button-url"). I have set ROOT_URLCONF = 'awizacje.urls' in settings.py. Is there something I am missing? Any way I should change settings to take base url into account? -
Django - Join two Table without Foreign key
I have two tables and want to join them.. but I can't do that without rawQueryset. how can i join two models without foreign key? The column for JOIN is not unique so it can't be PK and Foreign Key. I want to get the SQL LIKE THIS 'SELECT * FROM genome AS A JOIN metadata AS B ON A.query_id = B.sample_id', and this the models I used. class Genome(models.Model): query_id = models.CharField(max_length=100) ref_id = models.CharField(max_length=30) matching_hashes = models.CharField(max_length=30) class Metadata(models.Model): project_id = models.CharField(max_length=50) # Metagenome의 query id와 JOIN함 sample_id = models.CharField(max_length=50) -
Cannot connect to redis in docker and django
I have run a redis container using this command: docker run -d --name redis -p 6379:6379 redis. and I have run my Django app using this command: docker run -it -p 8000:8000 voucher. and my connection redis url is redis://redis:6379/1. But i cannot seem to connect to redis here is my error: redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known. -
Django problem with missing " underscore" in url
I am a beginner and need a little support. Everything works in the application, but when in the form it typing "new york", "_" is missing in the url. My code is res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=1b79ea7b1251b7a830b41a81d6bd').read() In response receives " InvalidURL at / URL can't contain control characters. '/data/2.5/weather?q=bielsko biala&appid=1b79ea7b1251b76cc0b41a81d6bd' (found at least ' ') I am looking for solutions on the Internet but I cannot solve it myself. Thank you very much for all your help -
django admin page links broken and always redirect to the home page(/admin)
We are running django with gunicorn + Nginx on amazon ecs with docker. For authentication and as SSO(single sign-on) provider, we are using Auth0. The admin page links have been working fine for some time but they suddenly stopped working in our dev environment. All of the links in the admin page redirect back to the admin homepage i.e if you click on the User model to see the users you just get redirected back to the admin homepage. We have tried so many solutions and it has been a very bizarre bug for us. The main reason this error is so confusing is that we have the same exact code with similar configurations on our staging environment and all the admin page links work perfectly in it. To enable authentication and SSO with Auth0 we are using a python library called python-social-auth and we think the problem could be caused maybe by a cookie or redirect-related issue coming from it. so we tried different configurations for it per the documentation and some StackOverflow answer to questions similar to this one but to no avail. This is our current settings.py configuration: # Auth0 Authentication Related Configs Keys SOCIAL_AUTH_PROTECTED_USER_FIELDS = [ … -
an error occured when TensorRT engine reference runs under the Django framework
I use the transformed tensorrt engine for a BertTokenClassification model referenceing in Django service, the following errors occur: [TensorRT] ERROR: 2: [pluginV2DynamicExtRunner.cpp::execute::115] Error Code 2: Internal Error (Assertion status == kSTATUS_SUCCESS failed.) This error is located in this line: context.execute_async_v2(bindings=bindings[:4] + [bindings[4]], stream_handle=stream.handle) However, it is puzzling that if the same reasoning code is not run in the Django service, no error occures. Could you help me what is the cause of this problem? -
Am I passing user object to ModelForm using CreateView correctly?
I'm developing a booking portal that allows a logged in user to create a delivery slot (booking). models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField() delivery_time = models.TimeField() booking_number = models.CharField(max_length=50,null=False) # def save(self, **kwargs): # if not self.booking_number: # self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" # super().save(**kwargs) def get_absolute_url(self): return reverse("booking_detail",kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking from bootstrap_datepicker_plus import DatePickerInput import datetime as dt HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('qty_plts','cbm','delivery_date','delivery_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6]}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} views.py from django.shortcuts import render # Create your views here. from .models import Booking from django.urls import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (ListView,DetailView,CreateView,UpdateView,DeleteView,TemplateView) class AboutView(TemplateView): template_name = 'about.html' class BookingCreate(LoginRequiredMixin,CreateView): login_url = '/login' redirect_field_name = 'bookmyslot/booking_detail.html' model = Booking form_class = BookingForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.user.booking_number = f"{self.request.user.delivery_date:%Y%m%d}{self.request.user.delivery_time:%H%M}" self.object.save() return super().form_valid(form) I want the booking number to be generated at the time of form creation, for the … -
file upload and process in django
I am a django beginner and here is what I am trying to build. upload a file using django form in media_root read the uploaded file by calling a function from my data extraction python file upload extracted data to databse using django models. Appreciate if experts can provide an example for what I am building. Thanks, Sam -
Combining Django DateField and TimeField in ExpressionWrapper gives TypeError: expected string or bytes-like object
I have a Request model that has a Foreign Key to a Slot My Slot models look like this:- class Slot(models.Model): day = models.DateField() start_time = models.TimeField() end_time = models.TimeField() In my views, im trying to annotate the day and start_time fields to compare them with the current time, from django.db.models import DateTimeField, DateField, TimeField, ExpressionWrapper, F pending_requests = Request.objects.annotate( my_dt=ExpressionWrapper( F('slot__day') + F('slot__start_time'), output_field=DateField() ) )[0] This gives me: TypeError: expected string or bytes-like object When I annotate each field to its respective field type, it works fine, pending_requests = Request.objects.annotate( my_dt=ExpressionWrapper( F('slot__day'), output_field=DateField() ) )[0] Not sure if Im combining the fields correctly or how I can fix this please -
Django - use raw query and order by with parameter
data_list = Data.objects.raw( 'SELECT * FROM data_table ORDER BY %(order_col_name)s', {"order_col_name" : order_col_name}) I use this code but..Ordering doesn't work. I think the raw function cann't pass the ordering column parameter. Can anybody help? -
Django formset for all choices in a given model field with prefilled values for the Choice Field
I have a model as follows: AGE_GROUPS = ( ('<1', '<1'), ('1-4', '1-4'), ('5-9', '5-9'), ('10-14', '10-14'), ('15-19', '15-19'), ('20-24', '20-24'), ('25-29', '25-29'), ('30-34', '30-34'), ('35-39', '35-39'), ('40-44', '40-44'), ('45-49', '45-49'), ('50+', '50+'), ) class Data(models.Model): dataset = models.ForeignKey('data.Dataset', on_delete=models.CASCADE) indicator = models.ForeignKey('data.Indicator', on_delete=models.CASCADE) facility = models.CharField(max_length=120, choices=FACILITIES) month = models.CharField(max_length=20) age_group = models.CharField(max_length=10, choices=AGE_GROUPS) male = models.PositiveIntegerField(blank=True, null=True) female = models.PositiveIntegerField(blank=True, null=True) And a form and formset as follows: class DataForm(forms.ModelForm): class Meta: model = Data fields = ['age_group', 'male', 'female'] DataFormset = forms.modelformset_factory(Data, form=DataForm, extra=len(AGE_GROUPS)) And this is the problem: In the template, I want the formset to be rendered as a table for all the age groups with the Age groups prefilled. Better still, is there a way to have the Age Group as a non-editable column, but the male and female editable? Mind you if the particular record already has values (for male and female), then the respective formset row should be prefilled as well. Here's my view so far: def home(request): data_formset = DataFormset(request.POST or None) # -> The below code is not working when the model has existing data # (I'm open to any approach) # Prefill the Age Groups in the formset # … -
python use case with django and other libraries and have to answer the following questions with it
I am completely new to python and had this university use case in the assignment. Need help with it. your help will be highly appreciated in advance. Kindly help me with this problem. import os import django import datetime from pytz import timezone from xwing import settings from gentella.api_access.emarsys.api import EmarsysApi from collections import namedtuple from typing import List os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xwing.settings") django.setup() from gentella.emarsys_models.models import ContactSegment brand_shop_segment = namedtuple('brand_shop_segment', ['id', 'name', 'count', 'brand']) def get_segment_info_as_df(brand: str) -> List[brand_shop_segment]: assert brand in settings.EMARSYS_LOGINS.keys(), 'passed \'brand\' is not in EMARSYS LOGINS' etc_timezone = timezone('Europe/Amsterdam') api = EmarsysApi(username=settings.EMARSYS_LOGINS[brand]['username'], secret_token=settings.EMARSYS_LOGINS[brand]['secret'], tzinfo_obj=etc_timezone) segment_data = api.get_segments() segments = [] for segment in segment_data: segment_count = api.get_segment_contact_count(segment_tuple=segment) brand_segment_combo = brand_shop_segment(id=segment_count.id, name=segment_count.name, count=segment_count.count, brand=brand) segments.append(brand_segment_combo) return segments def save_segments(segment_info: List[brand_shop_segment], brand: str) -> None: today = datetime.datetime.today().date() ContactSegment.objects.filter(dt=today, brand=brand).delete() data_list = [] for segment in segment_info: data = ContactSegment( id=segment.id, name=segment.name, count=segment.count, brand=segment.brand, dt=today ) data_list.append(data) ContactSegment.objects.bulk_create(data_list) def main() -> None: for brand in settings.EMARSYS_LOGINS.keys(): print(brand) segment_list = get_segment_info_as_df(brand=brand) save_segments(segment_list, brand=brand) if _name_ == '_main_': main() ============================================================================================== Questions: What type of process is the code supporting? Kindly walk us through the code – main functions, objects, general functionality. What is exactly the purpose of line 19? Could the … -
Django Query set: Duration from two DateTimeField()
In my Django project, I have a model like this- class Task(models.Model): ticket_number = models.CharField() order_number = models.CharField() number_of_errors = models.IntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField() I'd like to make a query set "tasks" where I'll include working_date, ticket_number, order_number, and work_hours(end_time-start_time) in HH:MM:SS for example 03:55:01 format. "working_date" will be derived from end_time. Once I get the query set right, I'll export the result in a CSV. I can do the query in MySQL like this: SELECT DATE(end_time) AS working_date, ticket_number, order_number, TIME_FORMAT((TIMEDIFF(end_time,start_time)),'%H:%i:%s') AS work_hours FROM task WHERE end_time>= pStartDate AND end_time< pEndDate; How do I do this in Django ORM? -
TemplateDoesNotExist at / templates/home/hom_page.html
i'm using django here's my views code: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'templates/Home/Home_page.html') here's my urls code: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), ] here's img: -
How do I send response data form multiple tables via django rest framework
I want to send Response(xyzSerializer.data), where xyzSerializer serializes data form two models i.e. Users and Customers to give it following body/look { 'userID': 1, 'firstName': 'name', 'lastName': 'Lname', 'gender': 'Male', 'country': 'Cloc', 'city': 'City', 'phoneNumber': '12345', 'dob': 'dd-mm-yy', 'dateJoined': 'dd-mm-yy', 'role': 'blogger', 'user': 1 'customerID': 1, 'occupation': '', 'blogger': True, 'userID': 1 } But, currently I can either serialize Users, or Customers model individually which give following output respectively, UserSerializer { 'userID': 1, 'firstName': 'name', 'lastName': 'Lname', 'gender': 'Male', 'country': 'Cloc', 'city': 'City', 'phoneNumber': '12345', 'dob': 'dd-mm-yy', 'dateJoined': 'dd-mm-yy', 'role': 'blogger', 'user': 1 } CustomerSerializer { 'customerID': 1, 'occupation': '', 'blogger': True, 'userID': 1 } I want to join data from two models using userID and send that as a response. Here are my Users and Customers models, class Users(models.Model): userID = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.TextField() lastName = models.TextField() gender = models.TextField() country = models.TextField() city = models.TextField() phoneNumber = models.TextField() dob = models.TextField() dateJoined = models.TextField() role = models.TextField() def __str__(self): return f"ID: {self.userID}" class Customers(models.Model): customerID = models.AutoField(primary_key=True) userID = models.ForeignKey('Users', on_delete=models.CASCADE, name="userID") occupation = models.TextField() blogger = models.BooleanField(default= False) def __str__(self): return f"ID: {self.customerID}" Here are my Serializers, class UserSerializer(ModelSerializer): class Meta: model … -
DRF normalize nested serializer
I have a ManyToMany field in my models. In serializer, I am able to get the nested serialized data, but I want to normalize it. models.py class Authors(models.Model): name = models.CharField(max_length=20) class Mets: db_table = "authors" class Books(models.Model): book_name = models.CharField(max_length=100) authors = models.ManyToManyField(Authors, related_names="books") class Meta: db_table = "books" serializers.py class AuthorSerializer(serializer.ModelSerializer): name = serializer.CharField() class Meta: model = Authors field = ("name",) class BooksSerializer(serializer.ModelSerializer): authors = AuthorSerializer() class Meta: model = Books field = ("book_name", "authors") The output of the above will be: "result": [ { "book_name": "Sample", "authors": [ { "name": "Person 1", }, { "name": "Person 2", } ] } ] But I want to output something like this: "result": [ { "book_name": "Sample", "author_name": "Person 1", }, { "book_name": "Sample", "author_name": "Person 2", }, ] -
django s3direct file upload working through admin panel but not through model form
I have a model form that lets users upload images. But when we click submit on that form, it's not being uploaded into s3. I have registered the same model in admin and the upload works through admin panel. So I know my s3 has been configured properly. I have made it to return a Httpresponse called error when the form is invalid and it's returning that when I click submit I am very new to django and can't wrap my head around this. Appreciate any help. Thank You My Model class advert(models.Model): category_choices = ( ("choice", "choice"), ) name = models.CharField(max_length=32) part_name = models.CharField(max_length=50, blank=True) category = models.CharField(choices=category_choices, max_length=255) photo = S3DirectField(dest='primary_destination') seller = models.ForeignKey(User, on_delete=models.CASCADE) soldby = models.CharField(max_length=32, blank=True) place = models.CharField(max_length=32, blank=True) cell = models.CharField(max_length=13,blank=True) My Model Form class advertform(forms.ModelForm): def __init__(self, *args, **kwargs): super(advertform, self).__init__(*args, **kwargs) self.fields['seller'].widget.attrs['hidden'] = True soldby = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) place = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) cell = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) # photo = forms.URLField(widget=S3DirectWidget()) name = forms.CharField(widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Name of component'})) part_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Part no./name'})) class Meta: model = advert fields = ('name', 'part_name', 'category', 'photo', 'soldby', 'place', 'cell', 'seller') My views function def addpost(request): if not User.is_authenticated: … -
change CORS port dynamically
I want to give front access to my endpoints, but their ports range from 3000 to 3005 how can i set that dynamically or set those all CORS_ALLOWED_ORIGINS = [ 'http://localhost:3001', 'http://localhost:3000', ] -
local variable 'Facility' referenced before assignment?
I am facing "local variable 'Facility' referenced before assignment". Although I have imported it from Models. I did same thing for many other models to fetch data but this time it gives this error. Please Assist. Views.py def addshift(request): facilities=Facility.objects.order_by('id') user=request.user if request.method=="POST": StartTime=request.POST.get('StartTime') StartDate=request.POST.get('StartDate') EndTime=request.POST.get('EndTime') EndDate=request.POST.get('EndDate') Facility=request.POST.get('Facility') Note=request.POST.get('Note') shift=Shift(user=request.user,StartTime=StartTime,StartDate=StartDate,EndTime=EndTime,EndDate=EndDate,Facility=Facility,Note=Note) shift.save() messages.success(request,"Shift added successfully!") context={ 'schedule':'active', 'facilities':facilities, 'user':user, } return render(request,'addshift.html',context) Models.py class Facility(models.Model): Title=models.CharField(max_length=200,null=True) FirstName=models.CharField(max_length=200,null=True) LastName=models.CharField(max_length=200,null=True) FacilityName=models.CharField(max_length=200,null=True) FacilityType=models.CharField(max_length=200,null=True) CorporateGroup=models.CharField(max_length=200,null=True) LegalName=models.CharField(max_length=200,null=True) Email=models.CharField(max_length=200,null=True) Phone=models.CharField(max_length=200,null=True) FacilityAddress=models.CharField(max_length=200,null=True) def __str__(self): return self.Title + " | " + self.FacilityAddress -
Getting query of commenter Not request.user
I am building a BlogApp and I am trying to get user of commenter not the request.user, I am building a query of Tag in which i will work on comment's user but it is getting `request.user. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) tags = TaggableManager() class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) blog_of = models.ForeignKey(Blog, on_delete=models.CASCADE) body = models.CharField(max_length=1000) views.py def blog_detail_view(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) # Tag query tag = Tag.objects.filter(blog__comment__commented_by=request.user) context = {'post':post} return render(request, 'detail.html', context) What have i tried ? I have also tried tag = Tag.objects.filter(blog__comment__commented_by=post.comment_set.commented_by) But it is not getting the comment user, It is only getting request.user. And if a user commented multiple times than it will get the user also Any help would be much appreciated. Thank You