Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to use Template Tags
I'm trying to create a form with dependent dropdowns so far I have been able to add the required triggers but I just noticed that the response message wasn't rendering template tags Even other HTML files that I try to add template tags to just gets ignored I have no clue what is even causing this kind of error After viewing a few other posts which said that if I were to use {% load XYZ %}. That I should use this load tag in all my HTML pages but this didn't solve my problem my views.py: from django.shortcuts import render,redirect from django.views.generic.base import TemplateView from status.forms import StatusForm from status.models import FlightStatus from django.views.generic import ListView, CreateView, UpdateView from postlog.models import Flight from django.urls import reverse_lazy # Create your views here. class StatusPageView(CreateView): template_name = "status/home.html" model = FlightStatus form_class = StatusForm success_url = reverse_lazy('status') def load_park_bay(request): flightid = request.GET.get('flight1') parks = Flight.objects.filter(fl_no='flightid').order_by('park_bay') context = {'parks': parks} return render(request, 'status/park_bay_dropdown_list.html', context) my urls.py: from django.urls import path,include from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.StatusPageView.as_view(), name='status'), path('ajax/load-park/', views.load_park_bay, name='ajax_load_park'), ] my home page where my form is present home.html: {% extends 'base_template1.html' %} {% … -
Where to put/ how to overide TokenAuthentication migrations
I'm adding TokenAuthentication to our django project, as we're adding an api to an already established project. In the DRF docs i see that: Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. I also see that to create tokens for existing tokens i need to run: for user in User.objects.all(): Token.objects.get_or_create(user=user) Good up to this point, but for me the populate tokens for existing users needs to be in the migration. I see the migration when i migrate: Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747... OK How can i add an operation to this (like here) and where is this magical migration coming from, I can't see it in my version control? -
Classic Django and today's demand?
I have question. Is classic django a good solution for large projects? Maybe a better solution is to write a backend in DRF and a fronend in the JS Framework. I've heard that now using classic django with HTML templates is slowly dying out. -
Django - UserModel - How to create Custom Text Field within the django/contrib/auth/forms.py
My Question - How to create Custom Text Field within the django/contrib/auth/forms.py. ? Am trying to tweak the Django default User Model . Am adding a test field by the name "bio" My code so far in the /python3.6/site-packages/django/contrib/auth/forms.py file is as below - class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) bio = forms.CharField( #FOO_bio # this value --not getting saved in PSQL label=_("bio_test within Forms.py"), #widget=forms.PasswordInput, #Didnt work thus switched to forms.TextInput widget=forms.TextInput, strip=False, help_text=_("Enter some dummy BIO here ."), ) Further down in this file within the defined method - def clean_password2(self) , am trying to add the "bio" as def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") bio = self.cleaned_data.get("bio") # I have no clue how to do this ? print(bio) #prints None in the terminal I do understand there is no key by the name "bio" within the DICT - cleaned_data. The custom field "bio" shows up in the … -
Is there a way to put telegram-bot handler functions in a different folder?
I'm trying to create a telegram bot on Django-telegrambot library. I've downloaded the sample project from https://github.com/JungDev/django-telegrambot/tree/master/sampleproject and I'm trying to modify it. When I add an external import (for example a file which contains some command services) to telegrambot file the handlers doesn't work. I set up the bot, and it works well (i'm using ngrok and webhooks). The bot answers commands by sending messages and outputs in console POST //'TOKEN' 200. In console I get Post //'TOKEN' 200 like in normal behaviour. I've tried to write functions which get the bot and update parameters, and call them in handled functions, but it doesn't work as expected after adding the import (from .Services import CommandServices as cs): enter image description here There is no much literature about django-telegrambot. Is there a way to debug a Django program by seeing the called URL and input (POST) data -
Django Reverse Not Found When Unit-Testing
I am writing unit-tests for a Django app. The app works as expected. However, one of the new tests fails because the system is not able to find a reverse match for a view name. What am I missing? django.urls.exceptions.NoReverseMatch: Reverse for 'video_uploader.list_videos' not found. 'video_uploader.list_videos' is not a valid view function or pattern name. app/tests.py from django.test import TestCase from .models import Video from .views import * from django.db import models from django.utils import timezone from django.urls import reverse class VideoTest(TestCase): def create_video(self, name="Test Video", creation_date=timezone.now, videofile="/video/"): return Video.objects.create(name=name, videofile=videofile) def test_video_creation(self): video = self.create_video() self.assertTrue(isinstance(video, Video)) self.assertEqual(video.__str__(), video.name + ": " + str(video.videofile)) def test_videos_list_view(self): video = self.create_video() url = reverse("video_uploader.list_videos") response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertIn(video.name, response.content) app/urls.py from django.urls import path from . import views app_name = 'video_uploader' urlpatterns = [ path('upload', views.upload_video, name='upload_video'), path('', views.list_videos, name='list_videos'), ] -
Need advice on my next step as a "web developer"
Hello stack overflow ! I need some advice about where to go / what to do next. A little bit of backstory : I am 28, and 5 months ago (after saving up enough money) I started learning web development full time. I went through various books / courses / articles, and of course stack, which helped me grasp some fundamentals on a couple different technologies. Recently, past two week I have been stuck in purgatory. I am trying to get an idea for a website, or any project of some kind but without any luck so far. I have learned basic JS, Python, React, Node and Django + CMS, I have used relational and non-relational databases. Learned bootstrap, html, css, sass, flexbox...etc. I have developed multiple projects including : - Tic Tac Toe [js] - Tetris [js] - Tetris [react] - Search Recipe App [react] - AirBNB app [django backend + react] - NewsWebsite [django + react] - ToDo list [node + react] ... You get it, the stuff that everyone builds when first starting out. What do I do next ? I will be attending a bootcamp in 2 months, with a job guarantee afterwards, but in the … -
Django resize and rename user images on upload with PIL and AWS S3
I've been trying to find a good way to manage user image uploads in a new Django website. I use PIL for image manipulation and images are stored in AWS S3. What I need is: User ends up with a single image file that gets overwritten for new images Images automatically get resized on upload and converted to JPG Here's what I have so far. Profile model from django.db import models from django.contrib.auth.models import User from utils.images import image_resize_rename class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='users/profile_pics/default.png', upload_to='users/profile_pics') wp_id = models.IntegerField(null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) image_resize_rename(self.image.name, (300, 300), img_rename_basename=self.user.username) utils.images.image_resize_rename import io import os from django.core.files.storage import default_storage as storage from PIL import Image def image_resize_rename(img_name, img_size, img_rename_basename=None): read_img = storage.open(img_name, 'r') img = Image.open(read_img) if img.width > img_size[0] or img.height > img_size[1]: img.thumbnail(img_size) in_mem_file = io.BytesIO() rgb_img = img.convert('RGB') rgb_img.save(in_mem_file, format='JPEG') head, tail = os.path.split(img_name) if img_rename_basename: write_img_name = os.path.join(head, img_rename_basename + '.jpg') else: write_img_name = os.path.join(head, tail.split('.')[0] + '.jpg') write_img = storage.open(write_img_name, 'w+') write_img.write(in_mem_file.getvalue()) write_img.close() read_img.close() if os.path.exists(img_name) and write_img_name != img_name: storage.delete(img_name) What this seems to do is create a jpg from the user image upload to the … -
Django Ajax: Multiple request to getting triggered for single ajax GET request
I have a weird issue when I'm making ajax get request from my template to my view. when i click on the history button, I could see in the log that ajax has sent the request to two different URL's. console log: [06/Nov/2019 21:22:38] "GET /NewHandBook/UserHistory?uname=pvivek HTTP/1.1" 200 4306 [06/Nov/2019 21:22:38] "GET /NewHandBook/Home? HTTP/1.1" 200 9980 the request should go only to /NewHandBook/UserHistory but not sure why its hitting /NewHandBook/Home my ajax call: <form id="UserHistory"> <button type="submit" class="btn btn-primary"> <i class="fas fa-history"></i> History </button> </form> $(document).on('submit', '#UserHistory', function (e) { console.log("clicked history button"); console.log(getCookie("userName")); $.ajax({ type: 'GET', url: '/NewHandBook/UserHistory', data: { 'uname': getCookie("userName") }, success: function (data) { console.log("executed userHistory") console.log(getCookie("userName")); } }) }) Urls.py url('UserHistory', views.history) views.py def history(request): uname=request.GET.get('uname') result = UserQueryHistory.objects.filter(User_name=uname) return render(request, 'History/DbHistory.html', {"result": result}) -
Why does it look like template inheritance only works with nested blocks?
Hello I have the following 3 templates (simplified for the purpose of this post): 1 - base.html: //link stylesheet {% block page_content %} {% endblock %} //add bootstrap, jQuery and run scripts 2 - base_app.html: {% extends "base.html" %} {% block page_content %} //html here {% endblock page_content %} {% block page_app %} {% endblock page_app %} 3 - base_app_main.html: {% extends "base_app.html"%} {% block page_app %} //html i wanna display when I call render(request, 'base_app_main.html', context) {% endblock page_app %} As it is right now, when I display 3 - base_app_main.html it does not display the parts inside the {% block page_app %}block, however if I change 2 - base_app.html as below it then works: 2 - MODIFIED base_app.html: {% extends "base.html" %} {% block page_content %} //html here {% block page_app %} {% endblock page_app %} {% endblock page_content %} And I cannot understand why the template inheritance does not work in the first case and does in the second ? The documentation or online tutorials I could find do not give relevant multiple inheritance examples. -
Unable to load image scattered in more than one chunks in MongoDB?
I am working on my FYP and using Pymongo to retrieve data from the MongoDB. I am facing some problems during fetching images from the chunks. Here is the code to retrieve stored images. def get_file_object(file_id): out = fs.get(file_id).read() base64_data = codecs.encode(out, 'base64') image = base64_data.decode('utf-8') return image This code only works for the images which are not scattered into more than one documents/chunks. And if the image splits into more than one documents/chunks like shown here, it produces the result like this.The image which I am trying to retrieve is here. I want to know that how can I retrieve and show images that splits into different documents/chunks. -
Django tests not using test db
I'm trying to run some tests on my django app, but I keep having errors with the migrations. I'm using docker-compose to run my app. I can run the server, add datas in the dev db without any problem, but when I try to run the tests, I have this error : python3 manage.py test -v 3 Creating test database for alias 'default' ('test_myapp')... Operations to perform: Synchronize unmigrated apps: gis, messages, rest_framework, staticfiles Apply all migrations: admin, app, auth, authtoken, contenttypes, sessions, token_blacklist Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application authtoken Running pre-migrate handlers for application token_blacklist Running pre-migrate handlers for application app Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Running post-migrate handlers for application admin Running post-migrate handlers for application auth Running post-migrate handlers for application contenttypes Running post-migrate handlers for application sessions Running post-migrate handlers … -
django CBV: How to add access restrictions?
I'm trying to use a CBV to send an OTP to verify the number of a registered user. My code sends the OTP, however, I need to ensure the following cases. if request.user.is_staff == True, then redirect to some page. (I need to redirect users who've already verified too, but that's the same logic) if request.session['otp_session'] exists and it's age is less than 5 minutes, then display a link to "verify_otp" page. ps: Here, I've repeated mobile=self.request.user.mobile in get(0 and post(). How can I avoid this repetition? Thanks for all inputs. Here's my view class SendOTPView(FormView,LoginRequiredMixin): form_class = SendOTPForm template_name="users/send_otp.html" def get(self, request): mobile=self.request.user.mobile form = self.form_class() return render(request, self.template_name, context={'form':form, 'mobile':mobile, 'action': 'send-otp'}) def post(self, request): mobile=self.request.user.mobile url = "api-url-to-send-otp" response = requests.request("GET", url) data = response.json() if(data['Status'] =='Success'): #messages.add_message(request, messages.INFO, 'An OTP has been sent to your registered mobile number.') request.session['otp_session']={'data': data['Details']} context={'action':'verify-otp'} else: messages.add_message(request, messages.ERROR, 'Something went wrong while sending OTP. Please try again.') form = SendOTP() context={'action':'send-otp','form': form} return render(request, self.template_name, context) Here's my template {% if action == 'send-otp'%} Get an OTP in your phone ({{mobile}} {{request.user.mobile_verified}}) and verify it. {% elif action == 'verify-otp'%} An OTP has been sent to your registered mobile number. … -
django urls.exceptions.NoReverseMatch error happens when I want to use reverse function in unittests?
I recently started developing an application with django and this is the link to whole project. this is the project structure: config/ env/ .env files requirements/ __init__.py ... settings/ __init__.py base.py local.py __init__.py urls.py views.py wsgi.py projects/ api/ town/ apps.py urls.py views.py ... core/ models/ town.py serializers/ town_serializer.py ... tests/ test_town.py manage.py this is the file project/api/town.urls.py : from django.urls import path from . import views app_name = 'town' urlpatterns = [ path('town/', views.CreateTownView.as_view(), name='town-list'), path('town/<int:pk>/', views.TownViewSet.as_view(), name='town-detail') ] And the file for config/settings/urls.py: from django.contrib import admin from django.urls import path, include # from .views import views urlpatterns = [ path('admin/', admin.site.urls), # path('', views.index) path('api/', include('project.api.city.urls', namespace='city')), path('api/', include('project.api.town.urls', namespace='town')) ] API works just fine when I use this link to check out: localhost:8000/api/town but when I am trying to run the unit tests in pycharm, unfortunately some error occurs. This is some part of test module which error happens in DETAIL_TOWN_URL = reverse('town:town-detail') : from django.db import IntegrityError from django.test import TestCase from project.core.models.town import Town from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status import unittest CREATE_TOWN_URL = reverse('town:town-list') DETAIL_TOWN_URL = reverse('town:town-detail') this is the error: raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'town-detail' with … -
Why this Django signal not triggered?
I have an app called aaa. Inside "aaa.models" there are some models Inside "aaa.signals" there is a function which looks like this @receiver(pre_save) def generate_thumbnail(sender, instance, **kwargs): print("get called") Inside "aaa.apps.py", there is something like this, which is waking up the signal function. class AaaConfig(AppConfig): name = 'aaa' def ready(self): from . import signals I have included this app into "settings.py" INSTALLED_APPS = [ ...... , 'aaa', ] I have found that this signal never gets called when any of the models' instance is saved, no matter the instance is saved during test or shell, or normal running time. -
Django: Updating Context Value every time form is updated
I've got an UpdateView I'm using to update some data from my model, but I want to give my user only a max amount of times they can do it, after they used all their "updates" it should not be possible anymore. My view looks like this: class TeamUpdate(UpdateView): model = Team template_name = 'team/team_update_form.html' context_object_name = 'team' form_class = TeamUpdateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'max_updates': 2 }) return context def form_valid(self, form, **kwargs): team = form.save() // update context somehow so that it has the new value for max_updates? messages.success(self.request, f'{team} was updated') return redirect(team.get_absolute_url()) My Problem right now is that I don't know how I can dynamically update my context every time my form is updated. How would I do that? I assume the hardcoded "2" must be removed and I probably have to do something like 2 if not value_from_form else value_from_form but how do I get this value_from_form? And could I use this value in my a dispatch to check if its zero and then redirect my user back with a warning message like "Sorry you've used up all you're updates for this team!". Thanks to anyone who answers! -
Django 2.2 not setting cookies when accessing via IP (192.168.x.x:y)
I'm developing a Django 2 and Python 3 web-app. When accessing it through 0.0.0.0 it works and sets the cookie, but if I access it with my local network IP address the cookies aren't set. The site loads, but not the cookies. It must be a configuration issue, but so far nothing worked. Some settings are: DEBUG = True ALLOWED_HOSTS = ['*'] CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False # Only for dev SESSION_COOKIE_SECURE = False # Only for dev Any idea? -
Create a query joining two independent tables, with one Foreign Key in common
I have two Models, one for Intakes of Goods in the warehouse, the other for Output of goods. My available inventory per item is the sum of the intakes minus the sum of the outputs for each item. How can I do that in a query in Django? I have tried using the Django ORM but apparently its only for joining models with dependencies among each other. THIS IS THE MODEL FOR THE OUTPUT OF GOODS. ITS LOCATED IN THE APP, LETS SAY "1" OF MY PROJECT. class OutputPosition(models.Model): created_at = models.DateTimeField(auto_now=True, null=False) output = models.ForeignKey(Output, related_name='outputs', on_delete=models.CASCADE) item = models.ForeignKey(Item, related_name='output_items', help_text='Nombre del artículo', on_delete=models.SET_DEFAULT, default=999999999) quantity = models.SmallIntegerField(null=False, help_text='Ingrese el número de artículos') comments = models.CharField(max_length=256, null=True, help_text='Comentarios') def get_item_name(self): return self.item.name def __str__(self): return str(self.pk)+' '+self.item.name THIS ONE BELOW IS THE MODEL FOR THE INTAKE OF GOODS. IS LOCATED IN ANOTHER APP. class Positions(models.Model): created_at = models.DateTimeField(auto_now=True, null=False) intake = models.ForeignKey(Intake, related_name='intakes', on_delete=models.CASCADE) item = models.ForeignKey(Item, related_name='intake_items', help_text='Nombre del artículo', on_delete=models.SET_DEFAULT, default=999999999) quantity = models.SmallIntegerField(null=False, help_text='Ingrese el número de artículos') comments = models.CharField(max_length=256, null=True, help_text='Comentarios') def get_item_name(self): return self.item.name def __str__(self): return str(self.pk)+' '+self.item.name class Meta: verbose_name_plural = "Positions" I have one view which I want to … -
In Django Web Project, my app is not recognized
I'm new in Python & Django.. Creating a new app using Python 3.6 Django 2.2.7 and for some reason, the url.py which hold the urlpatterns of the project, is not recognizing the urls.py of my new app (ManageMissingBusinesses). Please see below the relevant urls.py (on the project level). urls.py (project level) from django.urls import path, include from app import forms from datetime import datetime import app.forms import app.views urlpatterns = [ path ('ManageMissingBusinesses/',include('ManageMissingBusinesses.urls')) ] The urls.py on the project level is located on level above the ManageMissingBusinesses module/directory. While starting the server, I'm receiving an error on the urlpattern line: path ('ManageMissingBusinesses/',include('ManageMissingBusinesses.urls')) "ModuleNotFoundError:No module named 'ManageMissingBusinesses' Can you explain me what is the issue? -
module 'django.db.models' has no attribute 'OnetoOneField'
I was following a Django tutorial which used models.OnetoOneFiled() in its models.py file. when I tried implementing the same I get his error: AttributeError: module 'django.db.models' has no attribute 'OnetoOneField' I have added this line as some of the previous answers suggested but with no luck. from django.contrib.auth.models import User from django.db import models # Create your models here. class UserProfileInfo(models.Model): user = models.OnetoOneField(User,on_delete=models.CASCADE, primary_key=True,) # additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username if successful, I should be able to migrate -
VSCode pylint is unable to import anything
This was never an issue until today, I've no idea what I have done to do this. So all the import errors are for django implying it is not installed but it is and runs fine, it's just the linting is throwing too many errors to be any use and I don't think just disabling linting is a way forward. Here is an example of one of the errors: { "resource": "/Users/rki23/Documents/Python/pcc_django/project_portal/views.py", "owner": "python", "code": "import-error", "severity": 8, "message": "Unable to import 'django.contrib.auth'", "source": "pylint", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 } All other imports are fine, for example datetime imports fine. As I mentioned my site still runs fine, it's just pylint is not working. All should be running from anaconda virtual environment, but I'm not sure how to show that bit. Here also is my workspace settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.pycodestyleEnabled": false, "python.pythonPath": "/Users/rki23/anaconda3/envs/django_env/bin/python", "sqltools.connections": [ { "database": "******", "dialect": "PostgreSQL", "name": "Development", "password": "**********", "port": 5432, "server": "localhost", "username": "********" } ] } and here is the launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", … -
hi am trying to deploy django poll web app on heroku but i cant get passed this errors i dont know what to do
2019-11-05T11:32:44+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/f43bc705-ff02-49d0-98ca-06da4760a3f8/activity/builds/3b99bc09-b4d0-401d-a62a-9a23fe8b6ec8 please this is the errors -
nginx reverse proxy multiple locations
I am trying the below configuration and nginx is not routing my web request to the right url. I tried multiple suggestions in online, but still getting error. rewrite proxy ~^ End slashes server { listen 80 default_server; listen [::]:80 default_server; server_name $ipaddress; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /flask { proxy_pass http://0.0.0.0:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://0.0.0.0:8001/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } -
Validate ModelForm without checking duplicate
I'm trying to write a view in django which checks if a client exists then it does nothing. If it doesn't exist then I create. This is what the ModelForm looks like: class FacebookLoginForm(ModelForm): class Meta: model = Client fields = ['facebook_id', 'first_name', 'last_name', 'email'] And here is my code: def facebook_login(request): data = json.loads(request.body) form = FacebookLoginForm(data) if form.is_valid(): # do something pass However for some reason when I call is_valid on the form it checks that the passed data doesn't exist in the database (where the model fields are unique). How can I set the ModelForm to just validate the data without checking if it already exists? My ultimate goal is to validate the input of the form and then update/create the database. -
Make default Django orm calls be more sufficient
I have Django 1.6 and simple view class: class CategoryDetailsView(DetailView): model = Category template_name = '/details.html' queryset = Category.objects.available_categories() def dispatch(self, *args, **kwargs): return super(CategoryDetailsView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(CategoryDetailsView, self).get_context_data(**kwargs) context.update({ 'items': ItemCategory.ITEM_CHOICES, 'items_categories': ItemCategory.objects.items_categories(), 'items_actions_count': ItemAction.objects.something_more(), }) return context I would like to enhance performance of the service and I see that get_context_data method call results in plenty of SELECT statements to the same table. Please, suggest me correct entry point for stating tuning django orm in order to minimize queries quantity.