Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can change render to return json in view Django
I have function in view from django.shortcuts import render from .models import myModel def articleTheme(request): if request.method == 'POST': article_id = request.POST['id'] article = myModel.objects.get(id=article_id) theme = article.theme return render(request, 'theme.html', {'newTheme': theme }) now it works normal. But I have excess html. I want return json object. What I can import and return? -
Creating child paged in migrations files
I'm trying to create to index pages that are children of home page, some like this: # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-13 22:50 from __future__ import unicode_literals from django.db import migrations def create_blogindexpage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') BlogIndexPage = apps.get_model('blog.BlogIndexPage') HomePage = apps.get_model('home.HomePage') blogindexpage_content_type, __ = ContentType.objects.get_or_create( model='blogindexpage', app_label='blog') # Create a new blogindexpage blogindexpage = BlogIndexPage.objects.create( title="Blogs", draft_title="Blogs", slug='blogs', content_type=blogindexpage_content_type, path='000100010001', depth=3, numchild=0, url_path='/blogs/', ) home_page = HomePage.objects.get(id=3) home_page.add_child(instance=blogindexpage) class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ('home', '0002_create_homepage'), ] operations = [ migrations.RunPython( create_blogindexpage, ), ] This index of blogs have to be a child from the home page and this migration file depends of home create_homepage migration, but it give me this error: File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in … -
Migration file don't change Site name and domain
I have this migration file: from django.db import migrations from django.contrib.sites.models import Site as DjangoSite def change_django_site(apps, schema_editor): site = DjangoSite.objects.get(id=1) site.delete() DjangoSite.objects.get_or_create(id=1, domain='www.xprende.com', name='XPrende') def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') HomePage = apps.get_model('home.HomePage') # Delete the default homepage # If migration is run multiple times, it may have already been deleted Page.objects.filter(id=2).delete() # Create content type for homepage model homepage_content_type, __ = ContentType.objects.get_or_create( model='homepage', app_label='home') # Create a new homepage homepage = HomePage.objects.create( title="Home", draft_title="Home", slug='home', content_type=homepage_content_type, path='00010001', depth=2, numchild=0, url_path='/home/', ) # Create a site with the new homepage set as the root Site.objects.create( hostname='www.xprende.com', site_name='XPrende', root_page=homepage, is_default_site=True ) def remove_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') HomePage = apps.get_model('home.HomePage') # Delete the default homepage # Page and Site objects CASCADE HomePage.objects.filter(slug='home', depth=2).delete() # Delete content type for homepage model ContentType.objects.filter(model='homepage', app_label='home').delete() class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ('sites', '0002_alter_domain_unique'), ] operations = [ migrations.RunPython( create_homepage, remove_homepage, change_django_site, ), ] As you can see i made a function that have to change the django site name and domain. But it doesn't do it, after apply the migrations i get the same default values: In [3]: DjangoSite.objects.get(id=1) Out[3]: … -
Coverage.py warning: No data was collected. (no-data-collected)
I am trying to find the coverage using coverage module for a django project but gets "Coverage.py warning: No data was collected. (no-data-collected)". My project folder has src and tests folders. When I run coverage run -m pytest && coverage report It produces a report with 100% coverage with the list of files inside the tests folder. Whereas when I run coverage run --source=src -m pytest && coverage report it says Coverage.py warning: No data was collected. (no-data-collected) No data to report. When I try to give the source=src or include=src in the .coveragerc also the same warning occurs. The tests passes for all the above cases. I want the coverage of the src folder. Is it because I am missing some path setting? -
Django make changes in DB only for certain user / django-reversion revert version`s object only for a certain user
After a long time spent for googling without a big success I really need a help from someone who faced with this question earlier than me. I am using the django-reversion for storing an object changes, and my goal is to allow user to access a list of the object versions and select needed one, so the object will be changed for that version, however these changes shoud be visible only for that user. Other users should see the actual data of the object, until they also activate some other object version. But the django-reversion package works so that when you reverting the object to some version, this will affect original object in DB. Some possible solutions I was considering are django session and cookies, however it seems to be realy complicated for this use-case because the object has relations with other models. Please give me some directions, how it is possible to perform the expected behaviour. Or it is not possible to make this with django-reversion? Thanks in advance for any information! -
How to override Allauth login template in app in Django?
I tried overriding Django Allauth login templates in my app, but it didn't work. APP_DIRS in settings.py is also True. Login template location: ProjectName\main\templates\main\account\login.html Any idea how to fix this, without creating a templates folder on project level? -
How can I alter the response coming from a delete request in Django Rest Framework?
I am creating an app which retrieves a list of students in the database and enabling the user to add and delete students. I am using Django and Django Rest Framework for the backend and React for the frontend. Upon deleting a student I want the new list of students to be returned in the response this is my views.py: from django.shortcuts import render from django.conf.urls import url from rest_framework import viewsets, status from app.models import University, Student from app.serializers import UniversitySerializer, StudentSerializer from rest_framework.views import APIView from rest_framework.response import Response from django.http import Http404 class StudentList(APIView): def get(self, request, format=None): students = Student.objects.all() serializer = StudentSerializer(students, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = StudentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): student = self.get_object(pk) student.delete() students = Student.objects.all() serializer = StudentSerializer(students, many=True) return Response({'data': serializer.data}) This is the request: axios.delete(`api/students/${id}`) .then((response)=>{ console.log(response); }) The request is working and the student is deleted, but the data in the response returns an empty string: {data: "", status: 204, statusText: "No Content", headers: {…}, config: {…}, …} Is there something I'm doing wrong? -
Which Python Framework should I learn?
Hi i'm learning python web development and using webapp2 framework to build my website and i'm almost done. Now i'm thinking to learn other python framework (Flask or Django). Which framework should i learn Flask or Django ? -
How to pass tuple as arguments in raw mysql in Flask Python? [duplicate]
This question already has an answer here: Python MySQL Connector database query with %s fails 1 answer I'm trying to fetch data from mysql by passing a tuple as argument. The query is perfectly working directly in mysql but when in flask app, its returning Sqlalchemy error image app.py: not_selected = tuple(not_selected) print not_selected for n in not_selected: all_modules = [] modules_data = db.execute("""SELECT id, group_code, group_name, module_name, url, icon FROM modules WHERE id NOT IN %s""",not_selected[n]) for j in modules_data: m = {} m['id'] = j[0] m['group_code'] = j[1] m['group_name'] = j[2] m['module_name'] = j[3] m['url'] = j[4] m['icon'] = j[5] all_modules.append(m) print not_selected printed in console was: (1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48) Note: Mysql query is 100% correct and working in mysql query browser but I don't know why this is returning error in your SQL syntax. Please help me out! Thanks. -
Setting up setattr behavior of Django model without affecting instance initialization
I have a model called A. When b attribute is set of that model, I want to update that attribute like this: # Note that PGJSONField is a field that can store string or json. class A(models.Model): description = PGJSONField(blank=True, null=True) def __setattr__(self, key, val): if key == 'description': val = {'description': val} super(A, self).__setattr__(key, val) This causes a side effect. When I get model instance from DB. It set's up description key as dict event if it's not. >>> a = A.objects.first() >>> a.description ..: {"description": "lorem ipsum"} My expected bahavior is something like this: >>> a = A.objects.first() >>> a.description ..: "lorem ipsum" >>> a.description = "foo bar" >>> a.description = {"description": "foo bar"} I think I must by pass _setattr method when model is being fetched but I couldn't find a way to do it. Any suggestions? -
Application overhead design decision: store needed value on database row or find it dynamically in queryset
I'm developing a simple price tracker application. I'm a bit new to web application design and could use an experienced opinion here. My application pulls price points for hundreds of thousand of products per day by unique price SKU. For each SKU I want to be able to show: All time high price All time low price Average price When my API writes a new SKU price to the database I am able to figure out these three values and write them to the latest/current price row. Is this a better design decision than say using a Django Queryset in my View to query for and/or calculate and display them? -
Onclick Confirm add Checkbox Length
This should be really simple, but I can't get it to work and I'm an absolute beginner with Javascript. I looked at various threads here. I'm working with a django template, on a simple link. I want to add an onclick confirmation message such as 'Trash (14) Projects? Are you sure?' where 14 is the number of checkboxes ready to submit in a form. Right now I have. <button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add projects to trash - Are you sure?')" >Remove / Add To Trash</button> Which of course doesn't have the number of projects to be deleted. I could add a script in the head to count the classes of checkboxes, but I want to know how I might execute javascript inside the confirm dialog itself? Such as... <button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add ($(":checkbox:checked").length) to trash - Are you sure?')" >Remove / Add To Trash</button> Which doesn't work, probably because the ":checkbox:checked" gets escaped inside the onclick " ". Anyone point me in the right direction as to what is the 'usual' way to do this kind of thing... -
Django, How to route the traffic?
Contract an instance in gandi.net but I want to have several domains (vhost) in that same instance only I was satisfied with the support that is only possible redirecting the traffic with my python code, I have no idea how to do it. Thank you for contacting Gandi support. Python instances only have one vhost, named 'default'. If you'd like to host multiple Python website on a single instance, then you will need to route the traffic with your Python code, by using the 'host' header. host = self.headers.get('Host') https://doc.gandi.net/en/simple/python We are at your disposal should you need any further information. Best regards, if someone could clarify, how to do routing with django? -
Different css margins for mobile & desktop without multiple {% block content %} in Django template
I need to change the margin-left that is applied to my main {% block content %} in my base.html template (that contains my navbar and other common elements) based on if the viewer is using mobile or desktop. My current base.html is like: <div class="content container-fluid"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> with a css file containing: .content { margin-left: 40px; } .content_mobile { margin-left: 10px; } Given that in other parts of my application I've accomplished this by using the following dedicated Bootstrap classes, my first thought was to do the same using something like: <div class=".visible-xs-block, hidden-xs"> <div class="content container-fluid"> <div class="row"> <div class="col-md-8"> <!-- This is hidden from mobile view --> {% block content %} {% endblock %} </div> </div> </div> </div> <div class=".visible-lg-block, hidden-lg .visible-md-block, hidden-md .visible-sm-block, hidden-sm"> <div class="content_mobile container-fluid"> <div class="row"> <div class="col-md-8"> <!-- This is hidden from all other views (including desktop) --> {% block content %} {% endblock %} </div> </div> </div> </div> But Django raises an exception because it can only render 1 {% block content %} per template! Any ideas how I can do this without using multiple blocks? -
Where can I to write my logic in APIView?
In the CreateAPIView I can override the create method to add my logic: class OpenstackAccountCreateAPIView(CreateAPIView): """ create openstack account """ serializer_class = OpenstackAccountCreateSerializer def create(self, request, *args, **kwargs): # put my logic here ...... But if I have a APIView, where can I to write my logic? class OpenstackAccountLoginAPIView(APIView): serializer_class = OpenstackAccountLoginSerializer # where can I put my logic? -
Save data of django form in database
I'm using Django 1.3 and I have a form defined with forms.py: class mopa(forms.Form): idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 ) causale = forms.CharField(label="Causale Pagamento *", required=True) imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True) quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True) and in this file I made the checks. My models.py file: class Mopamodel(models.Model): idcarrellosorgente = models.IntegerField() cod_ente = models.CharField() causale = models.CharField() imp_unitario = models.DecimalField() quantita_item = models.IntegerField() and my views.py def paga(request): # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = mopa(request.POST) print('form: ', form.data) #return a dictionary # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required # p=form.save() <--don't works: error: 'mopa' object has no attribute 'save' idcarr = form.cleaned_data['idcarrellosorgente'] caus = form.cleaned_data['causale'] imp_u = form.cleaned_data['imp_unitario'] qta = form.cleaned_data['quantita_item'] dictmopa={} dictmopa['id_carr']=idcarr cod_ente = form.cleaned_data['cod_ente'] mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta #mopapay.save() <--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType' .... # redirect to a new URL: return HttpResponseRedirect(reverse('viewsdati/') ) How can I save the form … -
How to check session expiration on close of browser in Django?
Here is the scenario I wish to handle in Django application User logs in web application. SESSION_EXPIRE_AT_BROWSER_CLOSE is set to true. User closes the browser window. Now how to know receive the session info that session has been killed/Destroyed? -
Creating an url within a div button using django url + div button value ie div id
I have created a clickable div to act as a 'button'that links to another page within my site. Is it possible to append the div ID into the url I call such that different divs call the same django url (as the base) but through the appended div id ended up going to different pages . for example: this example works with the pack.id being appended but in the scenario I want to implement I do not used a django model <div id="ticket1"> <a href="{% url 'student-packages-add' pack.id %}"> </div> trying to do: <div id="ticket1"> <a href="{% url 'student-packages-add' div.id %}"> </div> what doesn't work and creates errors: <div id="ticket1"> <a href="{% url 'student-packages-add' ticket1 %}"> </div> or <div id="ticket1"> <a href="{% url 'student-packages-add' "ticket1" %}"> </div> -
Comparing date field in a form with current date
I am trying to check with an if statement if the date entered in a form is before the current date. If so write to an object in the model. I am also not sure if there are a better way of doing this. I get this error '<' not supported between instances of 'DateField' and 'datetime.date' My view: class ActionCreateView(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' template_name = "nodiso/actioncreate.html" form_class = forms.LeadActionCreateForm # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] ) def get_success_url(self, **kwargs): return reverse("nodisoapp:leaddetail", kwargs={'pk': self.kwargs['pk']}) def form_valid(self, form): if form.fields['Duedate'] < datetime.date.today(): self.object.overdue = 1 else: pass self.object = form.save(commit=False) self.object.lead_id = self.kwargs['pk'] self.object.creator = self.request.user.firstname self.object.save() return super(ActionCreateView, self).form_valid(form) The Model: class LeadActions(models.Model): lead = models.ForeignKey(Leads) name = models.CharField(max_length=265) crdate = models.DateField(auto_now_add=True) Duedate = models.DateField() creator = models.CharField(max_length=265) overdue = models.IntegerField(null=True,blank=True) def __str__(self): return self.name The form: class LeadActionCreateForm(forms.ModelForm): class Meta: model = models.LeadActions fields = ['name','Duedate'] -
Extend the user model (avatar)?
I want to extend my user model and add avatar(image) field. I created new app - accounts and inside the models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings from django.contrib.auth.models import User def download_location_of_usrpic(instance, filename): return "%s/%s" %(instance.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( upload_to=download_location_of_usrpic, null=True, blank=True, height_field="height_field", width_field="width_field" ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) My admin.py from accounts.models import Profile admin.site.register(Profile) Made makemigrations and migrate I also have a GCBV @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): model = User fields = ('first_name', 'last_name', 'email', 'image', ) template_name = 'my_account.html' success_url = reverse_lazy('my_account') def get_object(self): return self.request.user But I dont see this field in admin and got the mistake in account Exception Value: Unknown field(s) (image) specified for User What did I miss? -
How do I run pytest in Jenkins server for django application?
I want to run pytest to verify all my unit test cases are passed in Jenkins server before deploying to production server. Can we achieve it without activating the virtualenv in the jenkins server? How is it done generally in jenkins server? -
How to reference a table from an existing Oracle Database for Django's ORM?
Context In the current Django project I am working on, I need to pull data from an existing Oracle database (12c). After setting up my environment as recommended by the Django documentation, it is however not possible to have access to the tables and their content via Django's ORM. I narrowed the problem to a naming problem between Django's ORM and existing tables for a database. Simply put, the question is : How can I reference an existing table from an Oracle database, in order to make queries via Django's ORM ? Configuration : Ubuntu Oracle 12c Oracle client 12.2 Django 1.11.7 The system uses two databases, one for the user management (SQL Lite in dev environment) and one for pulling data (an Oracle database). A router is used to handle the databases. The Oracle database shouldn't be modified since it is used by other systems, nonetheless the account used to connect to it in Django's settings, has the privileges to modify the database. The error : "ORA-00942: table or view does not exist" is thrown when making queries via Django's ORM. Even though it is possible to access the table with cx_Oracle IntelliJ's Datagrip and PyCharm. Identified issue : … -
django.db.utils.OperationalError: table "blog_post" already exists
I'm creating a blog using Django and anytime I run manage.py migrate, I get the error below: (venv) (C:\Users\KOLAPO\Anaconda3) C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads>manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, taggit Running migrations: Applying blog.0001_initial...Traceback (most recent call last): File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "blog_post" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\operations\models.py", line 96, in database_forwards schema_editor.create_model(model) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 295, in create_model self.execute(sql, params or None) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute cursor.execute(sql, params) File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 79, … -
What are form factories and when should they be used?
Would someone like to attempt a succinct explanation of what a form_factory, or a modelform_factory is in relation to a form / modelform? Why use a factory? Is there an official technical definition for a factory method? -
Django: Parent categories doesn't shown in admin interface
Problem: Dash signs display in 'Parent category' column before I open any menu item. I get 'Parent category' items when open menu item profile(see admin.py below) Before and after opening of menu profile: picture1 and picture2 (pay attention on Parent Category column) My models.py: (attention on parent_id) class Menu(models.Model): cat_title = models.CharField(max_length=150, verbose_name='Category title') menu_title = models.CharField(max_length=150, verbose_name='Menu title') parent_id = models.IntegerField(blank=True, null=True, verbose_name='Parent category', choices=(('',''),)) url = models.CharField(max_length=255, verbose_name='URL', blank=True) named_url = models.CharField(max_length=255, verbose_name='Named URL', blank=True) level = models.IntegerField(default=0, editable=False) My admin.py: () class MyMenu(admin.ModelAdmin): def get_choices(self): choices = (('',''),) categories = models.Menu.objects.all().values() for i in categories: choices += ((i['id'], i['cat_title']),) return choices def formfield_for_choice_field(self, db_field, request): if db_field.name == 'parent_id': db_field.choices = self.get_choices() return super().formfield_for_choice_field(db_field, request) list_display = ('cat_title', 'menu_title', 'parent_id', 'level') list_display_links = ('cat_title', 'menu_title') admin.site.register(models.Menu, MyMenu) Question: How could I rewrite my admin.py to show parent_id items without opening any menu item profile? I've already tried Model.get_FOO_display() but it doesn't work in right way. Any help would be appreciated.