Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement upvotes and downvotes in Django models?
I am trying to develop a reusable votes Django application that can fit any model and allow me to avoid code duplication. Its purpose should be to just upvote and downvote objects. For example, I could develop a project where there are Question and Answer models, both of which have their respective score field (upvotes - downvotes). The code in models.py could look something like this: class Question(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 class Answer(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 It is clear that this code would work but is not well designed since the two models are practically a copy of one another. To solve this, I was thinking about creating a votes app with perhaps a Vote model in it that would fit both the Question and Answer models described above. I tried to create a single Vote model in votes/models.py, but I ended up needing two models anyway: a QuestionVote and an AnswerVote model. Besides, I could not really integrate this code with the Question and Answer models at all. Here is the general idea for the QuestionVote model I came … -
Django rest framework one to one relation model
I would like to add phone number as one to one relation to django User table. is there I can get phone number field too at the registration. -
Admin filters for django admin
Django admin provides very basic view for applying filters on List pages but we have several uses cases where we want multi select, multi search, range filtering. These cases include applying filtering on related fields and reverse related fields as well We explored several packages https://github.com/modlinltd/django-advanced-filters https://github.com/silentsokolov/django-admin-rangefilter https://github.com/lukasvinclav/django-admin-numeric-filter but none seems to fit our use cases well without fiddling with base model admin. Are there alternatives to these ? If creating own custom filters how are you handling such uses cases ? - any ideas / tips / suggestion to start with ? I did get some idea for search here - https://medium.com/@hakibenita/how-to-add-a-text-filter-to-django-admin-5d1db93772d8 for multiple options to search, planning to use comma separated values and then split that in backend confused on how to implement for multi select choices -
Pyinstaller Django Channels issue
I'm trying to pack a django app into an .exe, after a multiple tries (hooks etc...) Everything works fine, except django-channels. When I run mysite.exe runserver, the app starts but the routing are not found and channels are not working. Here is my .spec -- mode: python ; coding: utf-8 -- block_cipher = None a = Analysis(['mysite\manage.py'], pathex=['C:\Users\SFadili\Documents\_Never Backup\Django\help2'], binaries=[], datas=[ ('mysite/templates', 'templates'), ('mysite/static', 'static'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\plotly\', 'plotly'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne\', 'daphne'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne-2.5.0.dist-info\', 'daphne-2.5.0.dist-info'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven\', 'raven'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven-6.10.0.dist-info\', 'raven-6.10.0.dist-info'), ], hiddenimports=[ 'mysite.routing', 'mysite.urls', 'myapp.apps', 'myapp.urls', 'myapp.routing', 'myapp.consumers', 'channels.apps', 'channels_redis', ], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='mysite', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage') FYI : I had an issue with daphne saying that another application is using the server, I solved it by modifiying the pyi_rth_twisted.py file into : from twisted.internet import asyncioreactor This creates module: sys.modules['twisted.internet.reactor'] asyncioreactor.install() when I run the server , I got thit : System check identified no issues (0 silenced). September 14, 2020 - 10:13:24 Django version 2.2.16, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the … -
Django - nearby user without geodjango?
I'm looking for any suggestions and alternative to Geodjango. My goal is to propose to user to find the nearest users and display a distance between them. I got a classical model for localisation. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') ... -
Django Quill text-editor
I have a problem when trying to add a value to QuillField field. I have a model field like this : ... from django_quill.fields import QuillField ... ... quill_field = QuillField(blank=True, null=True) #QuillField ... And the idea is to add a value on object creation inside the create function : ... if form.is_valid(): obj_ = form.save(commit=False) ... obj_.terms_of_use_text = get_default_terms() #Here obj_.save() ... ... With get_default_terms() function which basically just pulls all the text from txt file: def get_default_terms(): cpath = Path.cwd() document = open((Path(cpath, 'properties/defaultTerms.txt'))).read() text_json = { "delta": "{\"ops\":[{\"insert\":\"%s} \\n\"}]}", "html": "<p></p>" } return json.dumps(text_json['delta'] % document) get_default_terms() function returns simple text in a normal format : "TERMS AND CONDITIONS\nAll of the membership rules contained herein apply equally to members, temporary members and guests alike.\nOverview\nAll reference to the [Property Address] or [Property/Company Name] refers to [Property/Company Name], its staff, employees, sub contractors, agents and representatives. Facilities refer to any of the rooms to be reserved within. Including but not limited to: the gymnasium, showers, saunas, changing rooms and fitness studios where applicable.\n... The problem appears when I try to save the text inside the QuillField, I get django_quill.quill.QuillParseError: Failed to parse value error. Any idea why I can't … -
Django bulk_update not working on default attributes
I want to change the default value of an attribute from a model in Django. So I want to update the existing values in the database. Strange enough, a bulk update doesn't change those values. My model: class UserSettings(models.Model): offline_notification_filter = models.BooleanField(default=False) My test class TestSetOfflineNotificationMigration(APITestCase): def test_set_offline_notification_filter_to_false(self): user_settings_1 = UserSettingsFactory(offline_notification_filter=True) user_settings_2 = UserSettingsFactory(offline_notification_filter=False) user_settings_3 = UserSettingsFactory(offline_notification_filter=True) user_settings_4 = UserSettingsFactory() all_user_settings = UserSettings.objects.all() for user_setting in all_user_settings: user_setting.offline_notification_filter = False UserSettings.objects.bulk_update( all_user_settings, ["offline_notification_filter"] ) self.assertEqual(user_settings_1.offline_notification_filter, False) This test is failing because the the offlince_notification_filter is not updating. Anyone knows why not? -
In Django, how to keep many-to-many relations in sync?
What's the best way, in Django, to set and keep up-to-date a many-to-many field that is (for a lack of a better term) a composite of many-to-many fields from other models? To give a concrete example, I have a Model representing a Resume. class Resume(models.Model): owner = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="resume", ) description = models.TextField(default="Resume description") skills = models.ManyToManyField(Skill, related_name="resume") The Resume object is referenced by another model called WorkExperience: class WorkExperience(models.Model): ... skills = models.ManyToManyField(Skill, related_name="work") owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) resume = models.ForeignKey( Resume, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) Notice that there's a fair amount of redundancy here, with both Resume and WorkExperience pointing to the same owner etc. That said, both of these Models (Resume & WorkExperience) have a field called Skills. That reference another Model called Skills. What I'd like is to have the Resume skills to point to the same skills as the ones in WorkExperience. Any suggestions on how to do this? I also have a Model called EducationExperience which also references Skills and has a foreign key relation to Resume. Is there any way to keep the skills in Resume be in sync with both the skills in WorkExperience … -
Pytest Django: access database but not in a transaction
According to the documentation of pytest.mark.django_db https://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-request-database-access, using pytest.mark.django_db Each test will run in its own transaction This makes it tricky to test certain behaviours with multiple sessions [say, with others started in other threads]. Specifically, if production code uses autocommit, which is the default, changes due to database statements become visible to other sessions immediately. However, in the test, changes in the main session won't be visible to others since the first is wrapped in a transaction. However, if I don't use pytest.mark.django_db, then running the test I get the error: RuntimeError: Database access not allowed Is it possible to have database access, but not in a transaction? -
"detail": "Authentication credentials were not provided." test.py
I am writing a test in test.py like this class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.login(username=self.username, email=self.email , password=self.password) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_create_todo(self): self.client.force_login(user=self.user) response = self.client.post(self.url, {"list_name" : "Clean the room!"} format='json', HTTP_AUTHORIZATION='jwt {}'.format(self.token)) self.assertEqual(201, response.status_code) and this always gives 401 in return. how I can authenticate properly user here. any kind of help would be highly appreciated . -
Django - public profile with slug - how to use two user models?
I've created a public profile with slug -> .../slug of user/ My issue is how I can know if current_user (user of the slug of the page has an active story): {% if current_user.story.is_active %}new_story_available{% else %}no{% endif %} That does not work because current_user is related to userprofile models. Does anyone has an idea? user.views.py @login_required(login_url='/cooker/login') def userpublicpostview(request, slug): user = get_object_or_404(User.objects.select_related('userprofile'), username=slug) ... storys = Story.objects.filter(user_id=user.id) return render(request, 'user_public_profile.html', { 'current_user': user, ... 'user_storys': storys, }) user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ... is_online = models.BooleanField(default=False) slug = models.SlugField(editable=False) class Story(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE,related_name='user_storys') title = models.CharField(max_length=200, unique=False) image = models.ImageField(upload_to='story/') created_on = models.DateTimeField(auto_now_add=True) @property def is_active(self): now = timezone.now() if (self.created_on + timedelta(days=1)) > now: return True return False -
Display an inherited Field in Django ModelAdmin
I have models.py file as follows. from django.db import models class UpdateCreateModelMixin: created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Question(UpdateCreateModelMixin, models.Model): name = models.CharField(max_length=100) code = ... ... (Some more field) How do I display the updated, created fields in the Django model Admin, my admin.py file is from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): list_display = ('name', 'created', 'updated') list_filter = ('created') admin.site.register(Question, QuestionAdmin) For the above admin.py file I am getting this error. <class 'assignments.admin.QuestionAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'created', which does not refer to a Field. So, how do I add an inherited fields in the django model Admin and why is the above failing? -
how to put tags in articles in python django in website
my client want me to build an article post website in which the user come and login and write the articles.in article he must put tags and with those tags the other users can search. the problem is i do not know how to put tags in views. and also in html .enter image description here and my views file is: enter image description here can any body please help me with sample coding -
How can i make a post request to a rest api endpoint and the request to save my form in a view file in django?
So i am trying to send a JSON file to a rest API endpoint and i am trying to use the requests library and it doesn't work. Also in the function i have a return render to another page, because when i save a form i want also to send a request to the rest api to send an email and they only send emails via the endpoint. from django.shortcuts import render from django.views.generic import View from Upload_Page import models from django.core.files.storage import FileSystemStorage from Upload_Page.forms import Upload_Document from django.shortcuts import redirect #from django.core.mail import send_mail from Upload_Page.mail import mail_class import requests import json def upload_doc(request): if request.method == 'POST': form = Upload_Document(request.POST, request.FILES) if form.is_valid(): form.save() mail=mail_class() jsonmail=mail.createSimpleMail() requests.post("http://mail.internal.de1.bosch-iot-cloud.com:80/email",data=json.dumps(jsonmail)) #send_mail('Title','Body','DigitalLibrary.BoschECC@bosch.com',['fixed-term.Razvan.Sabou@ro.bosch.com'],fail_silently=False) return render(request,'Upload_Page/upload_successful.html') else: form = Upload_Document(auto_id=True,label_suffix='') return render(request, 'Upload_Page/upload_page.html', {'form':form}) So this is the code, and i do not know why it doesn't send the post request, i checked the terminal to see what requests are made and the request from the requests it doesn't appear. I've searched but i am new in django and Rest API and i didn't find the answer for my problem, if you need any more information i can provide it to you. So … -
Feeding json data from Django into jquery function
I am implementing some jquery code for filtering, which initially takes data from a json file: function getProducts() { $.get("products.json", (products) => { ...; }) However, instead of fetching a json file, I'd like to use a json-like array and use that instead of the json file. This data would come from the Django backend, which would pass the data onto the html template. Something like this: var products = {{jsonData}} which would then be this: var products = [ { "id": 1, "category": "shirts", "name": "Fantasy T-shirt", "rating": 4, }, { "id": 2, "category": "hoodies", "name": "Wolf Hoodie", "rating": 5, }, ] How could I modify the jquery code to accept that? Thanks! -
My site is not available after installing Let's Encrypt certification
I am a beginner in web development. I built a site with Django, saw that my site was not fully secure, found out the following tutorial and installed certbot on my server. https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04 I followed all the guideline in that tutorial and it worked fine with no error, but after that, my site is completely inaccessible on any devices(it's not a problem of cache I think). I used lightsail AWS, ubuntu 18.04 and nginx, and my server block content is: server { server_name 1.23.456.7 mysite.com www.mysite.com; location = /favicon.ico {access_log off; log_not_found off; } location /static { alias /home/ubuntu/projects/mysite/static; } location / { include proxy_params; proxy_pass http://unix:/tmp/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certb$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name 1.23.456.7 mysite.com www.mysite.com; return 404; # managed by Certbot } I have absolutely no idea on how to solve the problem. Please help me. -
Calling Django function with Angular button
I am trying to add Django to Angular. I have set up Angular web page already, and it has been running for quite awhile without any problems. I just have to add a button in Angular that is going to call python function. I searched for a way to do that, and it seems python Django is a popular way to do it. So, I have been reading and following with github open sources. I can start a new django project and starting from there, I can integrate Angular and Django just fine. But, when I tried to integrate Django into existing Angular project, that is where I have some problems. From what I saw in open sources, I think the below structure is correct. But, what I do not get is how to call a python function in views.py in django from all the way in page.html that is located in src folder (Angular side). project-ui server src app core page page.html ui_python - templates - ui - urls.py - views.py - ui_python - urls.py - manage.py in ui_python/ui/urls.py, I have urlpatterns = [path('helloworld/', views.HelloWorld, name='test')] in ui_python/ui/views.py, I have def HelloWorld(self, request): data = 'Hello World' print(data) return … -
how to allow user to update his/her own record in django
I have managed to develop a django application where a user can sign up and login using django authentication. Now i want to create a form for the user update his/her record after login based on the user model. Please help me how i will create the UpdateProfile form, loading the form in the profile.html view and updating the record when the user clicks update record button. My sign up form from django import forms from django.contrib .auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name=forms.CharField(max_length=30, required=True, help_text='Enter your first name.') last_name=forms.CharField(max_length=30, required=True, help_text='Enter your last name.') email=forms.EmailField(max_length=254, help_text='Enter a valid Email') class Meta: model=User fields=('first_name','last_name','email','username','password1','password2') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control'}), 'username': forms.TextInput(attrs={'class': 'form-control'}), 'password1': forms.TextInput(attrs={'class': 'form-control'}), 'password2': forms.TextInput(attrs={'class': 'form-control'}), } My profile function def profile(request): if request.method == 'POST': form = UpdateProfile(request.POST) if form.is_valid(): form.save() return redirect('profile') form = UpdateProfile() return render(request, 'profile.html', {'form': form}) else: form = UpdateProfile() return render(request, 'profile.html', {'form': form}) -
Django define which urls loaded and which temolate show
i have many html files (all of them are same) i useing base.html , but i want to define which html show, for examole when something.com/love loaded show love content, if something.com/game loaded show game content. how define this? and where define? in views.py or in html? {% for lov in lovess %} {% if forloop.last %} love Content text{{lov.body_text}} {% endif %} {% endfor %} if game urls loaded shows game body text. i do not want to copy paste and create many html files (DRY) , i want to used one basic which are extends in html files. -
django-channels. Is it possible to combine sending/receiving messages to one method?
I have some complex logic that I need to handle after my code receive some message from channel layer: send a request to client through websocket, wait for response, send another request, wait again, then send response back through a channel. Right now the only way I found is to split all logic to a bunch of smaller methods and to use lock to sync all. It's working but looks ugly. Is it possible to write something like that? async def complex_logic(self, data): with self.lock.acquire(): await self.send_ws_request1(data) resp1 = await self.get_ws_response1() data2 = self.do_something_with_resp(resp1) await self.send_ws_request2(data) resp2 = await self.get_ws_response2() await self.send_resp_to_channels(resp2) -
How to convert boostrap template to pdf in django
I have invoices bootstrap template in which data come with ajax response after invoice filled with response data then i want to convert that exact template with its css into pdf, so i can send it through email using django server. Is there is anyway to convert template with its data and css into pdf. I tried so many things but can't get desire result. I want exact pdf of this invoice with css. Thanks in adnvance. -
Suspicious file operation : Cannot configure media root and base dir in my django Project folder
I am trying to save the project files to media then grap to show in url, so far i have followed some easy techniques to avoid the file operation and stored them in media my setting.py file-> STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my models.py files model fields-> picture = models.ImageField(null=True, blank=True, upload_to = "photos") resume = models.FileField(null=True, blank=True, upload_to = "resume") It stores then correctly and shows as media url. my urls.py file-> from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/cand/',include("core.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) main problem happens when i query a resume pdf file. It can't find the BASE_DIR from django.conf import BASE_DIR url = serializer.data["resume"] file_name = url.split("/")[-1] data=ResumeParser(os.path.join(BASE_DIR,"/media/resume/",file_name)).get_extracted_data() return Response({**serializer.data, "data": data}, status = status.HTTP_200_OK) Although it works when i use absolute path-> url = serializer.data["resume"] file_name = url.split("/")[-1] data=ResumeParser("/home/riyad/Desktop/kalkedev/services/candidate","media/resume/",file_name).get_extracted_data() return Response({**serializer.data, "data": data}, status = status.HTTP_200 _OK) is this is a django issue because i have been dealing with this issur previously and taking the easy way(default base_dir) to store file. Need to find the answer quick. -
Django Forms posting not working - Django simply renders the page again
Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working. See my code below: models.py from django.db import models from accounts.models import User from datetime import datetime, date #// ------------ FUNCTIONS -------------// # Generate Organisation IDs for each organisation def org_id_generate(): last_org = Organization.objects.all().order_by('org_id').last() if not last_org: return 'ORG_001' else: last_org_id = last_org.org_id number_in_id = int(last_org_id[4:7]) new_number_in_id = number_in_id + 1 new_org_id = 'ORG_' + str(new_number_in_id).zfill(3) return new_org_id #// ------------ MODELS -------------// class Organization(models.Model): org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False) organization_code = models.CharField(max_length=20) company_name = models.CharField(verbose_name="Company Name", max_length=60) legal_name = models.CharField(verbose_name="Legal Name", max_length=100) industry_distribution = models.BooleanField(verbose_name="Distribution", default=False) industry_education = models.BooleanField(verbose_name="Education", default=False) industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False) industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False) industry_retail = models.BooleanField(verbose_name="Retail", default=False) industry_services = models.BooleanField(verbose_name="Services", default=False) business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True) vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True) created_date = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By") effective_start_date = models.DateField(auto_now_add=False) effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True) update_date = models.DateTimeField(default=datetime.now) last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By") def __str__(self): return self.company_name forms.py from django import forms from organizations.models import Organization class OrganizationAddForm(forms.ModelForm): class Meta: model = Organization exclude = … -
input type="submit" doesn't show full text
and I have a list of element {{FieldName}}. when I use this list inside an input it shows just the first Word not all text? my code {% for con2 in FieldName %} <table style="border-width: 2px; border: #333;"><tr> <input type="submit" value= {{con2.FidlAbr}} name="FieldName" style="width:200px;"></tr></table> {% endfor %}</form> </div></div></div> the output should be like: BEQ , HMZ , TFT DEVO 100 , TIM SNAGUENE , TFNW , TRNW but it gave me an output like!! BEQ , HMZ , TFT, TIM, TFNW , TRNW what is the problem with it? -
How to get highest rated comment for another model through Django ORM?
This is a pretty straight forward issue but I don't know why prefetch related isn't working for me. My relevant models: class Aritcle: pass class Comment: num_likes = models.IntegerField(default=0) pub_date = models.DateTimeField('date published') word = models.ForeignKey(Article, on_delete=models.CASCADE) I want to return a list of Articles, and for each article the highest rated comment on that article (max num_likes). I have a QuerySet[Article] called search_results. I keep trying: search_results.prefetch_related( Prefetch('comment_set', queryset=Definition.objects.order_by('-num_likes').first(), to_attr="top_comment") ) But it doesn't seem to work. I've tried to use the attr and it gives me an attribute error: for article in search_results: print(article.top_comment) generates: AttributeError: 'Article' object has no attribute 'top_comment' I've tried with arbitrary query sets, doing Comments.objects.filter('pub_date') but nothing seems to work