Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Including the current date in TimedRotatingFileHandler
Is it possible to somehow overwrite the functionality of Django's TimedRotatingFileHandler method to include the date in the current iteration of the file? By which I mean, have the current filename be dated as mylog.log.YYYY-MM-DD as opposed to just mylog.log with the date being added in when it gets rotated out? Here is my basic code I am using: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'session': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/efs/mylog.log', 'when': 'midnight', # this specifies the interval 'interval': 1, 'backupCount': 1, }, .... -
Integrating Angular 2 frontend with python app
I'm supposed to make an Angular client app, and integrate it with a python server, and not sure if I should also consider using any python framework (such as Django or Flask) alongside my frontend framework. I've got some minimal experience with making Django apps, but not sure what would be the profit of using it just for the frontend and not as a fullstack framework. Using angular on the front means rendering the data on the front (in contrast to classic django design), so is there any good reason to use django on my backend over just a plain python environment? Is it easier to make an API using django for example? Another basic question that might sound a little stupid but stems from the fact that i'm new to web development, is where is the server-side code of a regular angular app is sitting? or in other words, what is "ng serve" command doing in the background? (as i guessed it runs a server). But this question is just for general understanding. And lastly, in either way, should the architecture for this kind of app be creating an standalone angular app for the front, whilst making another standalone … -
Change the appearance of labels and input fields (from a Model Form) used in a DJango template
I am using a script below (that resides in a DJango template) to display input fields that are associated with a particular Model Form. The purpose of this template is to add and modify data for a Model. The name of the template is : model_name_form.html (ex: customer_form.html for the Model representation of the table Customer) In order to add/modify data, the Model Form is being used. The problem is that when using the script below, a type of default presentation is being used for the fields. In my case, the fields need to be more customized. The customized labels and input fields make the form look much nicer. I start out with this (which is in the template that displays the form): {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small"> {{ field.errors }} </span> </div> <label class="control-label col-sm-2"> {{ field.label_tag }} </label> <div class="col-sm-10"> {{ field }} </div> </div> {% endfor %} Which turns into this: <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small"> </span> </div> <label class="control-label col-sm-2"> <label for="id_companyname">Company Name:</label> </label> <div class="col-sm-10"> <input name="companyname" id="id_companyname" type="text" maxlength="30"> </div> </div> But what is needed is a label/input presentation similar to the … -
Django Queryset for concat query fullname of first_name and last_name
I would like to do a fullname (first_name concat last_name) search/query in Django. The following is my model: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) created_at = models.DateTimeField(auto_now_add=True) For example we have an entry like this. first_name:"Michael", last_name:"Jackson" I want to be able to query full name "michael jackson". If can show without case sensitive would be great as well. This other stackoverflow question is similar but the answers is not fulfilling this particular requirement Querying full name in Django. We want to be able to do a concat search. -
psycopg2.ProgrammingError: column of relation does not exist
Trying to insert data into PostgresSQL database. Python code: myFields = ((DOT_Number,),(Entity_Type,),(Operating_Status,),(Legal_Name,), (Phone,),(Address,) ) query = """ INSERT INTO saferdb_question( DOT_Number, Entity_Type, Operating_Status, Legal_Name, Phone, Address)VALUES ( %s, %s, %s, %s, %s, %s);""" cur.execute( query, myFields) Getting error: Traceback (most recent call last): File "scraper.py", line 189, in <module> cur.execute( query, myFields) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/psycopg2/extras.py", line 144, in execute return super(DictCursor, self).execute(query, vars) psycopg2.ProgrammingError: column "dot_number" of relation "saferdb_question" does not exist LINE 1: INSERT INTO saferdb_question( DOT_Number, Entity_Type, Oper... SQL from PostgreSQL that created the table: CREATE TABLE public.saferdb_question ( id integer NOT NULL DEFAULT nextval('saferdb_question_id_seq'::regclass), "DOT_Number" character varying(10) COLLATE pg_catalog."default" NOT NULL, ... "Phone" character varying(15) COLLATE pg_catalog."default" NOT NULL, "Address" character varying(200) COLLATE pg_catalog."default" NOT NULL, ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE public.saferdb_question OWNER to postgres; -
How tooutput what is being run for Django migrations
In Django 1.9.6 with MySQL 5.7, Django migrate task is taking so long and I'd like to review why so. Here are my commands python manage.py makemigrations python manage.py migrate And it seems to be stuck at: Operations to perform: Apply all migrations: webapi, customers, jobs, finance, installations, common, bills, corporate. Running migrations: <------- stuck here for 10 minutes I'd like to view what is going on and which migration is being run. Is there a way to enable it? -
Django image field default static file
I was wondering if there is a way to use an static image file as a default for an ImageField? I'm asking this because if you write something like this because first, I'm not able to upload media folder to my github repository because I store in there the user uploads, and the default file always be the same, so I want to serve the default from static but the user uploads from media directory. If you use this: image = models.ImageField(upload_to=/upload/folder/, default=/img/default.jpg, blank=True, null=True) It will try to load the default image from the media directory. -
Javascript and the Django 'static' template tag
I've got a wee site set up to play some sounds a list of which are passed forward by my view. I'm going to go straight into the code: var sounds = "{{js_sounds|escapejs}}"; sounds = JSON.parse(sounds); var howls = {}; sounds.forEach(function(sound){ howls[sound] = new Howl({ src: ["{% static 'audio/"+sound+".mp3' %}"] }); $(document).on('click', '#'+sound+'_btn_play', function(){ howls[sound].play(); }); $(document).on('click', '#'+sound+'_btn_stop', function(){ howls[sound].stop(); }); } Not the neatest solution - the html template also creates a bunch of buttons and things for playing the sounds, which my Javascript references in those on click functions. I'm also using the Javascript Howler library to simplify the playing of the sounds. Now, when I was testing this locally it worked perfectly, but after I deployed, a problem arose in the line src: ["{% static 'audio/"+sound+".mp3' %}"]. It seems like this is being executed weirdly, because rather than inserting the sound into the Django tag and executing it as one string, it seems to be executing it as: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"], i.e. attempting to parse the "+ as part of the string. I'm struggling to figure out why it's doing this when deployed but not locally. Also, any feedback on how to make this process … -
django rest django list query customize json array result response because of date formating
I have this Django REST API that I want to customize the list query result for the json response. The reason is because of date formatting and potentially other formatting as well. This is the Rest API, the issue is created_at I want it to formatted like this: ('%Y-%m-%d %H:%M'). The following code doesnt have any formatting, it will just list and create a json on the result. @api_view(['POST']) def employee_get_list_by_page(request): val_params = ["id", "username","first_name","last_name","created_at"] employee_list = Employee.objects.all().values(*val_params).order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(list(employees), status=status.HTTP_200_OK) This is the model. Notice I have .as_dict() function. For individual record like using emp = Employee.objects.get(id=6), I can do like this emp.as_dict() and the result will have the formatted date in created_at. class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username def as_dict(self): return {"id": "%d" % self.id, "username": self.username if self.username else "", "first_name": self.first_name if self.first_name else "", "last_name": self.last_name if self.last_name else "", "created_at":self.created_at.strftime('%Y-%m-%d %H:%M')} This is the json response result of the … -
Django empty a modal which contain an html
I am working with Django wherein I have a modal on a html page which includes the the html to be displayed when the modal is clicked. The modal is refreshed every 1 second until closed so as to get the latest data from the server. Now, when the modal is closed and clicked again for another link, the old data is still present and new data takes a second or two to be displayed. I want to know how we could empty the modal html before displaying the new data. My modal: <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="edit-modal"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" id="close" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 align="center" class="modal-title" id="gridSystemModalLabel">IP details</h4> </div> <div id="cats" class="modal-body"> {% include "ip_list.html" %} </div> <div class="modal-footer"> <button type="button" id ="close2" class="btn btn-primary btn-md" data-dismiss="modal">Close</button> </div> </div> </div> Here ip_list.html is the html file which gets called when the modal is clicked. Right below this I have my Jquery running to display the data. <script type="text/javascript"> $( document ).ready(function() { $("a").click(function() { var query; query = this.id; //console.log(query) $('#edit-modal').modal('show'); $.get('/reserve/get/', {'ip': query}, function(data){ $('#cats').html(data); //$('#edit-modal').modal('show'); var handler = setInterval(function(){ $('#edit-modal').modal('show'); },1000); $('#close').button().click(function (){ clearInterval(handler); //$('#edit-modal').modal('hide'); }); … -
Implementing python code in a website using django
As you can imagine I am a newbie regarding django, bootstrap and so on. I've developed a python code which interprets some data from various .csv files and displays it in a Excel file with multiple diagrams. Now I would like to create a sort of a admin website where users can log in, specify which data from the csv files they would like to examine and the website should show them that data in form of diagrams. Users should also have the possibility to save those diagrams as PDF's or Excel files. As a template I would like to use something like this: https://wrapbootstrap.com/theme/inspinia-responsive-admin-theme-WB0R5L90S. Where should I start and how? Do you have any recommendation or examples that I might look at to get some inspiration? Of course I found the django documentation but instead of directly starting with it, I thought I'd might ask more experienced developers. Thanks! -
Is it safe to make a empty field non-empty for a existing database?
Hi, I'm trying to alter my current django project schema, the data migration tool is south. django version is 1.6.9. It is a existing database so I don't want to mess up with my historical data. What I'm trying to alter is making a blank=true field non-empty(blank=false) here is my model class: class Post(DraftableModel, EditTrackingModel): title = models.CharField(max_length=120, verbose_name='headline') description = models.CharField(max_length=260, blank=True, verbose_name='lead-in', help_text="260 character limit") /*rest of the code*/ I want change the description from models.CharField(blank=True) to models.CharField(blank=False), which is the default blank value considering the existence of my database, some of my old Post model do have empty description. After my migration and change of database schema, will my database be corrupted? -
Django 1.8 IntegrityError when adding new user
I moved an old Django app from 1.4 to 1.8 and everything in the main application ran fine. I then needed to copy everything from server 1 to server 2, and in the process just dumped the mysql data for the admin database and installed to the new database. Everything came up fine, however when creating a new user I get: IntegrityError at /admin/auth/user/add/ (1048, "Column 'last_login' cannot be null") This is a live system with 30 accounts. I found a variety of solutions to this online but I want to make sure it doesn't trash my database. I only need the admin database fixed up. My business side database and tables are not managed by Django, but is a custom schema (that I inherited). btw, deleting a user works fine. -
AJAX in JavaScript function not working as expected [on hold]
Every time that a function is called in my .js, this should be executed: var slider = document.getElementById("slider"); var output = document.getElementById("text"); output.innerHTML = slider.value; slider.oninput = function() { output.innerHTML = this.value; $.ajax({ url: 'www.google.es', type: 'get', success: function(data) { alert('OK'); }, failure: function(data) { alert('NOT'); } }); } So I must receive an alert, successfully or not. But nothing happens. I am sure that the function is called. Am I missing something? -
Django ajax file upload form - file not uploading
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Whenever I try to do anything nothing happens. Here's the upload form: <form class="uploadForm" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="uploadFile"> <input type="submit" class="button" id="uploadButton" value="Upload"> </form> Here's my Jquery + Ajax: $('.uploadForm').on('submit', function(event){ event.preventDefault(); var fileSize = ($('#uploadFile')[0].files[0].size/1024); var fileName = $('#uploadFile')[0].files[0].name; var realSize = sizeConverter(fileSize); var fileData = new FormData($('#uploadFile')[0]); var csrfToken = '{{ csrf_token }}'; $.ajax({ url: '{% url 'project:uploadFile' %}', type: 'post', data: { 'fileData': fileData, 'fileSize': realSize, csrfmiddlewaretoken: '{{ csrf_token }}' }, cache: false, processData: false, contentType: false, success: function(data){ alert(data); } }); }); Here are views.py: class uploadFile(TemplateView): template_name = "project/uploadFile.html" def post(self, request): fileSize = request.POST.get('fileSize') fileData = request.FILES['fileData'] return JsonResponse(fileSize, safe=False) Now, with this setup when I submit the form nothing happens. I don't get any errors in the console, nothing. When I remove 'fileData' from data and cache: false, processData: false, contentType: false, inside Ajax this works(text only though). I tried changing new FormData($('#uploadFile')[0]); to new FormData($('#uploadFile').get(0)); but that did not help. I am guessing the issue here is with the fileData variable but … -
Django and Celery - 'from celery.decorators import task' not importing remotely
I'm trying to get my site working and I'm running into the problem of my server not importing celery modules (least I think that's what is going on). When I run from celery.decorators import task in my virtualenv on my remote server it seems to import them correctly as it doesn't show any errors... BUT when I go to my website which is django + apache + mod_wsgi served, I have a task.py file: from django.core.files.storage import FileSystemStorage from celery.decorators import task from celery.utils.log import get_task_logger logger = get_task_logger(name) from .models import books from .models import uploading_books @task(name="upload_book") def upload_book(book_name): # code to upload book which throws an error saying: No module named decorators I know this sounds like a general question, please let me know if you need anything else and I can provide it. -
Ajax call works on click, but not when button is submit button is pressed
I have the following HTML template in Django to POST a request when the user selects the select option. The console shows the correct value based on what the user selects. My problem is when I push the submit button my POST gets posted as None on the submitted view. How can I get it to post on button click, i've aliased the button as my_select. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <form action = "{% url 'submitted' %}" form method = "POST"> {% csrf_token %} <h2>Applications:</h3></br> {% for app in retreivecheckbox %} <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }} </li> {% endfor %} </div> </div> <div class="row"> <div class="col"> <label for="accesslevel"><h3>Access Level</h3></label> <select title ="accesslevelid" class="form-control my_select" id="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> </div> <div class="col"> <label for="phi"><h3>PHI</h3></label> <select class="form-control my_select" id="phi" title = "phi" > <option value = ""> Please select if you need access to PHI data </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> </div> </div> <div class="row"> <div class="container"> <div class="row"> … -
django WebSocket HANDSHAKING and DISCONNECT
Now I am trying to make chat using socket, but just this message is showing. [2017/12/08 18:51:07] WebSocket DISCONNECT /chat/prj/chat/ [127.0.0.1:55457] [2017/12/08 18:51:08] WebSocket HANDSHAKING /chat/prj/chat/ [127.0.0.1:55461] and get this from inspector InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable reconnecting-websocket.min.js:1 Firefox can’t establish a connection to the server at ws://localhost:8000/chat/prj/chat/. reconnecting-websocket.min.js:1:1075 The connection to ws://localhost:8000/chat/prj/chat/ was interrupted while the page was loading. reconnecting-websocket.min.js:1:1075 How to fix this? here is my consumers.py @channel_session def ws_connect(message): try: prefix, label = message['path'].strip('/').split('/') if prefix != 'chat': log.debug('invalid ws path=%s', message['path']) return room = Room.objects.get(label=label) except ValueError: log.debug('invalid ws path=%s', message['path']) return except Room.DoesNotExist: log.debug('ws room does not exist label=%s', label) return log.debug('chat connect room=%s client=%s:%s path=%s reply_channel=%s', room.label, message['client'][0], message['client'][1], message['path'], message.reply_channel) message.reply_channel.send({"accept": True}) Group('chat-'+label, channel_layer=message.channel_layer).add(message.reply_channel) message.channel_session['room'] = room.label @channel_session def ws_receive(message): try: label = message.channel_session['room'] room = Room.objects.get(label=label) log.debug('recieved message, room exist label=%s', room.label) except KeyError: log.debug('no room in channel_session') return except Room.DoesNotExist: log.debug('recieved message, buy room does not exist label=%s', label) return try: data = json.loads(message['text']) except ValueError: log.debug("ws message isn't json text=%s", text) return if set(data.keys()) != set(('handle', 'message')): log.debug("ws message unexpected format data=%s", data) return if data: log.debug('chat message … -
Django FileField update writes to disk but not to database
I am trying to update a FileField to an image of something downloaded from internet. I have the following code # update profile pic pic_url = fb_login_data['picture']['data']['url'] pic_url_parsed = urllib.parse.urlparse(pic_url) image_req = urllib.request.urlretrieve(pic_url) with open(image_req[0], 'rb') as f: user.profile_image.save(os.path.basename(pic_url_parsed.path), File(f)) The behavior is pretty strange: the image is saved to disk properly in the MEDIA_ROOT directory where it should be, but in database, the field remains empty. I also tried calling user.save() manually. Do you have any ideas why is that happening and how can I update properly the FileField? using Django 2.0 and Python 3.6.3 -
Filter only Selected Options in Choices Field on Model Form
I have a model formset that is written to HTML in the template like this: {% for form in formset %} <td>{{ form.instance.entity }}</td> <td>{{ form.choices }}</td> {% endfor %} form.instance.entity renders as text and can be easily filtered with ydacf or any other Django filtering method. form.choices renders as an HTML select box: <select name="form-0-disposition" id="id_form-0-disposition"> <option value="">---------</option> <option value="Option 1">False Positive</option> <option value="Option 2" selected>Monitor</option> </select> Let's say there are two forms in the formset: one has not been edited yet so choices is ---------, and the other has been edited and is Option 2 (like in the example above). If I attempt to filter this field, all options in the select box are included, even though only --------- and Option 2 are present as selected HTML elements. How would I present an editable select box to the user, but also allow them to filter by the selected value or form.instance.choices value? -
What is the equivalent of None and Null in Django if statements
I am trying to check if an object instance already exists in the model or if it's empty. I'm new to Django and I can't figure out the logic behind making that happen here. This is my function code and what I'm trying to do (In views.py): def registerAttendee(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) if act.attendee.get(student=request.user) is None act.attendee.add(attendee) messages.success(request, 'You\'re successfully registered as an attendee!', extra_tags='alert') else messages.warning(request, 'You\'re already registered as an attendee!', extra_tags='alert') return redirect('home/#work') I'm basically checking, if the user is not registered in this activity, then I'm going to add him/her, but if the user is already registered, I'm displaying a specific message. My current code doesn't work because I'm getting an "Invalid Syntax" error on the word None. I tried replacing it with NULL and BLANK but I'm still getting this error. What do I replace it with? This is what I have in models.py in case it helps: class Attendee(models.Model): student = models.ForeignKey(User, related_name="attendee") class Activity(models.Model): type = models.CharField(max_length=50, default="") title = models.CharField(max_length=200, default="") description = models.CharField(max_length=500) owner = models.ForeignKey(User, related_name="owner") college = models.CharField(max_length=200) location = models.CharField(max_length=200) room = models.CharField(max_length=200) startDate = models.DateTimeField(null=True, blank=True) endDate = models.DateTimeField(null=True, blank=True) attendee = … -
Django 1.11 - CSRF Verification failed despite having csrf_token template tag
New to django, making a to-do list page. I get the CSRF error after entering text in the input text box and hitting ENTER. I know this is likely a duplicate but after reading many of the forums and docs I'm still getting this issue. Here's what I've tried: I have the {% csrf_token %} template tag inside my form tag. I have 'django.middleware.csrf.CsrfViewMiddleware' in the MIDDLEWARE section of my settings. CSRF_COOKIE_SECURE = False is the default in Django 1.11. I am using http, not https. I'm using the render() function in my view. My Firefox Privacy settings are set to allow third-party cookies. Doesn't work in Chrome either. I'm not using the enctype="text/plain" tag in my HTML form tag. I've tried supplying a context dict to abide by this excerpt of the release: Here is my code: home.html <!DOCTYPE html> <html> <head> <title>To-do List</title> </head> <body> <h1>To-do List</h1> <form method="POST"> <!--tried adding action="" as well--> <input name="item_text" id="id_new_item" placeholder="Enter a to-do list item" /> {% csrf_token %} </form> <table id="id_table"> <tr><td>{{ new_item_text }}</td></tr> </table> </body> </html> urls.py from django.conf.urls import url from django.contrib import admin from lists import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home_page, name='home') ] settings.py … -
Prefetch related starting from a single object - geting first in second prefetch and count and order
I have 3 Models Product,Company Categories. class Product(Meta): categories = models.ManyToManyField(Category) company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) I need: to get all the products of a company show the product first category count the number products per company and show order products by reverse updated_at I start from: 1. Company.objects.get(pk=company_pk).prefetch_related('products') will give me an error, because get returns an object: 'Company' object has no attribute 'prefetch_related' get without prefetch works. Company.objects.filter(pk=company_pk).prefetch_related('products') there is no error, but in template: {% for company in company_list %} {{ company.name}} {% endfor %} I loop even is one, but doesn't show me anything. Besides that I need to attach first category to each product, and count the number of products -
Passing a GET to a POST request
I have a collection of check boxes that sends a GET request from profile to requestaccess. <form action = "{% url 'requestaccess' %}" form method = "GET"> <button href="{% url 'requestaccess' %}" class="btn btn-primary" input type = "submit"> Request Access</button> After my GET request is sent i'm able to render it on the requestaccess page by using the following in my view: checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) If I run the following request.method == 'POST' it won't write to the database unless I remove the if condition on the for loop. if request.method == 'POST': for i in checkedlist: requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title ,report_id = i, accesslevel_id = selectedaccesslevel, phi = '0', access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00') requestsave.save() The request is wrote to the database correctly, but I have to hard code the POST request from my ajax call because it tries to insert a NULL value to the database when going from profile to accessrequest. In the following template I included the JS and Ajax call to send the POST request but, it … -
Django, how to access models inside a model through a model field
I have two models that have a many-to-one relationship between them. from django.db import models class Continent(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=2, unique=True, primary_key=False) c = Continent.objects.get(id=1) countries = c.country_set.all() class Meta: ordering = ["name"] class Country(models.Model): name = models.CharField(max_length=255, unique=True) capital = models.CharField(max_length=255) code = models.CharField(max_length=2, unique=True, primary_key=False) continent = models.ForeignKey('Continent') population = models.PositiveIntegerField() area = PositiveIntegerField() class Meta: ordering = ["name"] I want the countries of a continent to be accessible through a countries attribute within the Continent model. I tried to follow the relationship "backward" like in the documentation (link below), but can't get it to work. https://docs.djangoproject.com/en/1.11/topics/db/queries/#backwards-related-objects