Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn error 203 while setting up django project
I try setting up a django project with nginx and gunicorn but get a gunicorn error 203: My installation is located at path /webapps/sarlex and all project files are owned by user "sarlex" and group "webapps". The virtualenv is located at /webapps/sarlex/environment. Gunicorn is located at /webapps/sarlex/environment/bin/ and owned by user sarlex. Gunicorn confirmation is set in /webapps/sarlex/gunicorn_start.sh: NAME="sarlex" # Name of the application DJANGODIR=/webapps/sarlex/ # Django project directory SOCKFILE=/webapps/sarlex/run/gunicorn.sock # we will communicte using this unix socket USER=sarlex # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=9 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=sarlex.settings # which settings file should Django use DJANGO_WSGI_MODULE=sarlex.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /webapps/sarlex/environment/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Executing gunicorn_start.sh works with environment activated and deactivated. /etc/systemd/system/gunicorn.service is owned by root and has this content: [Unit] Description=gunicorn daemon After=network.target [Service] User=sarlex Group=webapps WorkingDirectory=/webapps/sarlex ExecStart=/webapps/sarlex/gunicorn_start.sh [Install] … -
Contacts matching query does not exist in django rest framework
I am trying to update Contact model fields while creating the new fields of UpdateInfo model and add them to the existing model. But I am getting this error contacts.models.Contacts.DoesNotExist: Contacts matching query does not exist. I know the contact object with the id 19 exists because I can see it when I try the get contacts API. I am sending data like this. My models: class Contacts(models.Model): full_name = models.CharField(max_length=100, blank=True) ......... def __str__(self): return self.full_name class Meta: verbose_name_plural = 'Potential Clients' class UpdateInfo(models.Model): contacts = models.ForeignKey(Contacts,on_delete=models.CASCADE, related_name='update_info') updated_at = models.DateTimeField(auto_now=True) modified_by = models.CharField(max_length=100, blank=True) def __str__(self): return f"Last modified by {self.modified_by} at {self.updated_at}" My views: class EditContactView(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Contacts.objects.all() serializer_class = ContactsUpdateSeializer My serializers: class UpdateInfoSerializer(serializers.ModelSerializer): contacts= serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = UpdateInfo fields = ['id','contacts','updated_at','modified_by'] class ContactsUpdateSeializer(serializers.ModelSerializer): update_info = UpdateInfoSerializer(many=True) id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Contacts fields = ['id', 'full_name', 'lead_source', 'email', 'phone', 'contact_owner', 'contact_status', 'company_name', 'job_position', 'tasks', 'notes', 'email_list', 'created_by', 'created_at', 'update_info'] def update(self, instance, validated_data): update_data = validated_data.pop('update_info') id = validated_data.get('id') contacts = Contacts.objects.get(id=id) #contacts.save() #contact_only_update_logic instance.full_name = validated_data.get('full_name') instance.lead_source = validated_data.get('lead_source') instance.email = validated_data.get('email') instance.phone = validated_data.get('phone') instance.contact_owner = validated_data.get('contact_owner') instance.contact_status = validated_data.get('contact_status') instance.company_name = validated_data.get('company_name') instance.job_position = … -
Django rest framework legacy DB foreign keys appearing as Null on API
I am using django connected to a legacy mysql DB. So i used inspectdb to get the DB tables. There are 2 models that I am using: class ScCustomerTypes(models.Model): customer_type_id = models.AutoField(primary_key=True) customer_type = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'sc_customer_types' class ScCustomers(models.Model): customer_id = models.CharField(primary_key=True, max_length=100) identification_number = models.CharField(unique=True, max_length=100) customer_type = models.ForeignKey('ScCustomerTypes', models.DO_NOTHING, related_name='customer_types2customers', to_field='customer_type_id') customer_names = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) location = models.CharField(max_length=100, blank=True, null=True) created_by = models.CharField(max_length=100, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) updated_by = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'sc_customers' Using the above I made the below serializer: from rest_framework import serializers from allDBModels.models import ScCustomers, ScCustomerTypes from employees.serializers import AllEmployeeSerializer class AllCustomerTypesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ScCustomerTypes fields = ('customer_type',) class AllCustomerSerializer(serializers.HyperlinkedModelSerializer): customer_type_id = AllCustomerTypesSerializer() class Meta: model = ScCustomers fields = ('customer_id', 'customer_type_id', 'customer_names', 'phone_number', 'identification_number', 'location', 'created_by', 'created_at', 'updated_by', 'updated_at',) Issue now is when i pull the api it returns as such: { "customer_id": "ICXY38ZP", "customer_type_id": { "customer_type": null }, "customer_names": "Test xxxxxxxxxxx", "phone_number": "2547xxxxxxx", "identification_number": "yyyyyyyyyy", "location": null, "created_by": "3b1e3f79", "created_at": "2020-10-20T13:58:21Z", "updated_by": null, "updated_at": null }, The issue is that its not returning the customer_type. … -
Django won't redirect bu urls
I am currently working on a project called NewsPaper. I bet there is a lot of works about this here. After adding a post, I have a button that subscribe the user to the category presented in the post. But, when it comes to redirect, It doesn't work at all. From my point of view, when I add a post, the "category" in Post.model doesn't refere to "category" in Category.model, and the subscribeView won't call Models.py # Create your models here. from django.urls import reverse class Author(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.author}' class Category(models.Model): category = models.CharField(max_length=255, unique=True, default='select category') subscribers = models.ManyToManyField(User, related_name='subscriber', ) def __str__(self): return self.category class Post(models.Model): news = 'news' article = 'article' Posts = [(news, 'news'), (article, 'article'), ('select', 'select')] author = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='User', blank=True, null=True) choosing = models.BooleanField(default=False) time_in = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255, unique=True) text = models.TextField(max_length=255) rating = models.FloatField(default=0.0) def __str__(self): return f'{self.title}: {self.text[:50]}' def get_absolute_url(self): return f'/Posts/{self.id}' Views.py # Create your views here. class Post_List(ListView): model = Post template_name = 'News/post_list.html' context_object_name = 'Posts' queryset = Post.objects.order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['time_now'] = datetime.utcnow() return context class Post_detail(DetailView): model = Post … -
Where can I find training materials on django-otp? [closed]
I received a test task from a potential employer - to implement otp authorization in django. I completed this task through the service api.msg91.com. In the Internet I found information about the existence of the django-otp package. But I didn't find any material that I could understand about it. Please share the training materials on django-otp? Is this really a used tool? -
Reverse for 'detail_view' with keyword arguments '{'pk': 11}' not found
I am building a BlogApp and I am stuck on a Error. What i am trying to do :- I just add slug into my model and also updated get_absolute_url and url. BUT after that whenever i try to open page in browser then it shows Reverse for 'detail_view' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['detail_view/(?P[-a-zA-Z0-9_]+)/(?P[0-9]+)$'] models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') slug = models.SlugField(null=True) def get_absolute_url(self): return reverse('detail_view',kwargs={'pk':self.pk,'slug':self.slug}) views.py def detail_view(request,pk,slug): data = get_object_or_404(Post,pk=pk) urls.py path('detail_view/<slug:slug>/<int:pk>',views.detail_view,name='detail_view'), template.html <a href="{% url 'detail_view' pk=topic.pk %}">More</a><br> I have no idea what is causing this error. Any help would be Appreciated Thank You in Advance -
twillio sending message via Browser
I have implemented a Django app for sending SMS via browser, The app is working fine when I have a custom message defined from the codes. The issue is that the view codes cannot read the message input from the browser for sending. VIEWS CODE def pastor_send(request): #recepient=Ministry.objects.all() template_name='corecode/pastor.html' if request.method=='GET': message=request.GET.get('sms') client = Client(settings.ACCOUNT_SID,settings.AUTH_TOKEN) message = client.messages \ .create( body=message, from_='+somenumber', to='somenumber' ) return render(request,template_name) return HttpResponse("Message sent Succesfully",200) HTML CODE {%extends 'base.html'%} {% load crispy_forms_tags %} {%block title%} Send to Ministry Pastors {%endblock%} {%block content%} <h4><b>Create the message here<b></h4> <br> <form method='GET'> <textarea id="w3review" name="sms" rows="7" cols="70" value="{{request.GET.q}}"> </textarea> <br> <br> <a class="btn btn-primary" href="{% url 'p-sms' %}"><i class="nav-icon fas fa-sms"></i> Send</a> </form> {%endblock%} -
how to solve NOT NULL constraint failed error in django models.py
I don't want to print 'NULL' value in my django template, so I set the model property to null=False. However, during the process of adding data by uploading a file, a NOT NULL constraint failed: error is displayed. Is there a way to upload data without outputting 'NULL' to the database and template? -
Which is the better way to create a follower-following system, Foreign Key vs ManyToMany in django?
Which one would be optimal for creating the followers-following system in Django. 1.Foreign Key class Follower(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') following = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') 2.Many-To-Many class Follower(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') users = models.ManyToManyField(User) -
Logout one session with cookie domain set in Django
The host of two project are af-abc.com and abc.com. And set SESSION_COOKIE_DOMAIN SESSION_COOKIE_DOMAIN = ".abc.com" to share cookie in these two domain. My question is how to logout one project with it's own session cleared? I mean if I can keep loging in af-abc.com as I logout abc.com -
Django queryset filtering is not working after .union()
The Set-Up: I have a situation where I filter out several querysets as usually, all from the same User model. Eg: if my_events: for event in my_events: users = User.objects.filter(attended_events__event=event).values("first_name", "last_name", "email", "phone_number", "attended_events__event__start_dt", ) list_of_user_qs.append(users) Then I union the querysets like so: final_qs = QuerySet for qs in list_of_user_qs: final_qs = final_qs.union(qs, all=True) so far all good. I keep all the records because in the next step I am counting email occurrences. I spent some time on trying to count occurences of the same email as I would usually but after unioning some methods do not work as usual but that is fine, I will do it manually. For that, I have the following code: emails_used = [] for obj in final_qs: the_email = obj["email"] if the_email in emails_used: pass else: obj["total_count"] = len(final_qs.filter(email=the_email)) user_activity = final_qs.filter(email=the_email).order_by("-attended_events__event__start_dt").first() user_activity["total_count"] = final_qs.filter(email=the_email).count() user_activity["last_visit"] = user_activity["attended_events__event__start_dt"] qs_with_count.append(user_activity) emails_used.append(the_email) What I am trying to do here is first get user email (always present as it is required). Then I check if the user with the email was already evaluated (because the email would be in the emails_used list. Now comes the strange part. Question: Although I filter the final_qs with the current email … -
python django admin - error when list-filter value is empty
I am decorating change_list_template = "admin/user_joined_status.html") by specifying a template in Admin. If I specify a date using list_filter = [("user_join_dts", Date RangeFilter)] of django admin, the count value that I want for the specified date will come out. The problem is, as on the capture screen, [range_gte_date_time = datetime.strptime (range_gte_string, "%Y-%m-%d")] when the date is not selected. There is an error from here. I don't know how to avoid errors when I don't choose a date. Please help me... admin.py @admin.register(UserJoinedStatus) class UserJoinedStatusAdmin(admin.ModelAdmin): list_filter = [("user_join_dts", DateRangeFilter)] list_display = ["id", "user_join_dts"] change_list_template = "admin/user_joined_status.html" def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} pro_today_secession = User.objects.filter( secession_dts__year=today.year, secession_dts__month=today.month, secession_dts__day=today.day, user_ty="US200200", ).count() pro_total_secession = User.objects.filter( is_secession=True, user_ty="US200200" ).count() pro_is_active_total = User.objects.filter( is_active=True, user_ty="US200200" ).count() ### Start the problem down here.### range_gte_string = request.GET.get("user_join_dts__range__gte") range_gte_date_time = datetime.strptime(range_gte_string, "%Y-%m-%d") range_lte_string = request.GET.get("user_join_dts__range__lte") range_lte_date_time = datetime.strptime(range_lte_string, "%Y-%m-%d") golfer_filter = User.objects.filter( user_join_dts__range=(range_gte_date_time, range_lte_date_time), user_ty="US200200", ).count() extra_context.update( { "pro_today_secession": pro_today_secession, "pro_total_secession": pro_total_secession, "pro_is_active_total": pro_is_active_total, "golfer_filter": golfer_filter, } ) return super().changelist_view(request, extra_context=extra_context) -
unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'
I have model it is have two MantToManyField, How I can sum or compain this two fields, there is number for each field, I want to have have result of sum this fields. My model class Video(models.Model): viewers = models.ManyToManyField(Account, related_name='video_views') viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) My view video_viewers_ip = video.viewers_by_ip.all() video_viewers = video.viewers.all() video_views = video_viewers_ip + video_viewers Or how to get the result number in a new field num_viewers = models.IntegerField('viewers_by_ip' + 'viewers') -
How to get value inside a div element using JS
Here I have a div element with class med and I want to access the value inside the div of the Prescribed:{{pro_id.prescribedmed}} .I tried JS to get the value by using the getattribute() but it does not show. how can get the value of it. Here is the piece of code <div class="column"> <!-- style="background-color:#bbb; --> <p class="newarrival ">Rs.{{pro_id.price}}</p> <h4>{{pro_id.name}}</h4> <p><strong>Category:</strong> {{ pro_id.category}}</p> <p><strong>Description:</strong> {{pro_id.smalldescription}}.</p> <div class="med hidden" > <p>Prescribed:{{pro_id.prescribedmed}}</p> </div> <button data-product={{pro_id.id}} data-action="add" type="button" class="btn-cart update-cart"> Add to cart </button> </div> i tired to get the element like var premed = document.getElementsByClassName('med').innerText; console.log(premed) here the output gives like undefined -
Set cookie domain in Django project
The host of two project are af-abc.com and abc.com. How to set SESSION_COOKIE_DOMAIN to share cookie in these two domain? -
django admin change form/update model form Violation of PRIMARY KEY constraint with ms sql backend
When I try to edit and update the form in django admin, I am getting IntegrityError at /admin/core/courses/144103/change/ ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK_dbo.Courses'. Cannot insert duplicate key in object 'dbo.Courses'. The duplicate key value is (144103). (2627) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") The admin model form has 2 inlines in it. Not able to understand why the issue is arising. I am not overriding any default behavior. -
How to retrieve data in the template from a custom MariaDB connector? (Django)
I have implemented the following connector following the MariaDB documentation. Documentation This is my db.py: #!/usr/bin/python import mariadb conn = mariadb.connect( user="user", password="", host="localhost", database="db") cur = conn.cursor() def get_some_data(): cur.execute("SELECT some_id FROM `db`.some_data") sid = [] for some_id in cur: sid.append(some_id) return sid conn.close() So far everything is clear, what I am not clear about is...how can I show in a html select a list with the values obtained from the query to the database on my django web page? Should I create a function in views.py and have it return something like this ?: def retrieve_from_db(request): #some code here return render(request, 'index.html', context) Do I need a context? Let's say my index.html is the following, how could I call retrieve_from_db(request) from the template and make this function call get_some_data() and display this information on the web? index.html {% extends "../base.html" %} {% load static %} {% load bootstrap4 %} {% block content %} {% bootstrap_javascript %} //Some form to retrieve the data from the .py scripts <form id="retrieve_db" action="someaction?" method="post"> <div class="form-group"> {% someforloop? %} <select name="myIdList" id="myIdList"> <option value="{{ some_id }}">{{ some_id }}</option> </select> {% endforloop %} </div> </form> {% endblock %} Let's say I want the … -
Django formset exclude fields will not be validated
I have this in my view: Itemform = modelformset_factory(OrderItems, form=OrderItemsForm, extra=ProductsCount, exclude=['OrderNo']) I set the value of OrderNo in the form.save methode: if Orderform.is_valid(): edit_form = Orderform.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id instances = Formset.save(commit=False) for instance in instances: instance.OrderNo = Orders.objects.get(ID=edit_order_id) instance.save() But it goes not in the for loop because I get this error: The OrderItems could not be created because the data didn't validate. [{'OrderNo': ['This field is required.']}, {'OrderNo': ['This field is required.']}] If I exclude this field should it not be ignored? If I render the FK Field OrderNo and choose the latest order it goes throw the loop and override the value but it's not helping if there was never a order. -
FieldDoesNotExist: User_balances has no field named 'None' - ManyToManyField
I am having a difficulty with a ManyToManyField and cannot seem to figure out how to fix this. When I access the ManyToManyField I get this error Models class AccountBalance(BaseModel): user = models.ForeignKey( User, verbose_name=_('Account Owner'), on_delete=models.PROTECT, limit_choices_to{'is_staff': False}, help_text=_("""The owner of Account Balance.""")) class User(AbstractBaseUser): balances = models.ManyToManyField( AccountBalance, verbose_name=_("Account Balances"), related_name="account_balances", help_text=_("Account balances held by user.") ) Accessing User.balances or User.balances.all() etc. returns this error FieldDoesNotExist: User_balances has no field named 'None' What am I doing wrong here. I need help. Cannot seem to find any assistance even going through other suggestions, returns same error -
Django RestFramework: Token auth errors returning HTTP response instead of JSON
I have a DRF backend with a Vue frontend. It has been working for a while (alpha test), but I am trying to thoroughly test the authentication of the site. I login as a test user, then go directly to the database and delete that user from the authtoken_token table. I then hit a backend endpoint to see what error I get. I'm getting an AuthenticationFailed message, but it is an HTTP response, not JSON. Also, it is a "500 Internal Server Error" instead of a 401 or 403. Looking at the handle_exception() method (rest_framework/views.py), I see that it is checking for NotAuthenticated and AuthenticationFailed exceptions, so it should match the actual exception of AuthenticationFailed. def handle_exception(self, exc): """ Handle any exception that occurs, by returning an appropriate response, or re-raising the error. """ if isinstance(exc, (exceptions.NotAuthenticated, exceptions.AuthenticationFailed)): # WWW-Authenticate header for 401 responses, else coerce to 403 auth_header = self.get_authenticate_header(self.request) if auth_header: exc.auth_header = auth_header else: exc.status_code = status.HTTP_403_FORBIDDEN exception_handler = self.get_exception_handler() context = self.get_exception_handler_context() response = exception_handler(exc, context) if response is None: self.raise_uncaught_exception(exc) response.exception = True return response How to ensure I get a JSON response? -
Celery with django and rabbitmq as broker is skipping every alternate task
I have integrated celery with a Django application. Here I am using RabbitMQ as message broker. I am getting a strange issue on Linux . Celery is processing alternate requests only (First request, third request, Fifth Request) -
loop over a dictionary for specific(say first 3) values and then loop again for the next (next 3) values and iterate till the end in django template
My dictionary named 'data' can have any number of values that is multiple of 3(say, it can have 3 or 6 or 9 values). And the keys are like 1,2,3, and so on. I would like to loop over the dictionary for the first three values, then for the next three values and so on. I tried the following code but it's not working and i also don't know how to iterate for the next three values. {% for key,value in data.items %} <td>{{ value }}</td> {% if key%4==0 %} {% break %} {% endfor %} I also tried declaring variable inside django template and use it as a key to access dictionary values but it didn't work either: {% with k=1 %} <td>{{ data.k }}</td> {% k=k+1 %} <td>{{ data.k }}</td> {% k=k+1 %} <td>{{ data.k }}</td> {% endwith %} Any ideas? Thanks in advance. -
How I can count the video views in django by ip for Anonymous users
I created a view to get the Anonymous users IP, I want when this user what the video then register this ip has watched the video,I know it's now efficient because might the user use diffrent network, This my model of the user by ip: class UsersByIP(models.Model): ip_user = models.GenericIPAddressField() def __str__(self): return self.ip_user This model to make relationship between the vdeo and the number of viewrs by ip class Video(models.Model): viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) I created this view to register the ip as view but I got this error: Field 'id' expected a number but got '127.0.0.1' and I couldn't solv it. The view: num_views_by_ip = Video.objects.annotate( num_views_ip=Count('viewers_by_ip'), ).order_by('-viewers_by_ip') data = get_object_or_404(num_views_by_ip, pk=pk) ip_user = UsersByIP(ip_user=request.META.get('REMOTE_ADDR')) if not request.user.is_authenticated: __, created = Video.viewers_by_ip.through.objects.get_or_create( video=data, usersbyip=request.META.get('REMOTE_ADDR') ) if created: data.num_views_by += 1 I would like to get any suggestions to solve this view or make a new view (logic) -
Django is sending error mails to admins but they don't reach Sentry
We have a site in production where Sentry is enabled but strangely some of the errors are not being reported to Sentry but are only being sent as emails to the admins set in the settings. Which logger settings we need to change so that only Sentry is used and no direct emails are sent? Our project is based on the cookiecutter-django code base. This is our current logger settings: General logger settings: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, } and the Sentry config: SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.WARNING, # Send errors as events ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) -
How can I filter questions that are answered/unanswered?
In attempting to replicate the unanswered QuerySet functionality of Stack Overflow, I'm left stuck how this would be done at the table level? How would I go about implementing a QuerySet where it returns all unanswered questions when the Question model doesn't have any foreign key reference to Answer on the table itself? It's only when an individual question has been queried that reverse relationship of answers can be accessed. class QuestionStatusQuerySet(models.QuerySet): def unanswered(self): pass def newest(self): pass class Question(models.Model): title = models.CharField(unique=True, max_length=50) body = models.TextField() dated = models.DateField(default=date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answers" ) response = models.TextField() dated = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="answers" ) class Meta: ordering = ['-likes']