Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python framework will be best for job portal website
Recently we started working on a job portal website as i am not from the technical background please someone guide in what sought of python framework we can use for job portal Moreover it would be really helpful if someone can help me in selecting the whole technology stack. I know Django and Flask are the 2 main options in Django.However, I don't have the clear idea with the whole tech stack for the job posting portal -
How do I fix 'Message' instance needs to have a primary key value before this relationship can be used
When I try to add a Message from the admin pages I get the 'Message' instance needs to have a primary key value before this relationship can be used. Here is my models.py Message class... class Message(models.Model): """ Message as sent through a Submission. """ default_id = time.time() #adding primary key to satisfy error id = models.BigAutoField(primary_key=True, auto_created=True) title = models.CharField(max_length=200, verbose_name=_('title')) slug = models.SlugField(verbose_name=_('slug')) newsletter = models.ForeignKey( Newsletter, verbose_name=_('newsletter'), on_delete=models.CASCADE, default=get_default_newsletter ) date_create = models.DateTimeField( verbose_name=_('created'), auto_now_add=True, editable=False ) date_modify = models.DateTimeField( verbose_name=_('modified'), auto_now=True, editable=False ) class Meta: verbose_name = _('message') verbose_name_plural = _('messages') unique_together = ('slug', 'newsletter') #order_with_respect_to = 'newsletter' def __str__(self): try: return _("%(title)s in %(newsletter)s") % { 'title': self.title, 'newsletter': self.newsletter } except Newsletter.DoesNotExist: logger.warning('No newsletter has been set for this message yet.') return self.title def get_next_article_sortorder(self): """ Get next available sortorder for Article. """ next_order = self.articles.aggregate( models.Max('sortorder') )['sortorder__max'] if next_order: return next_order + 10 else: return 10 @cached_property def _templates(self): """Return a (subject_template, text_template, html_template) tuple.""" return self.newsletter.get_templates('message') @property def subject_template(self): return self._templates[0] @property def text_template(self): return self._templates[1] @property def html_template(self): return self._templates[2] @classmethod def get_default(cls): try: return cls.objects.order_by('-date_create').all()[0] except IndexError: return None and the admin.py module class MessageAdmin(NewsletterAdminLinkMixin, ExtendibleModelAdminMixin, admin.ModelAdmin): logger.critical('MessageAdmin') save_as = … -
django-rq-scheduler not printing information on console window
I am referring to the official documentation from here. Here is my code: Directory Structure: settings.py file app1/jobs.py file Scheduled job in django-admin panel (time is 2 minutes after the current time) Issue I am expecting some log messages on the console (command prompt) after the specified time. But even after waiting for more than the specified time, there are no log messages. -
How to add notification feature in DRF?
I am new to Django. I have a question. How to add notification feature in Django Rest Framework? Like if a user has signed up, it's data should be popped up to frontend of owner as a notification. How to implement it's backend? Do we have to use django channels and web sockets? Why can't we do this with WSGI server which is supported by normal Django applications? e.g. class Employee(models.Model): some fields When object of class Employee is created, it's data should be popped up to frontend of it's owner as notification. -
i use video.js but i can't fast-forward when use on Django framework
i use video.js to play video and i create condition if videoPn( n = 1 to 17 ) = 0 video player hide progressControl and when videoPn = 1 video player show progressControl. my problem is when videoPn = 1 video player show progressControl but it can't fast-forward when i'm click at progressControl video will restart. But I tried to test it without Django. it's no problem var player = videojs("videoP"); function light(Cvideo) { for (let i = 0; i < videos.length; i++) { let video = videos[i]; if (videos[i].id === Cvideo) { //change name and src document.getElementById("nameV").innerHTML = videos[i].name; player.src({ type: "video/mp4", src: videos[i].src }); player.play(); if (!video["videoP" + (i + 1)]) { //hide progressControl player.controlBar.progressControl.hide(); player.on("timeupdate", function() { //percentage var percentage = (player.currentTime() / player.duration()) * 100; //display percentage document.getElementById("percentage").innerHTML = Math.round(percentage) + "%"; if (percentage === 100) { //if percentage = 100 change videoPn when n=i+1 video["videoP" + (i + 1)] = 1; //videoproมี = 1 var videopro = video["videoP" + (i + 1)] = 1; $.ajax({ type: "POST", url: "/update-video-progress/", data: { video_id: videos[i].id, videopro: videopro, }, success: function(response) { console.log("Video progress updated"); }, error: function(xhr, textStatus, errorThrown) { console.error("Failed to update video progress"); }, }); … -
can't get query strings in production mode but in development every thing is fine
i have a django app that should get query string params. and this works fine in my localhost. but when on deployed the app on python linux host , it encountered 500 server error. there isn't any errors in the stdr.log file . my url: path("foo",views.get_foo) my view: get_foo(request): model_foo= TestModel(name = request.GET.get("foo")) model_foo.save() return HttpResponse("done") thanks for helping -
Using Django "through" argument for saving additional information in ManyToMany field
I am trying to create a scenario where I may add an "order" of level (to add the degree of escalation) for the saved instances of a model "ContactPerson" according to some criteria (say seniority or position of responsibility). The form is intended to look someting like this: Contact Person Level Franc Correa 2 Liz Burnett 3 Christian Amarilo 3 Mark Tannit The Level values will be entered at runtime to the (already) created contact persons. (The empty field for the last entry in the above table signifies that a level is not yet assigned.) I have created the following models: class ContactPerson(models.Model): name = models.CharField(max_length=128) designation = models.CharField(max_length=128) class Level(models.Model): level = models.PositiveSmallIntegerField() desig_person = models.ManyToManyField(ContactPerson, through='Order') class Order(models.Model): contact_person = models.ForeignKey(ContactPerson, on_delete=models.CASCADE) level_order = models.ForeignKey(Level, on_delete=models.CASCADE) location = ... Now I create / add persons (in model ContactPerson) and later want to assign "level/degree of escalation" in model "Order" in field level_order at runtime. To that end I am using the following model form and assigning to an inlineformset_factory: class AssignEscalationLevelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AssignEscalationLevelForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = Order fields = ('contact_person', 'level_order', 'location') As already stated above, I want to … -
Fixing a NoReverseMatch in a Django Project for Registration
Hi I keep getting NoReverseMatch at /users/register/ however I am have followed the step by step for fixing this error: Here is the urls.py app_name = 'tac' urlpatterns = [ path('terms-and-conditions/', TermsAndConditionsView.as_view(), namespace='terms_and_conditions'), path('user-agreement/', UserAgreementView.as_view(), namespace='user_agreement'), ] Here is the register.html that is causing the error: <label class="form-check-label" for="terms_and_conditions">I agree to the <a href="{% url 'tac:terms_and_conditions' %}">terms and conditions</a> </label> Here is the traceback error: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Project\users\views.py", line 34, in register return render(request, 'users/register.html', {'form': form}) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 175, in render return self._render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 167, in _render return self.nodelist.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\defaulttags.py", line 472, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 82, in reverse raise NoReverseMatch("%s is not … -
RuntimeError: Model class django_celery_beat.models.SolarSchedule doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm using my virtualenv and upon executing celery -A app beat -l info -S django, this error always displays. RuntimeError: Model class django_celery_beat.models.SolarSchedule doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. N.B: django_celery_beat already installed and migrated. I have used the following versions, like Python Version: 3.8 Celery Version: 5.1.1 Celery-Beat Version: 2.2.1 But my expectation is to run celery smoothly :) -
How to change url params (query_string) in django rest framework before handle request?
Because I need compatible with old client. For example, when I recevie an request http://0.0.0.0:8000/api/exercises/?pk=13, i want change the params so http://0.0.0.0:8000/api/exercises/?id=13. Others: http://0.0.0.0:8000/api/exercises/?displayName=ABC change to http://0.0.0.0:8000/api/exercises/?display_name=ABC http://0.0.0.0:8000/api/exercises/?target=1,2 change to http://0.0.0.0:8000/api/exercises/?target=1&target=2 Is there any place I can write code before handle the request? Thanks. -
How to display a form error on invalid password input in django?
I have a login form that can display a error message on invalid username input, but I am having trouble figuring out how to display an error on a invalid password input. The invalid username error I want to be able to display an error like this for the password when the user inputs a correct username but incorrect password. forms.py from django import forms from django.contrib.auth.hashers import make_password, check_password from django.contrib.auth.forms import AuthenticationForm from .models import User class LoginForm(AuthenticationForm): username = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username', 'required': True})) password = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password', 'required': True})) def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username) if not user: raise forms.ValidationError('Incorrect username') return username def clean_password(self): # This is the part I need help with # NOTE This code does nothing, just used to # display the functionality I want to implement password = self.cleaned_data['password'] if not check_password(password): raise forms.ValidationError('Incorrect password') return password views.py from django.contrib.auth.views import LoginView from .forms import LoginForm class LoginUserView(LoginView): template_name = 'login.html' authentication_form = LoginForm login.html {% extends 'base.html' %} {% block title%} Login {% endblock title %} {% block content %} </div> <form method="post"> {% csrf_token %} <div class="mb-4"> <p class="text-danger"> {{ form.username.errors.as_text }} … -
Exception Value: ['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.']
I'm trying to save theAttendance mode, but I'm getting an error. I can't figureout what it is. Error is ['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.'] Here is my models.py from django.db import models from employee.models import Employee # Create your models here. class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) date = models.DateField() day = models.CharField(max_length=10) in_time = models.CharField(max_length=5) out_time = models.CharField(max_length=5) Here is my views.py from django.shortcuts import render,redirect from django.views.generic import View from django.http import JsonResponse from employee.models import Employee from .models import Attendance # Create your views here. class MarkAttendanceMainView(View): def get(self,request): return render(request,"mark_attendance.html") def post(self,request): attendance_time_in = [] attendance_time_out = [] attendance_date = [] attendance_day = [] emp_id = request.POST['attendance_emp_id'] emp = Employee.objects.filter(emp_id=emp_id) for id in request.POST: if "in" in id.split("_"): attendance_time_in.append(id) elif "out" in id.split("_"): attendance_time_out.append(id) elif "date" in id.split("_"): attendance_date.append(id) elif "day" in id.split("_"): attendance_day.append(id) i = 0 while i < len(attendance_time_in): date = request.POST[attendance_date[i]] day = request.POST[attendance_day[i]] time_in = request.POST[attendance_time_in[i]] time_out = request.POST[attendance_time_out[i]] i +=1 print(emp, date, day, time_in, time_out) attendance = Attendance(emp,date,day,time_in,time_out) attendance.save() return redirect('mark_attendance_main_view') -
Form attributes duplicating in '.controls' div when using CheckboxSelectMultiple widget with Crispy Forms
I have a form that's meant to filter results in a list view. I'm using HTMX to submit a GET request whenever the form changes, and I'm using Crispy Forms to render the form (including the hx attributes on the <form> tag). I've used this pattern multiple times before with no issues, but on this particular form I want to use the CheckboxSelectMultiple widget. When the form is rendered, the hx attributes that I'm applying to the <form> tag are getting duplicated on the <div class="controls"> tag that holds the checkboxes. Form class MyListFilterForm(forms.Form): status = forms.MultipleChoiceField(choices=MyModel.STATUS_CHOICES, required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'GET' self.helper.disable_csrf = True self.helper.attrs = { 'hx_get': reverse('myapp:my_view'), 'hx_trigger': 'change', 'hx_target': '#my_table_body', } Rendered HTML <form hx-get="/path/to/view/" hx-target="#my_table_body" hx-trigger="change" method="get"> <div id="div_id_status" class="control-group"> <label for="" class="control-label "> Status </label> <div class="controls" hx-get="/path/to/view/" hx-target="#my_table_body" hx-trigger="change"> <label class="checkbox" for="id_status_0"><input type="checkbox" name="status" id="id_status_0" value="1">Choice 1</label> <label class="checkbox" for="id_status_1"><input type="checkbox" name="status" id="id_status_1" value="2">Choice 2</label> <label class="checkbox" for="id_status_2"><input type="checkbox" name="status" id="id_status_2" value="3">Choice 3</label> </div> </div> </form> This duplication of the hx attributes is causing the HTMX request to fire twice whenever one of these checkboxes is clicked. Not only that, but the first request … -
Fixing date & time format in HTML
Context of Question Hi all, I'm building a Twitter clone. I'm using JavaScript to create & insert a new Tweet into the news feed. After inserting the new Tweet into the news feed, I noticed the date & time format is different after refreshing the page. Examples below for reference: Tweet after inserting into news feed & before refreshing the page Tweet after refreshing the page The Tweet in JSON format looks like this { "id": 56, "user": "admin", "content": "yes", "date": "Feb 07 2023, 12:26 AM", "likes": 0 } I'm using Django as the backend & the how a Tweet gets serialized is as follows: def serialize(self): return { "id": self.id, "user": self.user.username, "content": self.content, "date": self.date.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } Now, I'm not sure what's causing this mismatch of date & time format: the serializer for the Tweet, or how HTML handles the date & time format -
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (when I try to run "python manage.py runserver")
I installed PostGIS 3.3. That PostGIS 3.3.2 bundle includes PostGIS 3.3.2 w, GDAL 3.4.3 (SQLite 3.30.1, OpenJPEG 2.4.0, Expat 2.4.8, FreeXL 1.0.6), GEOS 3.11.1, Proj 7.2.1, pgRouting 3.4.2, osm2pgrouting 2.3.8, ogr_fdw 1.1.3 spatial foreign data wrapper extension, and pgPointcloud 1.2.4, h3-pg 4.0.3. But when I try to run GeoDjango app, then it stopped with the following error. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal304", "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. My system variables show GDAL installed and path set already. I am trying to setup correctly geodjango with gdal, So kindly expecting help to solve this matter. -
Why is my django session not persisting? It works when I use Postman but not when I try through my Frontend
I'm currently working on a registration component for an application built using React with TypeScript and Tailwind CSS, Django and MongoDB. In my Django backend I have an app called login_register_app, which is used for registration functionality. I want to create a session that stores the id of the document when the document is created so that when the user is asked to add further details on the following page the correct document can be updated. So far, I have the following function for registration: @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at least one uppercase, lowercase, digit and special character [#?!@$%^&*-]' else: error = 'passwords do not match' # verify email does not already exist … -
How do i get selected value from select option from my template? Django
views.py: def add(request): categories = Category.objects.all() current_user = request.user owner = current_user if request.method == "POST": isActive = True img = "ASS" title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] category = request.POST["categories_n"] f = Listing(title,description, img, price, isActive=True, owner = owner, category) f.save() context = {'owner': owner, "categories":categories} return render(request, "auctions/add.html", context) template: {% block body %} <div class ="main"> <form action = "{% url 'add' %}" method = "POST"> {% csrf_token %} <h3>Owner of the item: <strong>{{owner}}</strong></h3> <ul class = "u_list"> <li class = "l_item"><label for = "t">Title:</label> <input type = "text" name = "title" id = "t" placeholder = "Item's name"></li> <li class = "l_item"><label for = "d">Description: </label><input type = "text", name = "description" id = "d" placeholder = "Details about the item"></li> <li class = "l_item"><label for = "p">Price: </label> <input type = "price" name = "price" id = "p" placeholder = "Item's price"></li> <select name = "categories_n" id = "c"> {% for option in categories %} <option value = "{{option.id}}" {% if categories_n == option.name %} selected = "selected"{% endif %}> {{option}} </option> {% endfor %} </select> <input type = "submit" value = "Submit"> </ul> </form> </div> {% endblock body %} How do … -
Django Heroku deploy error "connection to server at "127.0.0.1", port 5432 failed: Connection refused"
I am trying to re-deploy my Python Django App on Heroku after the free dyno canceled. However, I got OperationalError at /catalog/ in Heroku: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /app/.heroku/python/lib/python3.10/site-packages/psycopg2/__init__.py, line 122, in connect I ran the App locally without any issue, and I used this as a reference but not solving my problem. I tried several changes in my settings.py: ALLOWED_HOSTS = ['.herokuapp.com','127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'somename', 'USER': 'someuser', 'PASSWORD': 'somepassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I personally believe the error was caused by those code above, and I had changed PORT to "8000", or used DATABASES['default'] = dj_database_url.config(), or set ENGINE to 'django.db.backends.postgresql', but those attempts were not working neither. Since it rans without error locally, so I am wondering what caused the Operational Error appeared? I would sincerely appreciate all the help since this issue bothered me for few days. -
linking django to web hosting site
I have created a webpage using Django and am looking to link it to my purchased domain name through domain.com. Domain.com tutorials have been worthless and they offer web hosting but I am not sure how to link my local Django project. Does it have to do with the SSL Certificate? Feel free to explain it to me like I am a 5 year old. I tried including the domain and ip of the purchased domain in the ALLOWED_HOSTS=[] but obviously that doesn't work without some communication between domain.com and Django. -
Django Rest Framework - How to use url parameters in API requests to exclude fields in response
Let's say I have an API that returns some simple list of objects at the /users endpoint { "count": 42, "results": [ { "name": "David", "age": 30, "job": "Baker", "location": "Alaska", "sex": "male", }, ... ] } I would like to pass a simple boolean that changes the output by removing certain fields. So /users?abridged=True would return the same objects, but omit a few fields. { "count": 42, "results": [ { "name": "David", "age": 30, }, ... ] } I suppose I could create two serializers, one for the full version and one abridged, but I'm not sure how I could use a url parameter to select which serializer to use. Is there a better way to do this? -
Converting fields inside a Serializer in django
I have a project where one model, called Request, has two fields (source, dest) that contain two ids which are not known to the user. However, each one is connected to another model User, who let's say that they have one field, username, which is known to the user. Now, I want to make a serializer that can take usernames, and convert them into ids. (The opposite was simple to achieve, I just modified the to_representation method.) The problem is that when I send {'source': 'john', 'dest': 'jim'} the serializer does not take these data as valid. This was expected behavior, as it expected ids and got strings (usernames). However, even when I overridden the validate_source, validate_dest and validate methods to actually check that the usernames exist (instead of the ids), I am still getting errors that the serializer expected id but got string. Are the validate, validate_<field> methods the wrong ones to override in this case? Should I just convert the usernames into ids inside my view? is it pythonic and good practice, django-wise, to receive some fields from the user and change them inside the serializer (as I change username into id)? Thank you. -
django query left join, sum and group by
I have a model: class Product(models.Model): name = models.CharField(max_length=100) class Sales(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='products') date = models.DateTimeField(null=True) price = models.FloatField() How do I return data as the following sql query (annotate sales with product name, group by product, day and month, and calculate sum of sales): select p.name , extract(day from date) as day , extract(month from date) as month , sum(s.price) from timetracker.main_sales s left join timetracker.main_product p on p.id = s.product_id_id group by month, day, p.name; Thanks, If only ORM was as simple as sql... Spent several hours trying to figuring it out... PS. Why when executing Sales.objects.raw(sql) with sql query above I get "Raw query must include the primary key" -
How to pass dynamic filtering options in django_filters form instead of all model objects?
I have the following structure of the project (models): Company (based on Groups) <-- Products (foreignKey to Company) <-- Reviews (foreignKey to Products). Inside template i want to give a user an opportunity to filter reviews by products, but when using django_filters it shows corrects queryset of reviews (related only to company's products) but in filter form dropdown options i can see all products of all companies (even those which are not presented on the page), for example for Company X i see on my page only Cactus and Dakimakura reviews, but in filter form i can select Sausage (but i shouldnt, because its product from another company). For now it's all looks like this: #View def reviewsView(request): context = {} user = request.user company = user.company products_qset = ProductModel.objects.filter(company=company) reviews_objects = ReviewModel.objects.filter(product__in=products_qset) filter = ReviewFilter(request.GET, queryset=reviews_objects) context['filter'] = filter return render(request, 'companies/reviews.html', context) #Filter class ReviewFilter(django_filters.FilterSet): class Meta: model = ReviewModel fields = [ 'product', 'marketplace', 'operator', 'state' ] #Template <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" name="press me" id=""> </form> <div class="review-list"> {% for i in filter %} {{i.product}}, {{i.marketplace}} etc. {% endfor %} I've done quite a lot of research on django_filters docs and this question … -
Cannot make a migration in Django project to compose up docker file
I have a Django project that uses old version of django.db.models.signals - post_syncdb. I changed models and added new to the db. To make docker-compose up and launch Django with docker I need to make a migration, but when I'm doing this it shows me this error `AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' I tried google the solution and noticed three ways: Check the Django version used in the project, as the post_syncdb signal has been deprecated since Django 1.9. Look through the project's code and identify any references to post_syncdb signal. If there are any, you may have to update the code to use a different signal. If the error persists, it may be a bug in one of the installed packages. You can try to update the packages to the latest version or raise an issue on the package's repository. The problem is that it's not mu project and I currently work on dev branch. How do I fix it and make a migration? -
How to optimizing database queries
How can I optimize an API, starting with optimizing database queries? Step 1: Model.objects.filter(is_disabled=0) Step 2: Index the database Step 3: Use pagination: Model.objects.filter(is_disabled=0)[offset:offset+10], where offset depends on the page number. Step 4: Consider using Redis to save data. Which Redis method should I use? I feel that a sorted set is fast, but it only stores integers and strings. If I want to save a dictionary, I need to use another Redis method. I'm also facing an issue with the Redis key if add data in redis for (Model.objects.filter(is_disabled=0)[offset:offset+10]) then key should be redis_key=”key”+str(page_number)), as deleting data would affect all page numbers. How can I handle Redis keys with page numbers? is it Good or bad to use redis for every 10 rows?