Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can celery use Django ORM?
How can celery use Django ORM? Celery and django are diffent processes. But, Celery worker can use Django Application code.(ORM, Model..) I think celery process have django application code. Is it right? What should I do setting when django and celery on another server physically? I was wondering how Celery can use the code in the django. -
How to make href point to a django template and pass context to it?
I have a django template listing mails/messages from a sql database. I am trying to make those messages clickable by using an <a> tag, as to open a page displaying the content of the message. Part of my template listing the messages : <table> <th>ID</th> <th>DATE</th> <th>SUJET</th> <th>SENDER</th> {% for message in messages %} <tr> <td>{{message.id}}</td> <td>{{message.date}}</td> <td><a href="">{{message.subject}}</a></td> <td>{{message.sender.address}}</td> </tr> {% endfor %} </table> Is there a way to fill this href such that it calls a views.py function while passing it the correct message instance ? I tried to write <a href={% url 'show_message' {{message}} %}> Where show_message would be a url name in my app_urls.py, but it doesn't seem to work. The doc seems to point to something similar though. Thank you ! -
drf allauth google signup sign in
Im using django allauth for google signup sign in after successfully sign in, all the functions which need authentication will be performed after user is authenticated but i dont know how to authenticate the user in backend after sign in sign up using customuser inheriting abstractbaseuser and a user with additional required field tried google sign in but want to authenticate the user -
Problem with Django template inheritance, i had tried referring Django docs and everything with the code is correct but the expected out is wrong
trying to extend base.html so that my home.html will be visible in base.html body I think i have missed something, can anyone take a look and suggest me. once check this code https://github.com/Pav125/portfolio/tree/main/portfo/skills/templates/skills or see parts of the code base.html <div> {% block template %}{% endblock template %} </div> home.html: {% extends "skills/base.html" %} {% block template %} Code here {% endblock template %} views.py from django.shortcuts import render def home(request): return render(request, 'skills/base.html') the content of the home.html file was not visible on web when i run the server -
How do I start a django project with uvicorn in pycharm and debug
I want to debug a django project using pycharm, but this django project uses uvicorn blogs.asgi: application --host 0.0.0.0 --port 8000 starts. How do I configure pycharm so that it starts a normal django project by clicking the Debug button in the upper right corner of pycharm The following is the normal django project startup configuration: enter image description here I tried to search various documents for configuration, but was unsuccessful。 I want to know how to set it up, can you give me some Pointers? Thank you My English is not good, if the description is inappropriate, please forgive me -
Error when using cms.api.create_page "UserWarning: No user has been supplied when creating a new PageContent object."
When I use the Django CMS API "create_page" function I get the following error: UserWarning: No user has been supplied when creating a new PageContent object. No version could be created. Make sure that the creating code also creates a Version objects or use PageContent.objects.with_user(user).create(...) page_content = PageContent.objects.with_user(user).create( When the "create_page" function is run it creates a page and then runs the "create_page_content" function which throws an error at the following line of code: user = getattr(_thread_locals, "user", "unknown user") page_content = PageContent.objects.with_user(user).create( language=language, title=title, menu_title=menu_title, page_title=page_title, redirect=redirect, meta_description=meta_description, page=page, created_by=created_by, changed_by=created_by, soft_root=soft_root, in_navigation=in_navigation, template=template, limit_visibility_in_menu=limit_visibility_in_menu, xframe_options=xframe_options, ) This is part of Django CMS' inbuilt API so I can't really change it. I could copy the "create_page" and "create_page_content" functions and use the edited copies but that seems like a fairly brute force solution and I'm probably just missing something. My relevant code: from cms.api import create_page from cms.constants import TEMPLATE_INHERITANCE_MAGIC new_page = create_page(title='Example', template=TEMPLATE_INHERITANCE_MAGIC, language='en') -
Django puts AND clause to lookup "in"
Django 4.2 together with graphene-django filters is making my query use AND operation class ExampleFilterSet(FilterSet): tags__name__in = StringInFilter(method="filter_tags_and_categories") class Meta: model = Example fields = {"users__email": ["in"]} Ideally, here it should have been OR query - where users__email in ['abc@gmail.com' , 'xyz@gmail.com'] but on debugging its doing an AND operation It was working well with django3.1 and graphene-django 2.9.9 -
Nginx[emerg] "map" directive is not allowed here in /etc/nginx/sites-enabled/default:1
This is my /etc/nginx/sites-enabled/default file map $sent_http_content_type $expires { default off; text/html epoch; text/css 30d; application/javascript 30d; ~image/ max; } server { listen 80 default_server; listen [::]:80 default_server; expires $expires; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /home/ubuntu/ask-local-django; # Add index.php to the list if you are using PHP #index index.html index.htm index.nginx-debian.html; server_name api.example.in admin.example.in; #location /favicon.ico { access_log off; log_not_found off; } location /media { autoindex on; alias /home/ubuntu/ask-local-django/media/; } location /static { access_log off; log_not_found off; alias /home/ubuntu/ask-local-django/staticfiles; } # location /.well-known { # alias /home/ubuntu/ask-local-django/well-known; # } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } #location /.wellness/assetlink.json { # root /home/ubuntu/ask-local-django/static/; # } access_log /home/ubuntu/logs/ask_local_access.log; error_log /home/ubuntu/logs/ask_local_error.log; # pass PHP scripts to FastCGI server # #location ~ \.php$ { # include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): # fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; # # With php-cgi (or … -
How do I access all files, such as environment variables
import Logging logger = logging.getLogger(__name__) logger = logging.getLogger("") How do I make this part accessible from all files? Is there a way to use it on all files without importing it similar to the environment variable? -
Deleting Django migrations in the auth app
I have a migration that was created for the built in django auth app and we realized it was a bad idea and want to completely remove it because its buggy. however since this migration was for the pre built auth app i have no clue where to find it in the directory to even remove it? We have a staging and production environment we'd need to apply this change to as well and Im unsure how to remove and where to even remove this change from -
Is it better to use http requests or websocket connection for uploading and retrieving static content
Is it better in terms of server load, resources, cost, ..etc to use standard post and get http requests or a web socket to initially upload and/or retrieve static content such as profile pics of a user and other users. Assume web-sockets are already being used for a real-time messaging feature between users, when user is authenticated at login or already logged in and opens app a web-socket is established. Don't worry about the difficulty of the coding in this question. And of course to log in and sign up http requests and JWT are used. Case 1: a user opens their own profile page. Case 2: A user then opens a search bar where they can search for other users. Initially they get a generic list of users. Complete with their names and profile pics, before they search for a specific user. Of course the user can scroll down to see more users profile. Essentially when there’s a page that needs to retrieve multiple profile pics or other static content. What would be the best way to deal with this static content efficiently with the least server load, resource, consumption and runtime cost? While you’re here what about dynamic … -
How do I get access to every file?
import Logging logger = logging.getLogger(__name__) logger = logging.getLogger("") How do I make this part accessible from all files? -
Django oauth toolkit, setting the scopes for separate authorization server
I am trying to separate my resource server with the authorization server https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html, and now confused on the setting of the SCOPES available in the authorization server. From my understanding, the authorization server would need to know the entities/models of the resource server in order for it to be able to create scopes, for example scopes like read:products, delete:products, read:customers, etc. Then the auth server would need to know that products, customers, etc. exist as entities in the resource server. So would my auth server (on startup) need to read the db of the resource server and get all the entities in it, so it can create scopes? How is this usually done in industry? Wouldn't this also mean the auth server is not completely isolated from the resource server? (since if the resource and auth servers are the same, it's easy to get the models/entities, but now it's confusing). And if I have the servers separate like this I would have 2 databases (the resource server's and the authorization's). How should I synchronize user related tables between the two databases? Since my resource server still needs user related data too e.g. an attribute User in Product object. I have … -
Am I missing something with Django's makemigrations?
I am working on a Django project and am struggling with adding a new field to a models class. I am still pretty new, but this is what my models class look like: class Manager(models.Model): ''' Create Manager model that the database will be used to create the database. Manager will house any and all necessary information about league managers. ''' manager_id = models.CharField(max_length=255,primary_key=True) team_name = models.CharField(max_length=255,null=True) display_name = models.CharField(max_length=255) record = models.CharField(max_length=255,null=True) I have another class League which contains a "league_id" field and I am attempting to add a Foreign Key reference to the "league_id" field in the Manager class. I attempted to add: league_id = models.ForeignKey("League",on_delete=models.CASCADE, db_column='league_id', default=0) Not sure if there is something wrong with the above, but I get the following error when I attempt to run makemigrations: django.db.utils.OperationalError: no such column: fantasy_basketball_manager.league_id Django version is 5.0.4 Python version is 3.12.0 I have attempted to delete the database, delete previous migrations files, and a few other thing. All of which I know are not necessarily good things to do, but I'm trying pretty much whatever I found online. I have my reverted any deletions so they are back to original states. I'm at a loss of … -
I use mac, starting django using visual code studio. I fail to start a new app “startapp” I get syntax error “ File ‘Manage.py’, line 17 ) from exc”
I am starting django with visual code studio. I fail to start a new app “startapp” I get syntax error “ File ‘Manage.py’, line 17 ) from exc” I tried changing in manage.py putting “except Exception as exc” but no good results -
nginx, gunicorn & django on amazon lightsail, what is the hostname of the ip address?
I deployed a Django application to Amazon Lightsail VPS, and it works as expected when I access it by the domain name xxxxx.com, However, if I tried to access it by the IP address, it gave an error: Invalid HTTP_HOST header: 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com'. You may need to add 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com' to ALLOWED_HOSTS. DisallowedHost at / Invalid HTTP_HOST header: 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com'. You may need to add 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com' to ALLOWED_HOSTS. Request Method: GET Request URL: https://ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com/` Of course, the MY-IP-ADDR-Here is my actual IP address number. I wander: Why did the lightsail change the url from 'MY.IP.Addr.Here' to ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com/? Why did the nginx proxy this request to Django? I expected it to discard the request. Is it safe to add the ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com to my allowed hosts? Is it a good idea to remove MY-IP-ADDR-Here from my'settings.py`? The following are the related configuration parameters: /etc/nginx/sites-enabled/mysite server { listen 80; server_name xxxxx.com MY.IP.ADDr.Here; location / { include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass http://unix:/run/gunicorn.sock; } } # many lines created hy certbot # `# I added the following block to tell nginx to discard any request that doesn't match the xxxxx.com MY.IP.ADDr.Here; # https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/#allowed-hosts` server { listen 80 default_server; listen [::]:80 default_server; return 444; } myproject/settings.py … -
Does wagtail tag {% slugurl 'page' %} work with Wagtail-localize?
I'm building a website with Django, Wagtail and Wagtail Localize. But when I'm load my website on "https://exemple.com/fr/" the slugurl tags generates links like href="/en/about/" I followed settings for urls.py : urlpatterns = urlpatterns + i18n_patterns( path("search/", search_views.search, name="search"), path("", include(wagtail_urls)), ) I also added middleware and others setting like LANGUAGES. Page are correctly translated and accessible with urls. The language code is detected because tag like {% if LANGUAGE_CODE == "fr" %} is working but this slugurl never work and always display "/en/about/" : <a href="{% slugurl 'about' %}" class="nav-links">about</a> Navigation isn't very fluid, because when you access a page you have to reselect the language each time. Is slugurl supposed to work with Wagtail-localize? -
Django: psychopg2 unique violation error anyway to fix this
I was updating my django projects version from 2.1 to 2.2 and it looks like some errors occurred with my staging database (I am assuming from all the answers that look similar to my problem). I however am unsure on how to correct this without losing or corrupting the data any further. Attached are the console errors I am facing, anyway to solve these? [ubuntu@staging.internal.] out: [36;1mOperations to perform:[0m [ubuntu@staging.internal.] out: [1m Apply all migrations: [0madmin, adverts, apple_news, articles, auth, bookmarks, captcha, checkins, contacts, contenttypes, contests, custom_flatpages, events, favourites, features, flatpages, hipimagingtools, home, listings, notifications, patio_guide, photos, profiles, ratings, sessions, sites, slide_shows, streams, tastypie, team, todos, videos [ubuntu@staging.internal.] out: [36;1mRunning migrations:[0m [ubuntu@staging.internal.] out: Applying auth.0010_alter_group_name_max_length...[32;1m OK[0m [ubuntu@staging.internal.] out: Applying auth.0011_update_proxy_permissions...Traceback (most recent call last): [ubuntu@staging.internal.] out: File "/project/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute [ubuntu@staging.internal.] out: return self.cursor.execute(sql, params) [ubuntu@staging.internal.] out: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "auth_permission_content_type_id_key" [ubuntu@staging.internal.] out: DETAIL: Key (content_type_id, codename)=(114, add_djangouser) already exists. [ubuntu@staging.internal. out: [ubuntu@staging.internal.] out: [ubuntu@staging.internal.] out: The above exception was the direct cause of the following exception: [ubuntu@staging.internal.] out: [ubuntu@staging.internal.] out: Traceback (most recent call last): [ubuntu@staging.internal.] out: File "manage.py", line 14, in <module> [ubuntu@staging.internal.] out: execute_from_command_line(sys.argv) [ubuntu@staging.internal.] out: File "/project_name/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in … -
django IntegrityError: Check constraint failed: new__blog_blogpage
I'm trying to build a blog using Django(wagtail cms) and have this error now that I'm not quite sure I understand. I'm assuming it has to do with my blog model. I've been googling for a day and half with no success. Many times the results are for NOT NULL constraint or ForeignKey error, but obviously my error is something different... I'm going to post my entire blog model because of the error text: new__blog_blogpage I just kept building off the getting started tutorial from wagtail docs and much of their demo project on github. I'm just not using all that code, mainly just the blog stuff... from __future__ import unicode_literals from django import forms from django.db import models from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey, ParentalManyToManyField from wagtail.models import Page, Orderable from wagtail.fields import RichTextField, StreamField from wagtail.admin.panels import FieldPanel, InlinePanel, MultiFieldPanel, MultipleChooserPanel from wagtail.snippets.models import register_snippet from base.blocks import BaseStreamBlock # add this: from wagtail.search import index # keep the definition of BlogIndexPage model, and add the BlogPage model: class BlogPersonRelationship(Orderable, models.Model): page = ParentalKey( "BlogPage", related_name="blog_person_relationship", on_delete=models.CASCADE ) person = models.ForeignKey( "base.Person", related_name="person_blog_relationship", on_delete=models.CASCADE ) panels = [FieldPanel("person")] class BlogPage(Page): introduction = models.TextField(help_text="Text to describe the … -
Django with datatables bootstrap 5 pagination is not working properly
I am learning Django with a sample web page. And I am trying to integrate Jquery DataTable with Bootstrap 5. The issue is, I have a total of 12 records in the DB. When I do the code and return the data to jquery, the table loads and it interpret it as a single set. So instead of showing pages 1 and 2 in the pagination, it is showing page 1 only. Giving my code below views.py def get_recipe(request): if request.method == "POST": # all_recipes = Recipe.objects.all() # data = list(all_recipes.values()) # return JsonResponse({"data": data}, safe=False) draw = int(request.POST.get("draw", 0)) start = int(request.POST.get("start", 0)) length = int(request.POST.get("length", 10)) # Default to 10 records per page search_value = request.POST.get("search[value]", "") order_column = request.POST.get("order[0][column]", "") order_dir = request.POST.get("order[0][dir]", "asc") page = start // length # Filter and retrieve data based on parameters (replace with your logic) total_data_count = Recipe.objects.all().count() filtered_data_count = total_data_count data = Recipe.objects.all()[page * length : (page + 1) * length] # Convert data to a list of dictionaries (or use a serializer) data_list = list(data.values()) # Prepare the response data response = { "draw": draw, "recordsTotal": total_data_count, "recordsFiltered": total_data_count, "data": data_list, } return JsonResponse(response, safe=False) else: return JsonResponse({"status": "error", … -
Atomic transaction with more than one model
I have a view that saves the data in two different models "Eliel_FuncionarioAlocacao" and "Eliel_FuncionarioAlocacaoCentro", however if an error occurs when creating "Eliel_FuncionarioAlocacaoCentro", it is not giving the rollback so as not to also create "Eliel_FuncionarioAlocacao", what am I doing wrong in this view? from .serializers import FuncionarioAlocacaoSerializer from auditlog.context import set_actor from client.app_eliel.models import Eliel_FuncionarioAlocacao, Eliel_FuncionarioAlocacaoCentro from django.db import transaction from microservices.serializers import ActorSerializer from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasReadWriteScope from project_datafit.utils import log_error from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.exceptions import ValidationError from rest_framework.response import Response import json import re @api_view(['POST']) @authentication_classes([OAuth2Authentication]) @permission_classes([TokenHasReadWriteScope]) def funcionarioAlocacao_create_api(request): actor_serializer = ActorSerializer(data=request.data) funcionarioAlocacao_serializer = FuncionarioAlocacaoSerializer(data=request.data) try: actor_serializer.is_valid(raise_exception=True) funcionarioAlocacao_serializer.is_valid(raise_exception=True) actor = actor_serializer.validated_data['actor'] matricula = funcionarioAlocacao_serializer.validated_data['matricula'] data_inicio = funcionarioAlocacao_serializer.validated_data['data_inicio'] data_fim = funcionarioAlocacao_serializer.validated_data['data_fim'] obs = funcionarioAlocacao_serializer.validated_data.get('obs') centros_data = funcionarioAlocacao_serializer.validated_data.get('centros', []) with transaction.atomic(): with set_actor(actor): try: funcionarioAlocacao = Eliel_FuncionarioAlocacao(Matricula=matricula, DataInicio=data_inicio, DataFim=data_fim, Obs=obs) funcionarioAlocacao.save() for centro_data_str in centros_data: centro_data = json.loads(centro_data_str) centro = centro_data.get('centro') porcentagem = centro_data.get('porcentagem') Eliel_FuncionarioAlocacaoCentro.objects.create( IdAlocacao=funcionarioAlocacao, CodCentro=centro, Peso=porcentagem ) return Response({'success': 'Alocação feita com sucesso'}, status=status.HTTP_200_OK) except Exception as e: log_error(request.path, str(e), actor) return Response({'error': 'Erro ao alocar funcionário'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except ValidationError as e: error_message = str(e.detail) error_message = re.search(r"ErrorDetail\(string='([^']*)'", error_message).group(1) return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST) I want the atomic transaction … -
ImportError in Views.py inside my django project
I am trying to import a function form a project I have made a few months ago, but I get a this error: ModuleNotFoundError: No module named 'seleniumtrack' I tried some things ChatGPT recommended and I tried to look things up on the internet, but unfortunately it didn't work. This is how my files are ordered: python/ ├── seleniumtrack.py └── tracklist/ ├── manage.py └── downloader/ └── views.py I am trying to learn Django, but here is my views.py script: from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect from django.urls import reverse import seleniumtrack class SearchTracklist(forms.Form): url = forms.CharField(label="Tracklist url") class StartScraping(forms.Form): start = forms.CharField(widget=forms.HiddenInput(), initial="start") # Create your views here. def index(request): if "urls" not in request.session: request.session["urls"] = [] if request.method == "POST": form = StartScraping(request.POST) if form.is_valid(): for url in request.session["urls"]: seleniumtrack.scrape(url) else: return render(request, "tracklist/index.html", { "form": form }) return render(request, "tracklist/index.html", { "urls": request.session["urls"] }) def add(request): if request.method == "POST": form = SearchTracklist(request.POST) if form.is_valid(): url = form.cleaned_data["url"] request.session["urls"] += [url] return HttpResponseRedirect(reverse("downloader:index")) else: return render(request, "tracklist/index.html", { "form": form }) return render(request, "tracklist/add.html", { "form": SearchTracklist() }) Can somebody help? -
ckeditor is not good for django anymore
before ckeditor worked for django but now it is not working and expired. django by itself suggest non-free ckeditor 4 LTS or ckeditor 5 but I don't know how to use it please if there is give me another editor for django or guide me for this ckeditor. -
django-dbbackup: server and pg_dump version mismatch
I faced on this error. who can help me? command: python manage.py dbbackup error: Traceback (most recent call last): File "/passchain/manage.py", line 22, in <module> main() File "/passchain/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/dbbackup/utils.py", line 120, in wrapper func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 93, in handle self._save_new_backup(database) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 106, in _save_new_backup outputfile = self.connector.create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 92, in create_dump return self._create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/postgresql.py", line 112, in _create_dump stdout, stderr = self.run_command(cmd, env=self.dump_env) File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 171, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump --dbname=postgresql://root:%251fiY%263%40%21%4073%2A6%25ZJ6dT%40%40%253703%2A%5E%2A3%26%254oW046%264%25%250%24%40fexO%2AY%40CRhFy8%2A%240%5E05%2105%407%23@db:5432/db --format=custom pg_dump: error: aborting because of server version mismatch pg_dump: detail: server version: 16.0; pg_dump version: 15.6 (Debian 15.6-0+deb12u1) i have installed postgress-client and therre is not exist any pg_dump package newer version 15 -
How to sort a queryset by a attributes's choices
I have a model with a selectable month and year, like so: class Item(models.Model): MONTHS_CHOICES = [ ('JANUARY', 'January'), ('FEBRUARY', 'February'), ('MARCH', 'March'), ('APRIL', 'April'), ('MAY', 'May'), ('JUNE', 'June'), ('JULY', 'July'), ('AUGUST', 'August'), ('SEPTEMBER', 'September'), ('OCTOBER', 'October'), ('NOVEMBER', 'November'), ('DECEMBER', 'December') ] month = models.CharField(max_length=9, choices=MONTHS_CHOICES, default="JANUARY", db_index=True) year = models.IntegerField(default=0) (...) If I try to order the items by month and year Item.objects.all().order_by("-year", "month"). Logically the months will be be ordered alphabetically. What can I do to get the items ordered by the same order I have the months on MONTHS_CHOICES? Option B is just redo the models to include a DateField with only year and month, like this question here and order it by that field I also tried the solutions on this page but nothing worked to me.