Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facebook API Auth 2 with python or Django
I am trying ti get user Token using Facebook oauth2 api but i am facing this error when redirect url call. InsecureTransportError at /data/FacebookAuth/ (insecure_transport) OAuth 2 MUST utilize https. I have running ngrok & https setup but i can't figure out why it is giving me this error Here is my code to get this token in django #Facebook App Credentials client_id = 'xxxx' client_secret = 'xxxxx' # OAuth endpoints given in the Facebook API documentation> authorization_base_url = 'https://www.facebook.com/dialog/oauth' token_url = 'https://graph.facebook.com/oauth/access_token' redirect_uri = 'https://ab207c1f.ngrok.io/data/FacebookAuthRedirect' facebook = OAuth2Session(client_id, redirect_uri=redirect_uri) facebook = facebook_compliance_fix(facebook) #Getting Facebook Authentication def FacebookAuth(request): authorization_url, state = facebook.authorization_url(authorization_base_url) redirect(authorization_url) #Getting Facebook Authentication Redirect def FacebookAuthRedirect(request): redirect_response = request.GET.get('code', '') token = facebook.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) print(token) return HttpResponse('ibrahim') -
Integrating Python Heroku with Firebase
In a django project I have imported firebase_admin and it worked perfectly on local host, but when I used Heroku to host my web app it gave error no module named 'firbase-admin'. I cross-checked my requirements files and it has firbase-admin. I don't know what's that I did wrong as I made sure that requirements used in virtual environment is same to that in Heroku requirements files. -
Get multiple Tags
I am designing a blog with each blog holding multiple tags. I use {% blog.get_tags.0 %} to get the tag from the tag field in the mysql table. What I want to do is filter by multiple tags, like this:{% if blog.get_tags.0 == "Tag1" and blog.get_tags.1 == "Tag2"%} I've stored the tags as Tag1, Tag2 in the Tag field in the blog table. {{blog.get_tags.1}} displays Tag2 but does not work in if statement. How do I use Tag2 in the conditional statement. -
Django:Choices and Foreign fIelds not being rendered on form
inputs involving foreign keys,booleans,and choices are not being rendered on my form.please help forms.py from django.forms import ModelForm from .models import Document class DocumentForm(ModelForm): class Meta: model = Document fields = '__all__' models.py class Document(models.Model): client = models.ForeignKey(Client,null=True,on_delete=models.SET_NULL) name = models.CharField(max_length=200,null=True) category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True,null=True) text = models.TextField(null=True) summary_text = models.TextField(null=True,blank=True) def __str__(self): return self.name views.py def createDoc(request): form = DocumentForm() context= {"form":form} return render(request,'main/document_form.html',context) document_form.html {% block content %} <form action="" method="post"> {% csrf_token%} {{form}} <input type="submit" value="SUMBIT"> </form> {% endblock %} -
model with this Email already exists in django
i have made a custom user model. signup and logout is working fine. but i have made a login form using that model.my model name is usersignupmodel. but whenever after signing-up, then i try to login it gives me error like that User signup model with this Email already exists. i can not find the problem. my models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): #if not email: #raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60,unique=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email','name','age'] objects = SignUpManager() def __str__(self): return self.name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True … -
Open a template file and go to a start line then print out a database query results
I got something similar to this, to work in another program by doing the following: with open (OutputFileName, 'r') as OutputFile: for line in islice(OutputFile, StartCount): pass for line in islice(OutputFile,int(FQuantity)): data= line.strip().split(" ") So the above did what i wanted it to, it openned a existing template file skipped to the StartCount and started writing out stuff. however this time im trying to skip to a startcount and print out database results. No matter how i try for some reason i cant get it to actually skip rows anymore; see attempts below: where numberlist is the data result from database. I think this one doesnt work because i leave the islice. with open(InputOrderARCpathcreate, 'r+') as inputfile: for line in islice(inputfile, StartCount): pass for row in numberlist: inputfile.write(str(row[0]) + '\n') other attempt where i try smthn closer to what worked before, using a quantity:- with open(InputOrderARCpathcreate, 'r+') as inputfile: for line in islice(inputfile, StartCount): pass for line in islice (inputfile, 1): for row in numberlist: inputfile.write(str(row[0]) + '\n') I want to know the following: how can I get this to work my way? (even if it isnt the best way i want to understand why it doesnt work. How can … -
Tests in Travis are not running
I trigger a build on my app but Travis doesn't run any test. As suggested on Travis official doc, I have created a postgresql db before_script. Here is my .travis.yml: language: python python: - '3.7' before_script: - pip install -r requirements.txt env: DJANGO_SETTINGS_MODULE=my_app.settings.travis services: - postgresql before_script: - psql -c 'create database travis_ci_test;' -U postgres script: - ./My-App/manage.py test And my Job log: Setting environment variables from .travis.yml $ export DJANGO_SETTINGS_MODULE=my_app.settings.travis $ source ~/virtualenv/python3.7/bin/activate $ python --version Python 3.7.1 $ pip --version pip 19.0.3 from /home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/pip (python 3.7) $ pip install -r requirements.txt $ psql -c 'create database travis_ci_test;' -U postgres $ ./My-App/manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK The command "./My-App/manage.py test" exited with 0. Done. Your build exited with 0. I have 9 tests running fine locally with python3 manage.py test. Do I have to ligrate first? -
getting django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I was using django with mongodb with djongo package. i used embedded field to make a embedded document in my collection. if i make migration using makemigrations command its throwing error like below. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\progrma\backend\mysite\myapp\models.py", line 12, in <module> class Myapps(models.Model): File "D:\progrma\backend\mysite\myapp\models.py", line 16, in Myapps skill = models.EmbeddedField( File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\djongo\models\fields.py", line 225, in __init__ super().__init__(model_container, *args, **kwargs) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\djongo\models\fields.py", line 87, in __init__ self._validate_container() File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\djongo\models\fields.py", line 91, in _validate_container for field in self.model_container._meta.get_fields(): File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 707, in _relation_tree return self._populate_directed_relation_graph() File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 678, in _populate_directed_relation_graph all_models = … -
pyodbc Login timeout expired
I am trying to connect to Microsoft SQL Server in windows 10 using pyodbc from a remote machine running Ubuntu 18 with (within django project). import pyodbc conn = pyodbc.connect(DSN=ODBC Driver 17 for SQL Server;DATABASE=test;UID=test_login;PWD=123456;server=129.168.1.3,49170;) I'm getting following error: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') -
i want to understand the following codes
0 order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if not order.items.filter(item__id=order_item.id).exists(): order.items.quantity = qty order.items.add(order_item) messages.info(request, "This item quantity was updated.") return redirect("shop:order-summary") can any one make me understand how the above code works? step by step please? -
Django TemplateSyntaxError Could not parse the remainder: error when using {% if MyModel.objects.filter(id=maxid).values('col2') = something %}
In Django, im trying to get a different button shown in html based on what value is in the latest created object of a model. my HTML code is: {% if MyModel.objects.filter(id=maxid).values('col2') = something %} <button id="Button 1">Button 1</button> {% else %} <button id="Button 2">Button 2</button> {% endif %} but when i reload the screen, Django gives me this error message TemplateSyntaxError at /col2/ Could not parse the remainder: '(id=maxid).values('col2')' from 'MyModel.objects.filter(id=maxid).values('col2')' -
PayPal/Stripe - Allow one user to pay another through Website
Goal: Allow a user on my website to pay another user(merchant) for a service via either PayPal or Stripe. I would like to take a percentage of the purchase amount and the remaining percentage would go to the merchants account. I've successfully added both Stripe and PayPal to my Django app, and successfully integrated a payment portal, but the default use-case appears to be for the user to send a payment to owner of the website (owner of the paypal/stripe account) via a client ID. For paypal, I figured out how to specify the payee as the merchant, rather than myself, but there is still not a clear way to split the payment. I would not like to accept 100% of the payment and then pay the merchant. The only payment I should receive is the percent of the payment at the time of the transaction.. Is it possible to implement this type of payment schema through Stripe Merchant onboarding? The only route to achieve this through paypal as far as I can tell is PayPal partnership (paypal marketplace), which is for larger businesses. -
js object to django objects
I'm very new to django. I have a page that allows user to get give a number based on the number I can create text input fields.The html code {% extends 'base.html' %} {% block head %} <title>Prepare</title> {% endblock%} {% block body %} <div class="container"> <center> <div class="font-style-light"> {% for i in NOQ %} <div class="container"> <input type="text" id= for.counter value=""><br> </div> {% endfor %} </div> </center> </div> {% endblock %} Now I have created the input fields but I want to get values of all the input fields and save them in django model. I can combine all the elements' value into a js array object. Is there a way to extract the value from js objects, Or is there any other way to satisfy this requirement. Thanks in advance -
i wrote an edit post view using forms in Django , it works without errors but the value in the database doesn't change
here's the Url.py url(r'^(?P<slug>[-\w]+)/edit$', views.noteEdit, name="noteedit") and the view i saw the result of the note after changing an it's work properly but after the second print(note) it looks like django don't save it and change it in the data base def noteEdit(request, slug): note = get_object_or_404(Note, slug=slug) print(note) if request.method == "POST": form = noteform(request.POST, instance=note) if form.is_valid(): print(note) newform = form.save(commit=False) newform.user = request.user newform.save() return redirect('/notes') else: form = noteform(instance=note) context = { 'form': form, } return render(request, 'edit.html', context) and the model part class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # on-delete work when we delete user the notes will be deleted title = models.CharField(max_length=30) content = models.TextField(blank=True) created = models.DateTimeField( default=datetime.datetime.now, blank=True,) slug = models.SlugField(blank=True, null=True) active = models.BooleanField(default=True) tags = models.CharField(blank=True, max_length=100) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Note, self).save(*args, **kwargs) -
Django REST Framework customize update method
My application has the following structure: models.py class EventHost(models.Model): hostid = models.ForeignKey(Host, on_delete=models.PROTECT) eventid = models.ForeignKey(Event, on_delete=models.CASCADE) someparam = models.CharField(max_length=100, blank=True, null=True) ... class Meta: unique_together = ("hostid", "event") class Host(models.Model): hostid = models.IntegerField(primary_key=True) hostname = models.CharField(max_length=100) ... class Event(models.Model): eventid = models.AutoField(primary_key=True) eventname = models.CharField(max_length=100) ... hosts = models.ManyToManyField(Host, through='EventHost') views.py class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.order_by('-date') serializer_class = EventSerializer class HostViewSet(viewsets.ModelViewSet): queryset = Host.objects.order_by('-hostid') serializer_class = HostSerializer class EventHostViewSet(viewsets.ModelViewSet): queryset = EventHost.objects.all() serializer_class = EventHostSerializer Currently to update EventHost table I'm doing http put providing id (which is primary key) in my url . I'd like to be able to update EventHost providing hostname and eventname (which will be passed in url) instead of id. Using SQL it would look like this: update eventhost set someparam='somevalue' from eventhost as a, event as b, host as c where b.id = a.eventid and c.hostid = a.hostid and b.eventname='myevent' and c.hostname='myhost'; From documentation I understood that I would need to modify the default update method for the viewset or/and modify queryset. Any ideas how should it be achieved? -
in django I want to remove employee name one by one after successfull attendence submition
I want onclick of update button the submitted attendence of employee should not display in the list. I mean it should be removed one by one after successfull submition of attendence of employees. My model of employee attendence is class Attendence(models.Model): EmpId = models.IntegerField(verbose_name='EmpId') Name = models.CharField(max_length=50,verbose_name='Name') Site = models.CharField(max_length=50,verbose_name='Site') #month = models.ForeignKey(Month,on_delete=models.CASCADE,verbose_name='month') #year = models.ForeignKey(Year,on_delete=models.CASCADE,verbose_name='year') Days = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Days') Nh = models.IntegerField(verbose_name='Nh') #SingleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='SingleOt',null=True) DoubleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='DobleOt',null=True) choices = [('P','Present'),('A','Absent'),('L','Leave')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') date = date.today() AttendenceOn = models.DateField(default = date) My view.py look like below def AttendenceList(request): attendencelist = Attendence.objects.filter(AttendenceOn=date.today()) return render(request,"attendencelist.html", {"attendencelist":attendencelist,"date":date.today()}) def AttendenceView(request): Emp_list = EmployeeRegistration.objects.filter(Status='Working', Site=request.user.SuperVisor.Site).order_by('- Doj') if request.method == 'POST': empid = request.POST['empid'] name = request.POST['name'] status = request.POST.get('Status') ot = request.POST.get('DoubleOt') site = request.user.SuperVisor.Site if status is "P": day = 1 Attendence.objects.create(EmpId=empid, Name=name,Status=status,Site=site,DoubleOt=ot,Days=day,Nh=0) attendForm = AttendForm() return redirect('show') else: attendForm = AttendForm() context = {"emp_list":Emp_list, "attendform":attendForm, "date":date.today() } return render(request,"attendence.html",context) and my Template of attendence.html is given below {% extends 'profilebase.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container" style="padding-top: 15px;"> <div class="card"> <h1 class="card-header bg-info">Attendence <p style="float: right;">{{date}}</p></h1> <div class="card-body"> <div class="row"> <div class="col-md-12"> <table class="table table-striped table-hover"> <thead> <tr> <th>#</th> <th>Id</th> <th>Name</th> <th>Role</th> <th>Status</th> <th>Ot</th> <th>Action</th> … -
In Django the media file is not getting created when user uploads a picture
i guess the ImageField(upload_to="pics") parameter must create a folder in the project directory with name as 'pics' when user chooses an media(image). But its not working. The image name is only getting stored in the database but when i fetch the image it cannot find the image. Please Help my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') my models.py: class tableOne(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) password = models.CharField(max_length=100) propic = models.ImageField(upload_to="pics") my views.py: def imageupload(request): name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') password=request.POST.get('password') p=request.POST.get('picture') data=tableOne(name=name,email=email,phone=phone,password=password,propic=p) data.save() return HttpResponse("Image inserted") -
Sending Emails from Class Based views not working
I am trying to send an email when a post in a Class Based View is created but I am not receiving anything although I am receiving a success message after post created. I am sure that email configuration is correct as I am receiving an email for a reset password Here is the view class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'post'] template_name = "post_form.html" success_url = "/score" success_message = "Thank you for Submitting a post" def form_valid(self, form): form.instance.designer = self.request.user return super().form_valid(form) def PostCreatedEmail(request): subject = 'Message subject' message = 'Message' send_mail( subject, message, 'email@email.com', ['email@email.com'], fail_silently=False, ) return render(request, '/score') here is the urls: path('new/', PostCreateView.as_view(), name='post-create'), -
how to filter groups that have products linked to them by a foreign key django
i am trying to filter groups that match with products that share a foreign key in between, foreign key is being set from the Product. i have done it correctly but i believe that there is an easier and a better way to do it. views.py def shop(request, shop_url): products = Product.objects.all() groups = None for product in products: groups = Group.objects.filter(id=product.item_group.id) context = { 'products' : products, 'groups' : groups, } return render(request, 'shop/shop.html', context) models.py class Product(models.Model): name = models.CharField(max_length=100) item_group = models.ForeignKey('Group', on_delete=models.CASCADE) class Group(models.Model): name = models.CharField(max_length=200) def __str__(self): return str(self.name) -
django manage.py runserver do not print python errors in the console
When I type python manage.py runserver and then I do some actions in the website, I cannot see Python errors in the console. I only get an error 500 message in the navigator. Is it possible to turn something on so as to see Python errors in the console? -
Django is rendering empty template to create new profile instead of submitting form
First some code: models.py class Findings(models.Model): patient = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) finding_type = models.CharField(max_length=35, null=True) upload = models.FileField(null=True, blank=True) date_created = models.DateField(auto_now=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.finding_type forms.py class AddFindingForm(ModelForm): class Meta: model = Findings fields = ('finding_type', 'description', 'upload', 'patient') labels = { 'finding_type' : _('Rodzaj badania'), 'description': _('Opis'), 'upload': _('Dodaj plik'), } views.py def add_finding(request): form = AddFindingForm() if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.patient = request.user.profile form.save() return redirect('profile') context = {'form': form} return render(request, 'add_finding.html', context) template {% block content %} <form method="POST" enctype="multipart/form-data" action=""> {% csrf_token %} {{ form.as_p}} <button type="submit"> Wyślij </button> </form> {% endblock %} So, everytime i'm trying to submit a filled form it displays another form to create new Profile, even if i'm setting patient manually. The empty form it's displaying is on the same url. I have no idea why it's doing that... -
how to make login authentication with custom user model in django
i have made a custom user model. signup and logout is working fine. but i have made a login form using that model. but whenever i try to submit the form ,after authentication it is supposed to redirect me to home page. but unfortunately it does not authenticate and redirect me to login page repeatedly. how should i solve this? my models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): #if not email: #raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60,blank=True,null=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email','name','age'] objects = SignUpManager() def __str__(self): return self.name def has_perm(self, perm, obj=None): return self.is_admin def … -
Django EmailMessage class execution makes the website slow and sluggish
I am using Django's EmailMessage class for sending auto mail, from a view. However the website literally stops showing the next render page (which is on a modal), until the Email has been sent. If I remove Email sending stuff then the website is very fast and works properly. Please guide as to how to send mail also while not forcing the user to wait for the mail sending process. My partial view codes are below for reference: email =EmailMessage( 'Message received', 'You received a message....', settings.DEFAULT_FROM_EMAIL, [request.user.email], reply_to=['noreply@example.com']) email.content_subtype = "html" email.send(fail_silently=True) return JsonResponse({"instance": rendered,"valid":True}, status=200) -
Changing width of django filter form
my filters.py file import django_filters from django_filters import CharFilter from .models import * from django.forms.widgets import TextInput, Textarea from django.forms import widgets class ProductFilter(django_filters.FilterSet): name=CharFilter(field_name='name', lookup_expr='icontains', label="", widget=TextInput(attrs={'placeholder': 'Search Here'})) class Meta: model=Product fields='__all__' exclude=['name', 'price', 'digital', 'image', 'description'] How can I change width of the filter form to the size of search bar we have in stackoverflow for example? A code snippet demonstrating it would be very helpful. -
How do i query for comment in Django
i am new in Django and i have been following tutorials online. I am having problem on how i can display comment, how do i query for comment in views, so i can be able to display comment for a particular post. Model: class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) image_caption = models.TextField(blank=True, null=True) class Comments (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) commented_image = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) comment_post = models.TextField() Views.py: def home_view(request): comment = Comments.objects.all() #This is getting all comment in all post, how do i query for comment in a particular post. context{'comment':comment} return render(...) Template: {% for com in comment %} <p>{{ com.comment_post }}</p> {% endfor %}