Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Paginate with Django Postman
i'm kinda new to django, i'm working on a project that requires user to user messaging, so i decided to use django postman. i was able to install in my project folder but the problem i'm facing has to do with pagination. The inbox should paginate after 20 messages but its not. base_folder.html {% block pm_folder_title %}{% endblock %} {% autopaginate pm_messages %} {% if invalid_page %} {% trans "Sorry, this page number is invalid." %} {% else %} {% if pm_messages %} {% b lock pm_by_modes %} Reall need help guys -
Django using wrong project root folder location
I just deployed my first project into production. When I try to access it, it fails because the project doesn't find the template folder. That's the error message: What seems to me is that my project is looking for the template folder outside the main project folder. I confirmed it when I moved the template folder to var/www. Therefore, doing that the django admin page interface (css and javascript) stops working. The html still there, but not styled. How do I tell django to look for the template folder whiting the project folder? Here's my apache config: WSGIDaemonProcess safebox python-home=/var/www/safebox python-path=/var/www/sa$ WSGIProcessGroup safebox Alias /media/ /var/www/safebox/media/ Alias /static/ /var/www/safebox/static/ <Directory /var/www/safebox/static> Order deny,allow Allow from all </Directory> <Directory /var/www/safebox/media> Order deny,allow Allow from all </Directory> WSGIScriptAlias /safebox /var/www/safebox/safebox/wsgi.py process-group=safebox <Directory /var/www/safebox/safebox> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> -
Django 2. Cannot import module to mail urls.py
Im cannot seem to import a module in my Django 2.0.3 project to the site-wide url patterns. Error: path('', authenticate.views.landing, name='landing'). Name 'authenticate' is not defined site/urls.py from django.contrib import admin from django.urls import path, include from authenticate.views import landing #from authenticate import views urlpatterns = [ path('admin/', admin.site.urls), path('streamers/', include('main.urls')), path('', authenticate.views.landing, name='landing'), ] authenticate/views.py def landing(request): return render(request, 'authenticate/landing.html') Simplified site tree: /site -urls.py -settings.py /authenticate - __init__.py - views.py -
Extended template block not taking css from static
Below shown extended html of an app for a class based view is not taking css from static file as mentioned in html. Please help in how to implement css for this extended block. HTML File: {% extends "base_template.html" %} {%block head%} {% load static %} <link href="{%static 'css/custom.css' %}" rel="stylesheet"> {%endblock head%} {% block content %} <h2>Dynamic content</h2> <p>You have visited this page {{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p> <div class="btnlayout" style="float: left;padding: 10px;"> <li><form action="/ekmmsc/treedump/printx" method="get"> <input type="text" value="8" name="mytextbox" size="1"/> <input type="submit" class="btn" value="Click" name="mybtn"> </form></li> <li><form action="/ekmmsc/treedump/Tree70" method="get"> <input type="submit" class="btn" value="Tree70" name="mybtn1"> </form></li> <li><form action="/ekmmsc/treedump/UserID" method="get"> <input type="submit" class="btn" value="UserID" name="mybtn2"> </form></li> <li> <form action="/ekmmsc/treedump/TG_Dump" method="get"> <input type="submit" class="btn" value="TG_Dump" name="mybtn3"> </form></li> </div> {% endblock %} Custom.css h1, h2, h3, h4, h5, h6 { color: black; } .btnlayout li form{ display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; width: 80px; } .btnlayout li { float: left; border-right:1px solid #bbb; border-left:1px solid #bbb; } I need the form elements to be displayed inline where as they are getting displayed as list. -
django unknown extra redirection
I have a middleware that forces login on certain pages, and also screen users who are not in a certain group: from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.conf import settings from re import compile from django.core.urlresolvers import reverse from django.utils.deprecation import MiddlewareMixin from django.contrib.messages import error, info EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] MANAGER_URLS = [] if hasattr(settings, 'MANAGER_ONLY_URLS'): MANAGER_URLS += [compile(expr) for expr in settings.MANAGER_ONLY_URLS] class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user') path = request.path_info.lstrip('/') next = request.path_info if not request.user.is_authenticated: if not any(m.match(path) for m in EXEMPT_URLS): return redirect('/login/?next=%s' % next) else: if not request.user.groups.filter(name='Manager').exists(): print('logged in') if not any(m.match(path) for m in EXEMPT_URLS) and any(m.match(path) for m in MANAGER_URLS): print('no manager') error(request, 'Permission Denied, You Need Admin Permissions For Access') return redirect('/login/?next=%s' % next) and in settings file: LOGIN_URL = '/login/' LOGIN_EXEMPT_URLS = ( r'^logout/', ) MANAGER_ONLY_URLS = ( r'^admin/', r'^clients/', ) my problem is that when I trying to access the admin url no messeage shown. I see in django consloe this: [01/Apr/2018 18:47:46] "GET /admin/ HTTP/1.1" 302 0 logged in [01/Apr/2018 18:47:46] "GET /login/?next=/admin/ HTTP/1.1" 200 2010 logged in [01/Apr/2018 18:47:47] "GET /login/?next=/admin/ … -
DeadlineExceededError: The overall deadline for responding to the HTTP request was exceeded on Google App Engine with Django
I'm trying to host an api (using the django rest framework) on the Google App Engine. At the root domain (https://mythic-plexus-194517.appspot.com/) no problems, but when I go to the endpoint /products/ I'm hitting a server 500 error and inspecting the logs I'm seeing DeadlineExceededError: The overall deadline for responding to the HTTP request was exceeded error. It's worth noting that /products works as expected on my local machine - and loads within a second. The trace stack looks like so: Traceback (most recent call last): File "/base/alloc/tmpfs/dynamic_runtimes/python27/6baee03590d046f1_unzipped/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 267, in Handle result = handler(dict(self._environ), self._StartResponse) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/wsgi.py", line 157, in __call__ response = self.get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/base/data/home/apps/g~mythic-plexus-194517/20180401t160704.408718556380642667/lib/django/utils/deprecation.py", line 140, in __call__ … -
How to change a value data in select Django
I would like to change the value attribute in the option tag in the django template. I'm using a form and the value is a foreign key, and I would like to set the name of Entity and save the id in database. My Entidade Model class Entidade(models.Model): co_entidade = models.CharField('Código', max_length=32, unique=True) no_entidade = models.CharField('Nome', max_length=32, unique=True) My Projeto Model: class Projeto(models.Model): no_projeto = models.CharField('Nome do Projeto', max_length=32) fk_entidade_proponente = models.ForeignKey('Entidade', on_delete=models.CASCADE, related_name='proponente') fk_responsavel_proponente = models.ForeignKey('Responsavel', on_delete=models.CASCADE, related_name='proponente') My Projeto Form: class ProjetoFormEdit(BaseForm): preview = [f.name for f in Projeto._meta.get_fields()] fk_entidade_proponente = forms.ModelChoiceField(queryset=Entidade.objects.values_list('no_entidade',flat=True), widget=forms.Select(attrs={'class':'form-control'}), to_field_name="no_entidade[enter link description here][1]") fk_entidade_concedente = forms.ModelChoiceField(queryset=Entidade.objects.values_list('no_entidade',flat=True), widget=forms.Select(attrs={'class':'form-control'}), to_field_name="no_entidade") My template https://pastebin.com/tTyps2Ej But when I render in the template I see this structure. <select name="fk_entidade_proponente" class="form-control" required="" id="id_fk_entidade_proponente"> <option value="" selected="">---------</option> <option value="sdsds">sdsds</option> </select> But I need to do this way. <select name="fk_entidade_proponente" class="form-control" required="" id="id_fk_entidade_proponente"> <option value="" selected="">---------</option> <option value="1">sdsds</option> </select> The number in value refers the id saved in the database. -
Do I really need GDAL for django-geojson?
I'm trying to represent some fairly simple geographical data in a Django project. I wanted to use django-leaflet and django-geojson. Now if I first try out this example project and try to run python manage.py migrate, I get this error message: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. However, it says explicitly: This project does not require any GIS library or specific database. Map data are stored in simple JSON fields. which I think is weird. What am I missing here? Do I really need to install GDAL? If yes, what would be an alternative, because what I am trying to do is not too complex. I use Python 3.6 on a Windows 10 machine. -
Django. An inline element is not created at the same time as the parent
I'm new to Django and need help. Here's what's in the model.py: class Constant(models.Model): name_constant = models.CharField(max_length=100,blank=False, null=False, unique=True) unit = models.ForeignKey(Unit, on_delete=models.PROTECT) def __str__(self): return self.name_constant class ConstantValue(models.Model): constant = models.ForeignKey(Constant, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.PROTECT, null=True, blank=True) value = models.DecimalField(max_digits=14, decimal_places=4, blank=False, null=False, validators=[MinValueValidator(0)]) def __str__(self): return self.name_constant class Meta: unique_together = ('constant', 'region') Here's what in admin.py: class ConstantValueInlineAdmin(admin.StackedInline): model = ConstantValue extra = 0 class ConstantAdmin(admin.ModelAdmin): list_display = ([field.name for field in Constant._meta.fields])[1:] list_display_links = ([field.name for field in Constant._meta.fields])[1:] inlines = [ConstantValueInlineAdmin] class Meta: model = Constant admin.site.register(Constant, ConstantAdmin) When I add a record to the Constant, I want to add a record via the inline in ConstantValue, but I get the error: AttributeError at /admin/inc/constant/add/ 'ConstantValue' object has no attribute 'name_constant' I think this is because the element with the external key can not receive the primary key Constant, because it has not yet been created. How to solve this problem? -
What field Django used in FOO_set?
I am little bit comfused. Lets say I have such models. models.py: class Company(models.Model): name = models.CharField(blank=False, null=False) class Game(models.Model): developer = models.ForeignKey(Company, on_delete=models.CASCADE) publishers = models.ManyToManyField(Company) If I use next code: current_company = Company.object.get(pk=1) current_company.game_set.all() as I understand it return all games of current_company, but what field (developer or publishers) Django used? -
Django: static folder for template's assets
I'm learning Django 2.0 I have a ready-made template, that contains all assets in assets folder.All references in template starts from assets/..., and I'm gonna keep it: all links should looks like {% static 'assets/...' %} My Django app has following structure: myapp ├───manage.py └───mysite └───static/mysite/static/assets # some mess here? └───templates/mysite/index.html Inside index.html I'm using {% load static %},In settings I have just STATIC_URL = '/static/' but framework can't find path to assets. What I'm doing wrong? -
django comments views from scratch
I'm working on a blog build on django and doing the comment stuff and I would like to build it from scratch here my views function: def topic_detail(request, slug): topic = get_object_or_404(Topic, slug=slug) form = CommentForm() if request.method == 'POST': if request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.topic = topic comment.created_by = request.user comment.save() return redirect('board:topic_detail', slug=topic.slug) else: redirect('accounts:login') else: form = CommentForm() return render(request, 'topic.html', {'topic':topic, 'form':form}) my page layout would be: < ............................> Something I want to write <.............................> Comment Field <.............................> Comments So when user presses the button, server will check if that user is authenticated. If yes comment is updated, If no user will be directed to login views. Here the problem, when I'm logged in everything works fine, but when I log out test the views, It does not redirect me to the login views but just reload the page. I would appreciate if you help me. Thanks! -
Django response to ajax request, and render template without refresh page
I am working a Django ajax problem. Here is the workflow. I click a button, an animation will run, and an excel file will be uploaded to the server, and server parses the excel and return some data which will be used to render a template(a table ). once server response, the animation stop, and the table show up. The whole things happend on the same page, with any redirect. Here is the problem, what should I return that will not refresh my whole page? The code I have like this: code for ajax request function startPredict(event) { var animation = document.getElementById("menu"); animation.style.display = ""; event.preventDefault(); var data = new FormData(); data.append('excel', $('input[type=file]')[0].files[0]); $.ajax({ url: "/predict_material/", data: data, type: 'POST', contentType: false, processData: false, success: function(data) { console.log(data) animation.style.display = "none" var table = document.getElementById("menu2"); table.style.display = ""; } }) } code for form <form method="post" enctype="multipart/form-data" id="uploadFile"> {% csrf_token %} <input type="file" name="document" id="id_document" style="display: none;" required> <input type="text" value="请选择文件" id="photoCover" class="input-large" style="height: 30px;color:#FF0000;"> <button type="button" class="btn1 btn-primary" onclick="$('input[id=id_document]').click();" style="margin-left: 10px; margin-right: 10px;">选择文件</button> <button type="submit" class="btn1 btn-primary" onclick="startPredict()" id="startUpload" >开始预测</button> </form> code for views method def predict(request): if request.method == 'POST': form = PredictUploadForm(request.POST, request.FILES) if form.is_valid(): filename = … -
django app not pushed in heroku
I have been trying to deploy an app on heroku but its giving an error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_2d584bc0856d993e4c738fe75d1e7e4c/static' Dont know where does these come from .. ?? "/tmp/build_2d584bc0856d993e4c738fe75d1e7e4c/" This is settings.py file import os import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' -
ImportError: cannot import name 'patterns'
I have a problem with Django, I created a 'login' app and added the URL on mysite/urls.py as below: from django.conf.urls import include, patterns, url from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), url(r'^user-auth/', include('user_auth.urls')), url(r'^file-upload/', include('file_uploader.urls')), url(r'^pagination/', include('pagination.urls')), patterns('login.views', url(r'^login/', 'loginView'), url(r'^greeting/', 'formView'), url(r'^logout/', 'logoutView') ) ] However, when I started the server, I received the message on console as: File "/home/win/Python/mysite/mysite/urls.py", line 16, in <module> from django.conf.urls import include, patterns, url ImportError: cannot import name 'patterns' Do you meet any problem like this? and any resolution to resolve it. Please please help me. Thanks -
How to test a social_auth_app_django custom pipeline?
I have a custom pipeline which pulls the name of the user from the response. How do I test the pipeline with django.test.TestCase? Here's the code for the pipeline: def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'github': try: userprofile = UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: UserProfile.objects.create(user=user, name=response.get('name')) -
Is there a way to make every page require login without using method decorators?
Currently I'm using the following method decorator @login_required(login_url="/accounts/login") but it's hardly efficient adding this to every single view and goes against the DRY principle. -
Testing Django app with docker compose
I'm using docker-compose to start my Django application. I am having problems keeping the data volumes between development and test separated. The development version of the code looks like this, and has data stored in Postgres, Elasticsearch, and Redis: version: '3' services: db: image: postgres:9.6.6 ports: - "5435:5432" environment: - POSTGRES_PASSWORD=example volumes: - pg-data:/var/lib/postgresql/data redis: image: redis:3.2.6 volumes: - redis-data:/data redis_cache: image: redis:3.2.6 elasticsearch: image: elasticsearch:5.6.6 volumes: - elasticsearch-data:/usr/share/elasticsearch/data web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" environment: - DATABASE_URL=postgresql://postgres:example@db/postgres - ENVIRONMENT=development - REDIS_URL=redis://redis:6379 - REDIS_CACHE_URL=redis://redis_cache:6379 - ELASTIC_ENDPOINT=elasticsearch:9200 env_file: docker.env depends_on: - db - redis - redis_cache - elasticsearch volumes: - .:/code volumes: pg-data: {} redis-data: {} elasticsearch-data: {} I created another version of this document for testing the app, which is called docker-compose.test.yml. Each time I start this version of the app I want to use a fresh copy of Postgres, Elasticsearch, etc. But it does not work that way. The goal is to populate some data during the test, then have it all removed on shutdown. I thought I could simply start services without a named volume to accomplish this. Like so: db: image: postgres:9.6.6 environment: - POSTGRES_PASSWORD=example Then I ran the test with: docker-compose … -
Connecting multithreaded task runner with django web application
I’m developing a web service using django. In addition to the web application, I have a separate module with about 40 functions that take in some parameters, perform some network-bound tasks and return results. These functions (or an entry point function) can be called from django views. Here is the flow I’m trying to achieve. From the web application, users can submit an URL to start the operation. That request should initiate those functions in parallel (with the URL as an argument) in the server (not necessarily all at once) User can do a request from the web application to get a list of completed tasks and results of the ongoing operation. Multiple users can submit URLs to the web application and initiate the operation separately (each user gets a list of 40 results) Currently I am experimenting with Thread and Queue classes to achieve this. What I want to know is how can I manage this flow without getting so many threads? How should I maintain the separation between two operation sessions? Is there any way I can in-cooperate the capabilities of django for this? All I ask is a basic guideline of how things should be organized to … -
How to embed Python list as it is in Django template?
There is a Django template in my web app which has a JavaScript section in it. chart.html {% block footer_javascript_section %}<script type="text/javascript" > g = new Dygraph( // containing div document.getElementById("graphdiv"), // CSV or path to a CSV file. "{{ biogas_plant_str }}", {width: 1000, height: 400, labels: {{biogas_plant_list}} } /* <---- THIS list */ ); </script> {% endblock footer_javascript_section %} I've passed in a Python list in the context of the chart view function.The list is referred by biogas_plant_list. The issue I need to embed the Python list as it is, without splitting or iterating over it. Other questions similar to this one, required the list to be handled in some way. A list has to be output after substitution. ['s1','s2'] However template substitutes the HTML character entities instead of the actual decoded characters. How to turn it off? [&#39;&quot;25.7\\n&quot;&#39;, &#39;&quot;26.3\\n&quot;&#39; ] -
Add fields to a Task without needing it in the Process?
I am currently using ViewFlow to model the process of creating websites in my company. My flow produces a website from an AWS instance to a E commerce site. Each Task in my flow adds a little bit of information to my site. Examples: pick domain, configure SSL. Every time a task is completed I will ask my users for some information that will be saved to a website database row. I am interested to know whether it is possible to add fields to a Task that doesn't require schema change in the my Process table. The reason I want this is because many of my tasks are asking my users for information that will be saved directly to our database. I do not need my process table to carry so much information that is only useful to one task. Right now, if you have fields=['field_not_in_schema', ...] you will get an error Unknown field(s) (field_not_in_schema) specified for MyProcess. I am using Viewflow's default frontend module. Any recommendations? -
How to auto logout user after certain period of time of loggedin.
I am working on a website to host a competition on local server.Actually the time limit of competition is 60 min.I want to auto logout every user after 60 min of logging In. I am beginner to django and this is my first project in django. Thanks in advance. -
Django - Running tests gives django.db.OperationalError
Recently I decided to make a threaded function in Python that checks the output of a function and then update the cache of the function accordingly. When I run my tests locally it's everything works as intended but on the server I get the following. OperationalError database "test_ebdb" is being accessed by other users DETAIL: There are 10 other sessions using the database.` This is the threaded function that I use, it's going to query the database if the function it's calling queries the database. def _check_and_update_cache(func, args, kwargs, cache_key, timeout=settings.DEFAULT_CACHE_TIMEOUT): """ Runs the function that has been cached to see if the output is the same as the one in the cache, if the output is not the same then it will update the cache with the new result """ new_result = func(*args, **kwargs) old_result = cache.get(cache_key) if new_result != old_result: cache.set(cache_key, new_result, timeout) This is the code that is calling it. t = Thread(target=_check_and_update_cache, args=(func, args, kwargs, key,)) t.start() Sorry if there aren't many details, I'm kind of at a loss as to what is happening. I'll try to provide you with some details. -
Coding for Entrepreneurs - Tracking Shares, "Join object" being displayed instead of entries
I'm watching the video course by Udemy "Coding for Entrepreneurs Learn Python, Django, and More." It's from 2015 so the code is outdated and I'm doing my best to update it and get it working properly. The origional code for the course is at "https://github.com/codingforentrepreneurs/launch-with-code." My altered code is displaying "Join object" in the Friend field for every entry instead of the friend's email. Below is the code that I am using. The views.py file: from django.conf import settings from django.shortcuts import render, HttpResponseRedirect, Http404 from .forms import EmailForm, JoinForm from .models import Join import uuid def get_ip(request): try: x_forward = request.META.get("HTTP_X_FORWARDED_FOR") if x_forward: ip = x_forward.split(",")[0] else: ip = request.META.get("REMOTE_ADDR") except: ip = "" return ip def get_ref_id(): ref_id = str(uuid.uuid4())[:11].replace('-', '').lower() try: id_exists = Join.objects.get(ref_id=ref_id) get_ref_id() except: return ref_id def share(request, ref_id): try: join_obj = Join.objects.get(ref_id=ref_id) friends_referred = Join.objects.filter(friend=join_obj) count = join_obj.referral.all().count() ref_url = settings.SHARE_URL + str(join_obj.ref_id) context = {"ref_id": join_obj.ref_id, "count": count, "ref_url": ref_url} template = "share.html" return render(request, template, context) except: raise Http404 def home(request): try: join_id = request.session['join_id_ref'] obj = Join.objects.get(id=join_id) except: obj = None form = JoinForm(request.POST or None) if form.is_valid(): new_join = form.save(commit=False) email = form.cleaned_data['email'] new_join_old, created = Join.objects.get_or_create(email=email) if created: new_join_old.ref_id … -
Use of same related_name in a single Model. Django
I have a User model: Class User(models.Model): #some fields And another Profile Model, which consists of fields -> mother and father. Class Profile(models.Model): father = models.ForeignKey( 'User', related_name='childs', on_delete = models.CASCADE) mother = models.ForeignKey( 'User', related_name='childs', on_delete = models.CASCADE) Now, is it right to do so? If it is, How am I to get a User's children?