Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Example of jqgrid with python
So I've cloned this https://bitbucket.org/romildo/django-jqgrid-demo.git as I am looking for a working example of jqgrid with django. I've been updating the code (as this seems like it was written for a version 2 of django and I'm workng on 4.1) I'm completely stumped by the lines from jqgrid import JqGrid giving me this error ModuleNotFoundError: No module named 'jqgrid' I cannot find a reference to jqgrid within pip and I cannot install one (jqgrid is not a python package) I understand that jqgrid is a javascript component around jquery but how do I get that to work in Python I have google for django-jqgrid and on youtube. None of the answers provide enough information to get a simple working example up. There seems to be an assumption that everything is installed and I'd like to understand what is required where and how to reference What am I missing? -
Convert SQL Query into Django Query ORM
I have this sql query, I need to use Django ORM format delete from foodies_orderstall as os where os.order = <order-id> and not exists ( select * from foodies_ordermenu as om where om.order_stall = os.id ); -
Converting a complex dictionary list to a dictionary
I would like to convert this dictionary list below into a dictionary data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } ] And I would like to have this result, just the starting brackets that we change to {..} data={ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } } -
ImageField storage options based on settings
I am using django-storages with the Azure backend. I would like to use the local provided Django solution when running locally and the Azure storage when running in production. How would I change this based on the settings? Do I just use an IF statement below these? # local image = models.ImageField(upload_to="profile_pics", blank=True, null=True) # production image = models.ImageField(upload_to="profile_pics", blank=True, null=True, storage=AzureMediaStorage()) -
What's the diffrence bettwen timezone.now and auto_now_add parameters in DateTimeField field in Django models?
I'm writing my first Django app - blog. When creating Post model I'm asked to create publish and created fields with timezone import. publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) It's explained that "By using auto_now_add, the date will be saved automatically when creating an object" and "timezone.now returns the current datetime in a timezone-aware format". So it seems to me that they both same job. Why not use default=timezone.now in both fields? What's the difference? It's my first question so sorry in advance if I made some mistakes. -
PgAdmin Queries fast Django orm very slow
When I write a query via pgAdmin, I get very fast results, but the queries made with Django orm are very heavy, what could be the reason? database connection as below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user', 'USER': 'users', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'data': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'data', 'USER': 'datas', 'PASSWORD': 'toor', 'HOST': '192.168.1.1', 'PORT': '5432', }, } The query I sent with pgAdmin PgAdmin 97 msec SELECT COUNT(id) as noti FROM notification WHERE created_at BETWEEN '2022-11-15 00:00:00' AND '2022-11-15 23:59:59' The query I sent with django Django 20.44 s from django.utils.timezone import get_current_timezone from datetime import datetime get_today = datetime.now(tz=get_current_timezone()) Notification.objects.using('data').filter(created_at__year=get_today.year, created_at__month=get_today.month, created_at__day=get_today.day).count() I'm making multiple database connections with Django the second database is running very heavy query how can I fix this -
solr search returning 3 result but when i it try to iterate object is not working
I have implement solr search and try to run this in a shell when i fetch all record it gave count 3 it's correct but when i try to display title and body it's gave me an error please let me help this solr-9.0 python3 and django 4 for solr > post_text.txt templates/search/indexes/blog/post_text.txt {{ object.title }} {{ object.tags.all|join:", " }} {{ object.body }} in search_indexes.py from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().published.all() Now in shell from haystack.query import SearchQuerySet from blog.models import Post sqs = SearchQuerySet().models(Post).all() sqs.count() # return 3 but when i run this loop then geting error for x in sqs: x.object Traceback (most recent call last): File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2018, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 2, in <module> File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/haystack/models.py", line 81, in _get_object self._object = self.searchindex.read_queryset().get(pk=self.pk) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line 636, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line … -
How to fix IntegrityError 1048 in django
So, i just made a upload feature to insert data into databases. Data inserted successfully into the database but show an error messages Before, i tried to change the column name on my excel .. i thought it was the problem, but after i undo the changes to default .. error still happened. Here's my view code Views.py if 'uploaddatasiswa' in request.POST: dataset = Dataset() new_siswa = request.FILES['uploadSiswa'] if not new_siswa.name.endswith('xlsx'): messages.info(request, 'Format tidak valid!') else: imported_data = dataset.load(new_siswa.read(),format='xlsx') for data in imported_data: tambah_siswa = modelUser( username = data[0], namadepan = data[1], namabelakang = data[2], password = data[3], email = data[4], jeniskelamin = data[5], tanggallahir = data[6], agama = data[7], alamat = data[8], telepon = data[9], role = "siswa" ) tambah_siswa.save() return HttpResponseRedirect("/admin/daftarsiswa") return render(request,'tambahsiswa.html') Models.py class modelUser(models.Model): namadepan = models.CharField(max_length=200, null=False, blank=False) namabelakang = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) email = models.CharField(max_length=200, null=False, blank=False) jeniskelamin = models.CharField(max_length=200, null=False, blank=False) tanggallahir = models.DateField() agama = models.CharField(max_length=200, null=False, blank=False) alamat = models.CharField(max_length=200, null=False, blank=False) telepon = models.CharField(max_length=200, null=False, blank=False) jumlahkelas = models.CharField(max_length=200, null=True, blank=True, default=0) role = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username Tables -
How can I get value from one function in another function in Django, views()
Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): latitude='latitude' longitude='longitude' context = {'latitude':latitude, 'longitude':longitude} my_view(context) return (context) @csrf_exempt @require_http_methods(["POST"]) def my_view(request,context): if request.method == "POST": # value_data=(my_view1(data=request.POST)) value_data=my_view1().objects.all() latitude = request.POST.get(value_data['latitude']) longitude = request.POST.get(value_data['longitude']) # In this example I am reading a file with (time, x, y) as dimensions xarr = xr.open_rasterio('/home/shaheer07/New Rasters/image_factors.tif') # Slice one of the bands img = xarr[0, :, :] #Use the .sel() method to retrieve the value of the nearest cell close to your POI pixel_value = img.sel(x=latitude, y=longitude, method="nearest") image = '/home/shaheer07/New Rasters/image_factors.tif' with rasterio.open(image) as f: # Load metadata meta = f.meta # Use the transform in the metadata and your coordinates rowcol = rasterio.transform.rowcol(meta['transform'], xs=latitude, ys=longitude, zs=None) y = rowcol[0] x = rowcol[1] # Load specific pixel only using a window window = Window(x,y,1,1) raster_values = f.read(window=window) return JsonResponse(pixel_value,raster_values, status=status.HTTP_201_CREATED) else: return JsonResponse('Nothing') -
Django CSRF Protection GraphQL API
I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF attacks as I exempt this protection with csrf_exempt without csrf_exempt it needs a csrf token. Is there a way to ask for a valid csrf token without sending it over the frontend ? The graphql api is only used for the backend for inserting data into the database in which I cant get the csrf token over the frontend. Backend/Frontend: Django Database: Mongo Thanks -
How to include staticfiles in wsgi django project?
Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static files were found. My project in /home/alevt/health_check. I have next structure of project: ---- client -------- manage.py -------- my.ini -------- app ------------ urls.py ------------ settings.py ------------ wsgi.py -------- health_app ------------ urls.py ------------ static --------------- scripts ----------------- myscript.js ------------ templates --------------- index.html settings.py INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'health_app', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') index.html <script src="{% static 'scripts/myscript.js' %}"></script> ERROR Not Found: /static/scripts/create-table.js my.ini [uwsgi] http = 10.107.14.161:8000 module=app.wsgi:application chdir = /home/alevt/health_check/client/ wsgi-file = /home/alevt/health_check/client/app/wsgi.py virtualenv=/home/alevt/health_check/env single-interpreter = true enable-threads = true master = true And my file of service Description=uWSGI instance to serve myproject [Service] ExecStart=/usr/bin/bash -c 'uwsgi --ini /home/alevt/health_check/client/my.ini' KillSignal=SIGQUIT Type=notify [Install] WantedBy=multi-user.target``` -
Multiple CN LDAP integration in Django project
I want to use multiple CN names in LDAP configurations. I tried to use AUTH_LDAP_REQUIRE_GROUP = "CN=GROUP_NAME1,OU=MSG Distribution Groups,DC=XXX,DC=XXX,DC=XXX" How can I allow multiple groups in CN? Thanks in advance. -
it safe to request url in django? [closed]
I need to check if user submitted url really exists. but I found in some sources that it is not safe to send request from django to the site for this. do you have any suggestions django used to have validation for this but then removed it for security reasons I found code samples: but verify_exists is deprecated for security reasons and has been removed in Django 1.5 -
Cannot connect to redis while using Sentinels in django-redis
Currently I am trying to integrate redis into my django project which is docker based. I was able to integrate redis using the DefaultClient but it doesn't work for SentinelClient My settings.py looks like this: DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' SENTINELS = [ ('redis://9b39d2b0eb5d', 26379), ] # 9b39d2b0eb5d is the ip of redis sentinel container CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-queue-1:6379', 'OPTIONS': { 'SENTINELS': SENTINELS, # django_redis.client.SentinelClient 'CLIENT_CLASS': 'django_redis.client.SentinelClient', 'CONNECTION_POOL_CLASS': 'redis.sentinel.SentinelConnectionPool', }, } } It doesn't throw any exception, django just gets stuck on loading -
Django rest framework updating a OneToOne field
I have a User model that inherits from AbstractUser which has an email field. And a profile model that has an OneToOne relation with the User model class User(AbstractUser): email = models.EmailField(unique=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=13, validators=[phone_regex], unique=True, null=True, blank=True) birth_date = models.DateField(blank=True, null=True) about = models.TextField(max_length=2000, blank=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" view.py class ProfileViewSet(ModelViewSet): .... @action(detail=False, methods=["GET", "PUT"], permission_classes=[IsAuthenticated]) def me(self, request, *args, **kwargs): profile = Profile.objects.get(user_id=request.user.id) if request.method == "GET": serializer = ProfileSerializer(profile) return Response(serializer.data) elif request.method == "PUT": serializer = ProfileSerializer(profile, request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): user = CurrentUserSerializer() def update(self, instance, validated_data): user_data = validated_data.pop('user') user_ser = CurrentUserSerializer(instance=instance.user, data=user_data) if user_ser.is_valid(): user_ser.save() instance.phone = validated_data.get('phone', instance.phone) instance.birth_date = validated_data.get('birth_date', instance.birth_date) instance.about = validated_data.get('about', instance.about) instance.save() return instance class Meta: model = Profile fields = [ 'id', 'user', 'phone', 'birth_date', 'about', ] Now when I try to update a user profile I get status: 400 Bad Request error { "user": { "email": [ "user with this email already exists." ] } } using patch instead of put or partial=True doesn't change anything I still get this error. What can I do here? -
Django: Async POST Request
I am trying to make an async post request using the following approach: First of all, I have defined a fixture to return the client: @pytest.fixture(scope="session") async def async_app_client(): async with AsyncClient() as client: yield client Then i use the client to execute the post request. @pytest.mark.asyncio @pytest.mark.django_db() async def test_single_statistic_task_monitoring( async_app_client, statistic_object_univariate ): print(reverse("statistics-list")) response_post = await async_app_client.post( reverse("statistics-list"), statistic_object_univariate, format="json", ) The error i am getting is: AttributeError: 'async_generator' object has no attribute 'post' However, for examples online many use httpx AsyncClient to make the post request. What is the problem here? -
Cannot create a db from scratch after messing with squashmigrations command in django
I tried to run the squashmigrations command in django and after a while I needed to delete the db and start from scratch (the problem also applies when downloading the repository from GitHub and trying to recreate the project). I get the following error when running python manage.py makemigrations or python manage.py migrate error: (venv) meal_plan main python manage.py makemigrations Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: meal_plan_recipe The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 22, in <module> main() File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 443, in execute self.check() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = … -
Django - Using Case to update datefield but no effect?
I am trying to update two fields: # This works, changes the correct field. DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( last_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_high_price'])), default=F('last_high_price') ) ) # Using the same condition to change another field in same row. Does not work? DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( date_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_date_time'])), output_field=DateField(), default=F('date_high_price') ) ) The field date_high_price will not update, I am getting a 200 response. But the field remains null. If I remove output_field then I get >FieldError. -
I have a two Model related to each other and I want to automatically create the data on ModelB upon creating the data in ModelA
I have this User Model Which came from the User of Django Admin class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def __str__(self): return str(self.id) + " " + self.email And I have another model related to this User model called Promoter model class Promoter(models.Model): user = models.ForeignKey( NewUser, on_delete=models.CASCADE, ) def __str__(self): return str(self.user.id) + " " + self.user.email def email(self): return self.user.email And every time I added a data into User I want to Automatically add also a data into the Promoter model with a link to newly created User This is my code in added/registering a new User class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): newuser = serializer.save() if newuser: return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I try to manually add the newly created User into the front end by having a two different API call both for adding User and adding promoter but I'm getting an error in adding a Promoter data manually (1048, "Column 'user_id' cannot be null") I also try … -
Best way to config gunicorn and nginx with django?
I am trying to deploy django with gunicorn and nginx on heroku, and i'm kinda confused with the way to config gunicorn and nginx, when i searched through internet, they usually create gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target but when i go to gunicorn docs : https://docs.gunicorn.org/en/stable/deploy.html. nginx has a config file like this worker_processes 1; user nobody nogroup; # 'user nobody nobody;' for systems with 'nobody' as a group instead error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { include mime.types; # fallback in case we can't determine a type default_type application/octet-stream; access_log /var/log/nginx/access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/tmp/gunicorn.sock fail_timeout=0; # for a TCP configuration # … -
'base_tags' is not a registered tag library. Must be one of:
Hello I get this error for create new custom template tags in django how i can debug my code? it's my template tags: from django import template from ..models import Category register = template.Library() @register.simple_tag def title(): return "any thing" it's my HTML code: {% load base_tags%} <a class="navbar-brand" href="index.html">{% title %}</a> it's my error: 'base_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I run webserver in terminal but for again it's doesn't work true -
How to return queryset based on selected option using AJAX in django?
Here is my view.py : def get_group_ajax(request): if request.method == "GET": g_id = request.GET['group_id'] productlist = models.Stocksupporter.objects.filter(pmaingroups = g_id).values('productname').exclude(numberqut=0) *//This is my queryset* Here is my AJAX and used Django template for loop : $("#allgrp").change(function () { const gId = $('#allgrp').val(); $.ajax({ type: "GET", url: '{% url "webapp:get_group_ajax" %}', data: { 'group_id': gId, }, success: function (data) { html_data = ` {% for pr in productlist %} <div class="cardc" id="card_id"> <p>{{ pr.productname }}</p> </div> {% endfor %} `; $("#card_id2").html(html_data); } }); }); now what is problem: I want return productlist (for loop) in AJAX Success based on selected value (mean group id), i used Response methods but still can not return anything. is there any way for do it? -
CSS not loading on django on different settings environments
I'm using Django as a framework, and I want to hide a column on mobile view with CSS. I use three different settings files: base, dev, and prod. All the main settings are in the base file and the only difference between the dev and prod settings - in what database I'm using (local Postgres and remote Postgres on Railway). I have my base.html file, where I load static files: <head> <meta charset="UTF-8"> <title>{{ title }}</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'main/css/base.css' %}"> <link rel="shortcut icon" type="image/png" href="{% static 'main/img/favicon.ico' %}"/> That's my project structure: I want to hide a column on mobile view, so that's what I have in my base.css: @media only screen and (max-width: 800px) { td:nth-child(1) { display:none; } th:nth-child(1) { display:none; } } However, when I run the app using dev settings - everything works fine. When I run using prod - changes are not displayed. It seems that CSS file is not being read, but I'm wondering why if the code is the same - the difference is only in using different databases on … -
Django complex query with page load slow
I have a quiz application made with Django. I am basically loading a pretty complex query. What I am basically doing is creating a new exam with this logic: Fetch the question from the question bank (the Question model) I get a certain questions number from each subject and I use them to create a QuestionDraft so I can store and save each student result. Each QuestionDraft has the AnswerDraft which I use for storing the user answered questions (each AnswerDraft is basically a carbon copy of the question bank Answer). While I wanna load a 50-question-test everything works pretty fine but when I want to load more than that amount of question, the page is loading extremely slow. I would like to know if, based on the models and the code I post down below, there is any way to improve the efficiency of the queries and/or the loading time. models.py class QuestionSubject(models.Model): quiz_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE) name = models.CharField(max_length=200) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Question(models.Model): id = models.CharField(max_length=7, default=generate_question_id, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = models.TextField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) question_bank_id = models.CharField(max_length=255, blank=True, null=True) question_topic … -
Django: error while using DateRangeFilter on a baseadmin
I trying to create a BaseDateAdmin models to use this package: https://github.com/silentsokolov/django-admin-rangefilter for filtering created objects based on the created date. But when I try to add this base model to another admin model which has some 'list_filter' items I get the following error: __init__() missing 2 required positional arguments: 'model_admin' and 'field_path' from rangefilter.filters import DateRangeFilter class BaseDateAdmin(admin.ModelAdmin): def get_list_filter(self, request): res = list(super().get_list_filter(request)) res.extend('created',DateRangeFilter) return list(set(res)) @admin.register(Example) class ExampleAdmin(BaseDateAdmin): list_filter = ( ('in_paid', 'state'), )