Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Как хранить и отображать параметры сайта (то есть какие-то числа, не связанные с работой django, для моих скриптов) через админку?
Можете подсказать где хранить такую информацию (в базе данных через модели django или как-то по-другому) и как сделать переход к ним в админке. Буду очень благодарен. -
Django: How to stop django session from expiring in django?
I have written a logic where a referer would get some point when the person they refered buy a package. Now the problem with this is that when i refer someone and they sign up and also buys a package immediately i the referer gets some point when after sometime maybe a day, if they buys another package i do not get any point again. In this case i feel like a session is timing out or something, but i cannot really tell what the problem here it. this is the code that gives me (or any user that refered someone) some point when the person they refered buy some package views.py profile_id = request.session.get('ref_profile') if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) print("Profile Id Is" + str(profile_id)) recommended_by_profile.indirect_ref_earning += 250 recommended_by_profile.save() else: print("Profile ID is None and no point where given") THis s my registerRef view that signs-up a user and detects the person who refered them def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile … -
geodjango spatial lookup failure Only numeric values of degree units are allowed on geographic DWithin queries
So I'm building Django app which has some stores saved with coordinates in db, all I need to do, when I get user coordinates, I want to search in db for the nearest store, IDk what to do after receiving coordinates eveything raises error tried this hard coded query lookup Shop.objects.filter(location__dwithin = (GEOSGeometry(Point(-95.23592948913574, 38.97127105172941)), D(km=5))) but still getting errors like Only numeric values of degree units are allowed on geographic DWithin queries. the srid if it matters is 4326, idk even know what this is -
TimeoutError [winError10060]
This is my function for sending email, but i am getting time out error. I tried to solve my problem by disabling the proxy settings and also enabling the imap from gmail. None is helping. Plus I think less secure app option is also disabled. Correct me if I am wrong settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIl_HOST = 587 EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = '#####' EMAIL_USE_TLS = True view.py def register(request): if request.method =='POST': form = RegistraionForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split('@')[0] user = Account.objects.create_user(first_name=first_name,last_name=last_name,email=email,username=username, password=password) user.phone_number = phone_number user.save() #user activation current_site = get_current_site(request) mail_subject = 'Please activate your account' message = render_to_string('accounts/account_verification_email.html',{ 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() messages.success(request, "Registration successful") return redirect('register') else: form = RegistraionForm() context={ 'form':form, } return render(request, 'accounts/register.html',context) -
How can i update quantity in the django cart?
model.py class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.IntegerField() date_added = models.DateTimeField(auto_now_add=True) if request.method == "POST": customer = request.user.customer order ,created = Order.objects.get_or_create(customer=customer,complete=False) id = request.POST.get('id') product = Product.objects.get(id=id) if OrderItem.objects.filter(product=product): orderitem = OrderItem.objects.filter(product=product) orderitem.quantity+=1 order.save() else: orderitem = OrderItem.objects.create(product=product,order=order,quantity=1) products = Product.objects.all() return render(request, "HTML/index.html",{'products':products}) Error QuerySet' object has no attribute 'quantity' I'm trying to a cart if an item exists in this cart, the system should update its quantity, if not then a new item should be created in the cart, how can i do that? -
Repeated syntax errors while guy in tutorial is getting none
I am new to coding, and am following a tutorial on how to make a forum website. I am instructed to enter two lines of code into the VScode terminal, which are: $ git clone https://github.com/SelmiAbderrahim/AutoDjango.git $ python AutoDjango/AutoDjango.py --venv The first one works fine and clones everything into my workspace, but for the second line I keep getting syntax errors. The first one was for line 43, which was: <h1 class="text-5xl">Django + Tailwind = ❤️</h1> So I took out the heart assuming it was that, but then I just got one for line 44 which was: </section> If anybody knows how to fix this, it would be much appreciated as I have spent days on this project and don't want it to end because of this problem. Here is the tutorial video with the timestamp: Tutorial -
How do I pass django variables to javascript in a for statement?
How do I pass django variables to javascript in a for statement I want to pass c.tv.tv_id in a for statement in javascript. I want to pass it to javascript in each for statement, but I don't know how to do it. {% extends 'base.html' %} {%load static%} <link rel="stylesheet" href="{% static 'css\common_movie_tv.css' %}"> {% block content %} <table> <tr> <tr> <th>name</th> <th>created_at</th> <th>comment</th> <th>evaluation</th> </tr> {% for c in object_list %} <tr> <th id = "trendings"></th> <td>{{ c.user.nickname }}</td> <td>{{c.tv.tv_id}}</td> <td>{{ c.created_at }} </td> <td>{{ c.comment }}</td> <td><h2 class = "rate" style="--rating:{{c.stars}}">{{c.stars}}</h2></td> </tr> {% endfor %} </table> <script> const tv_id = {{c.tv.tv_id}} fetch(`https://api.themoviedb.org/3/tv/${tv_id}?api_key=${TMDB_API_KEY}&language=en-US`, { method: "GET", headers: { "Content-Type": "application/json" } ) .then(res => res.json()) .then(data => { var mainDiv = document.createElement("div"); mainDiv.setAttribute("class", "card"); mainDiv.setAttribute("style", "width: 18rem;"); var img = document.createElement("img"); img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.poster_path); img.setAttribute("class", "card-img-top"); img.setAttribute("alt", "..."); var body = document.createElement("div"); body.setAttribute("class", "card-body"); var title = document.createElement("h5"); title.setAttribute("class", "card-title"); if (data.name) { title.innerHTML = data.name; } else { title.innerHTML = data.title; } //var text = document.createElement("p"); //text.setAttribute("class", "card-text"); //text.innerHTML = data.results[i].overview; var link = document.createElement("a"); link.setAttribute("href", "/" + "tv" + "/" + data.id + "/"); link.setAttribute("class", "btn btn-primary"); link.innerHTML = "View Details"; body.appendChild(title); //body.appendChild(text); body.appendChild(link); mainDiv.appendChild(img); mainDiv.appendChild(body); … -
Django app deployment on heroku compiled slug size is too large
So i am deploying my django application which consists on a reural network model used for fungus classification. The total files on the repo wheight like 100MB but i keep getting this error: 129 static files copied to '/tmp/build_dcf9fdff/hongOS_project/staticfiles'. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: ! Compiled slug size: 1.1G is too large (max is 500M). remote: ! See: http://devcenter.heroku.com/articles/slug-size remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! remote: ! We have detected that you have triggered a build from source code with version e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to hongos-heroku. remote: To https://git.heroku.com/hongos-heroku.git ! [remote rejected] develop-heroku -> main (pre-receive hook declined) error: fallo el … -
icontains unable to search certain words from a field that uses richtext field - Django
I made a search function in my project where a user can enter a query and a number of fields will be searched before sending a response with the data filtered. As usual I am using icontains in the views for making the queries in my model. I copied certain words directly from a field that uses ckeditor to the searchbar to see if it works. What I have noticed is it is unable to match certain that are in bold form. In the image for example if I search the words arbitration agreement no data is returned but as you can see the words exists in the field. This is happeing with all the bold words. Please help me to solve the problem as I am unable to understand as to why this is happeing. Below is the view that deals with the search functionality. Using ckeditor for the field. views.py def search_citation(request): q = request.data.get('q') print(f'{q}') if q is None: q = "" if len(q) > 78 or len(q) < 1: return Response({"message":'not appropriate'}, status=status.HTTP_200_OK) try: judge_name = Civil.objects.filter(judge_name__icontains = q) case_no = Civil.objects.filter(case_no__icontains = q) party_name = Civil.objects.filter(party_name__icontains = q) advocate_petitioner = Civil.objects.filter(advocate_petitioner__icontains = q) advocate_respondent = … -
footer.html is not included when extending the base.html file
In header.html, I have <h1>Header Section</h1> In footer.html, I have <h1>Footer Section</h1> In base.html I have {% include 'header.html'%} {% block content %} {% endblock %} {% include 'footer.html' %} But when I extend the base template, I only get the header and the content of the page which extends the base. The footer section appears as {% include 'footer.html' %} Why is that? -
Django: Models aren't loaded yet
I am trying to create fixtures dynamically. def create_search_options_fixtures(): for group in search_options_groups: try: this_group, created = SearchOptionGroup.objects.get_or_create( name_en = group['name_en'], ) for opt in group['options']: this_option, created = SearchOptions.objects.get_or_create( name_en = opt['name_en'], ) this_group.columns.add(this_option) this_group.save() except Exception as e: print(str(e)) Apparently the record is not yet created when I try to add a M2M relation. Thank you for any suggestions -
Django : get_context_data method from classview not working
I want to make an application that uploads files to an azure blobstorage, with a part dedicated to the history of all uploaded files. I used the post and get method of classview FormView and it works perfectly to upload the files. Now I have to query the database/model to get the history to display it. So I think the best solution is to use the get_context_data method to pass the data to the template. However it doesn't work, no data are transferred and I can't target the problem. Below is my classview and my html. Views.py class DocumentUpload(FormView) : model = TblDocument template_name = 'documents/documents.html' form_class = FilesForm context_object_name = 'object_list' def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = super(DocumentUpload, self).get_context_data(*args, **kwargs) context['object_list'] = TblDocument.objects.all() return context def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) files_selected = request.FILES.getlist('Filename') # create a list of files if form.is_valid(): for file in files_selected : # DEFINE THE DATA OF THE FILE file = FileDefinitionBeforeUpload(file=file).file_information() # GET THE CONTENT OF THE FILE content = file.read() file_io = BytesIO(content) # THE UPLOAD … -
Django TemplateDoesNotExist. Django doesn't check one of the my apps, when looking for templates
Django can't find needed template from my app. I named directory "app/template/app/template.html", my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Also I add my app name in INSTALED_APPS. I tried move my template in project's directory and its work! But I just wanna understand, why loader didn't check my app directory -
how to access specific choice in django choice field for conditional statements
I have an Account model which extends django's standard User model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group', blank=True) EMAIL_PREFERENCES = [ ('user_emails', 'User Emails'), ('group_emails', 'Group Emails'), ('leader_emails', 'Leader Emails'), ] email_preferences = MultiSelectField( verbose_name = 'Email Preferences', choices=EMAIL_PREFERENCES, blank=True, max_choices=3, max_length=255, default=['user_emails', 'group_emails', 'leader_emails'] ) I also have many celery tasks that send email notifications for when Users create, update, delete, join, or leave Groups. However, I want these emails to only be sent if the User wants them to. When a new User registers, their email preferences default to accepting all emails, but they have the ability to change their preferences in this view: class EmailPreferencesUpdate(UpdateView): model = Account form_class = EmailPreferencesUpdateForm template_name = 'accounts/update_email_preferences.html' def form_valid(self, form): instance = form.save() email = instance.user.email update_email_preferences_notification.delay(email) return HttpResponseRedirect(reverse('user_detail', args=[str(instance.pk)])) My issue is I'm trying to have conditionals, before I run my celery tasks, to see if the User allows this type of email, but I can't figure out how to access the User's choices to see if that specific choice was selected. For example, I have a UserUpdate view: class UserUpdate(generic.UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/update_user.html' def get_object(self): return self.request.user def … -
KeyError in Django REST's POST request only occurs when sent from frontend but not when sent from postman
Frontend This is my code in the frontend. In short, it fetches the bing queries from third-party api, maps through the results to create a new array, and makes a POST request to Django REST axios .get( "exampleapi.bing.com/query", { withCredentials: true } ) .then((response) => { const webPages = response.data.webPages.value.map((page: any) => ({ id: nextId(), documentId: draftId, url: page.url, title: page.name, desc: page.snippet, isNews: false, })); console.log('webPages: ', webPages); axios .post( `${process.env.NEXT_PUBLIC_API_URL}/api/v1/recsources/`, { data: webPages, }, { withCredentials: true } ) .catch(AxiosCatch); }) .catch(AxiosCatch); This is what I see when I console.log the webPages right before I make the POST request, [ { "id": "id19", "documentId": "AVD4Mpy", "url": "https://www.verywellmind.com/social-media-and-depression-5085354", "title": "The Link Between Social Media and Depression - Verywell Mind", "desc": "Studies also indicate that social media may trigger an array of negative emotions in users that contribute to or worsen their depression symptoms. Defining Depression Clinical depression or major depressive disorder is a mood disorder characterized by ongoing feelings of sadness and loss of interest in activities that an individual once enjoyed.", "isNews": false }, { "id": "id20", "documentId": "AVD4Mpy", "url": "https://www.tuw.edu/school-news/does-social-media-cause-depression/", "title": "Does Social Media Cause Depression? | Study Media Psychology", "desc": "Recent research seems to link excessive … -
How to manipulate uploaded file in Django
I'd like to know how to manipulate in other function the file uploaded. I views.py I have the code that will read the file: def upload(request): global up myfile=request.FILES['myfile'] fs=FileSystemStorage() filename=fs.save(myfile.name, myfile) uploaded=fs.url(filename) up=myfile return render(request, 'pacote_u.html', {'uploaded': uploaded}) I'm trying to open and manipulate it, part of the code I'm trying to do this: def knapsack_upload(request): p = 0 perc = p / 100 # Leitura dos arquivos start = time.time() #path = pasta + arquivo path=up data = np.loadtxt(path, dtype=float, delimiter=" ") path = path.replace('.txt', '') In a function I receive the file and in other function I want to manipulate the values of the uploaded file. -
csrf token error for class based views in django
CSRF TOKEN error for class based views I am creating a CRUD model using class based views. For the create I used the class based view, CreateView and the crispy template when displaying it on the html file. But for some reason when I am deploying the code on to my development environment I am getting the following error: CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed - https://torii-dev-internet.azurewebsites.net does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need … -
Django/Apache2 not serving media files in production when "manually" added new media
I'm using Django (Django 4.0.3.) with Apache2 to run a webserver and serving media locally. Part of the site is a warehouse item tracker and is working fine, user can upload media (images) to items, categories etc and everything is displayed as expected. The other part displays multiple images downloaded from an ftp server via a script I wrote in python, which downloads images, stores them in its specific folder (in the media folder) and edits the Sqlite3 db to point Django to the correct media path - these images however is not displayed when "debug=False". It works when "debug=True". When clicking image I get the message: Not Found The requested resource was not found on this server. It's my first Django project so I'm a little out of my depth and I'm not really sure what to google. Anyone have any ideas how to make this work or how I could do this another way? My guess would be that it has something to do with static files? Project structure: |mysite |__warehouse |__static |__mysite |__media | |__lots of folders | |__(image) |__cameras Apache django.config: Alias /static /home/usr/mysite/static <Directory /home/usr/mysite/static> Require all granted </Directory> Alias /media /home/usr/mysite/media <Directory /home/usr/mysite/media> Require … -
How to force fill field to Inline Models in Django
We added the model named Comment as inlines in the Course model. We want to make it mandatory to fill in the fields in the Inlines model when the Save button is clicked. # models.py class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... updated_at = models.DateTimeField(auto_now=True)) class Comment(models.Model): CHOICES=[(1,'Approved'), (0,'Rejected')] course = models.ForeignKey(Course, on_delete=models.PROTECT) opinion = models.IntegerField(choices=CHOICES) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # admin.py class CommentInline(admin.StackedInline): model = Comment max_num = 1 radio_fields={'opinion':admin.HORIZONTAL} @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'reviewer', 'created_at',) inlines = [CommentInline,] -
Django forms - 'CalculatorFormProduct' object has no attribute 'kwargs'
I am trying to filter my dropdown list and I get the following error KeyError at /product/product-name/ 'slug' I am not sure how to apply a slug filter in my formset so the user can only see components that are related to this product. Based on few answers and articles I know that I can pass slug by using kwargs.pop() in init method but it doesn't work in my case What I've tried so far: product_slug = kwargs.pop('related_product__slug') product_slug = kwargs.pop('slug') I even tried this: product_slug = self.kwargs['slug'] But I get this error: 'CalculatorFormProduct' object has no attribute 'kwargs' None of the above approached worked. I am confused about how should I do it correctly. Any advice on what am I doing wrong will be appreciated. forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(),required = False) number_of_units = forms.IntegerField(min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) def __init__(self, *args, **kwargs): # product_slug = kwargs.pop('related_product__slug') product_slug = self.kwargs['related_product__slug'] super().__init__(*args, **kwargs) self.fields['related_component'].queryset = CostCalculator.objects.filter(related_product__id=product_slug) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units', 'total_price') readonly_fields = ('created', 'related_product') CalculatorFormsetProduct = formset_factory(CalculatorFormProduct, extra=0) views.py ProductDetailView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'calculator/cost_calculator.html' model … -
Sometimes i get No changes detected when i try to do makemigrations
so my problem is that sometimes when I try to do makemigrations it gives me No changes detected error while I did some changes to my tables . I also tried py manage.py makemigrations ( name of my app ) at first it acts like everything is ok and successful but then when you want to display the tables you edited in models.py it raise error which the new row doesnt exist. anyway i also tried to used python manage.py migrate --fake Please give me some suggestion what to do ! -
filtering before joining django orm
I have three imaginary models: class Singer(BaseModel): singer_name = models.CharField(max_length=50, db_index=True) album = ForeignKey(album, on_delete=models.CASCADE, null=True, related_name="singer_album") class Album(BaseModel): album_name = models.CharField(max_length=50, db_index=True) class Fan(BaseModel): fan_name = models.CharField(max_length=50, db_index=True) admired_singer = ForeignKey(Singer, on_delete=models.CASCADE, null=True, related_name="fan_singer") now lets say I want to query all singers + albums starting with 'g' that belong to the singer that the fan 'RSNboim' admired. my intuition is to go like queryset = Fan.objects.values('admired_singer','album_name').filter(album_name__startswith='g') and now is my primary Question my real DB is running on about 6M records so I wish I could force Django to filter before it executes the join statement because it's consuming more effort first to join and only then filter by criteria. will inserting the filter() before the values() actually execute filtering before joining? or does Django/Postgres have their own way of prioritizing the operation's order? -
problem in loading css and js files in django project
can anyone pls help in loading and linking html css and js files so that files can be show on local host server when i run django project im newbie if anybody can help i can email them code so they can make corrections i tried almost more than 26 hours trying to solve it but cant i provided my codes here if anyone want to contact they can contact me on my email or msg or can drop their ids ill send them code this is my urls.py code from django.contrib import admin from django.urls import path from final import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.homepage), path('aboutUS/',views.aboutUS), path('course/<int:courseid>',views.courseDetail), ] this is my setting.py code """ Django settings for final project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!&f8&!k2uik_#y^b@o%4wmxxh%+xnw=gp9g=2o_h85d^^kpqd&' # SECURITY WARNING: don't run with debug turned … -
Search by multiple parameters, Django?
I have model Person: name, phone, address i have person1 with : name1, phone1, address1 Is it possible to find all entries of a model that has the same name and address but must have a different phone ? -
Order Django Queryset by attribute that could be char or int?
I have the following model that I need to order by the grade attribute, but that attribute can be either a character or integer (K, KA, KF, NA, 1, 2, 3, etc.)... what is the best way to accomplish that? We are using MS SQL as a backend (I cannot use __regex because the DB version does not support it). I annotated a first_letter_group attribute onto the queryset because any grade with multiple letters should be treated as it's first letter (KA = K, KN = K, etc.) I'm trying to order these results by alpha first, then ascending numerically (e.g. 'P, K, 1, 2, 3, 4...') # This is an unmanaged model class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="loc_id") grade = models.CharField(db_column="grade", max_length=10) end_year = models.IntegerField(db_column="end_year") run_date = models.DateField(db_column="run_date") student_count = models.IntegerField(db_column="students") I've tried annotating additional fields where I cast the results to CharField or IntegerField but they (expectedly) error out when they hit something that does not convert. all_enrollments = ( Enrollment.objects.filter( location_id__in=location_ids, end_year=today.year, ) .order_by("-run_date") .annotate(first_letter_group=Substr("grade", 1, 1)) ) ordered_enrollment_list = ( all_enrollments.annotate( number_field=Cast( "first_letter_group", output_field=IntegerField() ), str_field=Cast( "first_letter_group", output_field=IntegerField() ), ) .order_by("-str_field", "number_field") ) I can't figure out how to do this without the …