Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i deploy nuxt app to django server
I wonder If there is any way to deploy a nuxt js app on a django server Is there any way like a template engine or similar solutions for doing this ? To be exact and short I want to use only one server for my website -
Celery / Celery beat stuck on old version of a script
I've got a django application running on AWS EC2 using Celery for periodic updates. I recently had to update a data processing script on the Django app, but no matter what I seem to try, Celery continues to use old copies of the processing script. Here's a run down: There was a change in how the data was published starting April 12. So the old processor stopped working on any data after April 12. I amended the script to work on all the data both up to and after April 12 and merged the changes to production. GitHub Actions ran successfully, built the containers, and deployed them to EC2. If I ssh into the EC2 instance and enter the container, I can run the manage.py update_nameofmydatamodel command and it runs properly and updates all of the data properly (I can tell because this feeds a website viz that then properly updates) When Celery Beat runs overnight, the data reverts to processing ONLY up to April 12 (I can tell because I go to the website viz and it has reverted back to only having data up to April 12) I removed the data model from the list of models to … -
createsuperuser works, but createuser does not
When i try to create a new user using my api, Django is not executing the create_user function and password is not hashed. When i createsuperuser in the terminal user password is hashed and create_superuser is executed(its using the previous create_user func). Could you please help? Thank you. class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password): """Create a new user profile""" if not email: raise ValueError('Users must have an email adress!') email = self.normalize_email(email) user = self.model(email=email, name=name) import pdb;pdb.set_trace() user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given credentials""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user -
What is the difference between "database backend" and "database bindings" in Python?
The Django tutorial over at djangoproject.com uses both terms, databse backend, and database bindings. What is the difference? Judging by semantics, I would've guessed a database "backend" to be some reside-on-the-server thing .., and "bindings" to denote configuations..? For example, which does cx_Oracle identify with? -
Forbidden: /api/v1.0/user/create-user/ & { "detail": "Authentication credentials were not provided." } DJANGO
I was creating Login functionality for my Python Django backend, "create user" functionality was working fine before. But then after Login was entirely coded, the create-user stopped working. My urls.py file: from django.urls import path from .views import TestView, UserView, UserLoginView from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token urlpatterns = [ path('test', TestView.as_view()), path('create-user/', UserView.as_view()), path('get-user', UserLoginView.as_view()), path('login-user/', UserLoginView.as_view()), ] My views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer from django.contrib.auth.models import User from django.contrib.auth import authenticate class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("Creating User") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_serializer.data}, status=200) return Response({'msg': "error: no user created"}, status=400) class UserLoginView(APIView): # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) def post(self, request, format=None): print("Login class") # Looking for user's email or username user_obj = User.objects.filter(email=request.data['email']).first( ) or User.objects.filter(username=request.data['username']).first() # if user is valid, returns user data in credentials if user_obj is not None: credentials = { 'username': user_obj.username, 'password': request.data['password'] } user = authenticate(**credentials) … -
DRF to select only some values from ForeignKey - Django
I am using Django Rest Framework and I am new to DRF. serializer.py class ResponseSerializer(serializers.ModelSerializer): class Meta: model = Response fields = [ 'user_id', 'question_id', ] As you can see I have 2 fields here user_id question_id Both of them are foreign key fields When someone hits this url http://127.0.0.1:8000/api/response/add/, they can see all the values when they select user_id or question_id. urls.py path('api/response/add/', views.response_create_view), And this is my views.py class ResponseCreateAPIView(generics.CreateAPIView): serializer_class = ResponseSerializer authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] response_create_view = ResponseCreateAPIView.as_view() What I want is user_id should only have 1 value in list and that is current user. question_id should have only those questions which I have filtered For instance, I only want these questions only queryset = Question.objects.filter(publish=True) Whats the best way I can achieve this? Thanks in advance !! Django Version: 3.2.12 -
Django Materialize Multiple Dropdowns
This might be pretty extensive - so any help is greatly appreciated. Similar: Materialize CSS (with django) dropdown form not working How to Implement 3-way Dependent/Chained Dropdown List with Django? I am working on a project involving dependent drop down menus following this django tutorial. Only difference is I am working with materialize css/js. The problem is that the drop-downs are not populating, and populate only after I post the form - Pre-"post", and Post-"post". When I do not initiate materialize - the form works. Materialize css/js is still a need though as it maintains consistency between my other pages. Even after I have initialized the 'select' after the materialize js was loaded: (Materialize docs here) HTMLs Base.html <head> {% load static %} <!-- Prism CSS --> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> <!-- Compiled and minified JavaScript --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script> {% comment %} $(document).ready(function(){ $('select').formSelect(); }); {% endcomment %} document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instances = M.FormSelect.init(elems); }); </script> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="{% static "main/css/materialize.css" %}"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="nav-wrapper" <ul id="nav-mobile" class="right hide-on-med-and-down"> {% include 'main/includes/navbar.html' %} </ul> </div> </nav> {% include 'main/includes/messages.html' … -
cannot migrate from Django sqlite3 to postgres, getting "psycopg2.errors.UndefinedTable: relation doest not exist" error
I am trying to migrate the sqlite3 db from my Django app to postgres db. I have tried all the tutorials out there but cant seem to solve this error when I try to run 'python manage.py migrate --run-syncdb' or 'python manage.py migrate'. I have installed psycopg2 as well. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } The error is "psycopg2.errors.UndefinedTable: relation "users_postcategory" does not exist LINE 1: ...ategory"."name", "users_postcategory"."name" FROM "users_pos..." screenshot1 screenshot2 -
(Django/Python) Error while deploying "chrnorm/deployment-action"
On GitHub I am trying to deploy a project to Herokuapp and I got this error during the "Create GitHub Deployment" stage of Deployment: Run chrnorm/deployment-action@releases/v1 with: initial_status: success token: *** target_url: https://***.herokuapp.com environment: production env: HEROKU_API_KEY: *** HEROKU_APP_NAME: *** Error: HttpError: Resource not accessible by integration Error: Resource not accessible by integration Here are the requirements.txt coverage>=5.3,<6.0 dj-database-url>=0.5.0 Django>=3.1.0,<4.0.0 gunicorn>=20.0.0,<21.0.0 psycopg2-binary>=2.8.0,<3.0.0 selenium>=3.141.0,<4.0.0 whitenoise>=5.2.0,<6.0.0 Can anyone please tell me what's wrong? Thank youuu -
Python Flask Caching 401 POST and Applying to next request
I have a Python flask backend that returns JSON. Every time I make a POST request that returns a 401 (because tokens have expired) it then prepends the JSON body data to the next request, which causes a 405 method not allowed because as you can see, the data is showing where the method should be. This is the same issue as this post for Django This is the log from my local: 127.0.0.1 - - [25/May/2022 08:17:01] "POST /stsatellites/filter HTTP/1.1" 401 - 127.0.0.1 - - [25/May/2022 08:17:29] "OPTIONS /auth/login HTTP/1.1" 200 - 127.0.0.1 - - [25/May/2022 08:17:29] "{"filters":[{"field":"NORAD_CAT_ID","op":"eq","value":25165}]}POST /auth/login HTTP/1.1" 405 - Here are screenshots of the requests, as you can see that filter data originated on the first request which got the 401 response. Filter POST Filter POST Payload Following Login request: Login POST Headers Login POST Payload We have a workaround in place which resolves this issue but it's a band-aid that I would like to remove. For some reason the request.get_data method fixes the caching issue. @app.after_request def after_request_func(response): if response.status == "401 UNAUTHORIZED": request.get_data(cache=False) return response -
AttributeError: type object 'FieldFile' has no attribute 'field'
This is the validation I'm using in views.py if form.is_valid(): FieldFile.save(self=FieldFile, name=file, content=file, save=True) return HttpResponse('Success') Here's forms.py class UploadFile(forms.Form): file = forms.FileField() And models.py grid_fs_storage = GridFSStorage(collection='images', base_url=''.join([settings.MEDIA_ROOT, 'images/'])) grid_fs_storage_video = GridFSStorage(collection='videos', base_url=''.join([settings.MEDIA_ROOT, 'videos/'])) # Create your models here. class Uploads(models.Model): uploaded_file = models.FileField(null=True, blank=True, upload_to='images', storage=grid_fs_storage) uploaded_video = models.FileField(null=True, blank=True, upload_to='videos', storage=grid_fs_storage) What am I missing here? -
Django Multi Combination Model Joins
Currently experiencing a problem where my models aren't joining on the foreign key properly, Doctors can only have one toolset, essentially I need to return [DoctorName, Category, Type, Subtype, Syringe, Bandage] ToolSetCategoryID, ToolSetTypeID, ToolSetSubTypeID all join on each other's respective tables and all join back to ToolSets an example of the models would be: class Doctor(models.Model): DoctorID = models.AutoField(db_column='DoctorID', primary_key=True) ToolSetID = models.ForeignKey("ToolSets", db_column='ToolSetID', on_delete=models.CASCADE) DoctorName = models.CharField(db_column='DoctorName', max_length=100) class Meta: managed = False db_table = 'tblDoctors' default_permissions = ['add','edit','delete'] class ToolSetCategories(models.Model): ToolSetCategoryID = models.AutoField(db_column='ToolSetCategoryID', primary_key=True) Category = models.CharField(db_column='Category', max_length=100) class Meta: managed = False db_table = 'tblToolSetCategories' default_permissions = ['add','edit','delete'] class ToolSetTypes(models.Model): ToolSetTypeID = models.AutoField(db_column='ToolSetTypeID', primary_key=True) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) Type = models.CharField(db_column='Type', max_length=100) class Meta: managed = False db_table = 'tblToolSetTypes' default_permissions = ['add','edit','delete'] class ToolSetSubTypes(models.Model): ToolSetSubTypeID = models.AutoField(db_column='ToolSetSubTypeID', primary_key=True) ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) SubType = models.CharField(db_column='SubType', max_length=100) class Meta: managed = False db_table = 'tblToolSetSubTypes' default_permissions = ['add','edit','delete'] class ToolSets(models.Model): ToolSetID = models.AutoField(db_column='ToolSetID', primary_key=True) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE) ToolSetSubTypeID = models.ForeignKey("ToolSetSubTypes",db_column='ToolSetSubTypeID',on_delete=models.CASCADE) Syringe = models.CharField(db_column='Syringe', max_length=100) Bandage = models.CharField(db_column='Bandage', max_length=100) class Meta: managed = False db_table = 'tblToolSets' default_permissions = ['add','edit','delete'] -
Django dev server does not automatically reload after saving files
I tested Django 3 a few months ago, and it all worked well. The browser refreshed itself after I made a change to files (.html and .py). Now I have an issue with a newly created Django project, the browser doesn't automatically reload after I saved a change that I made on my local machine. OS: Windows 11 Editor: PyCharm / VS Code Django 4.0.4 Python 3.10.4 Directory structure project/ ├── project/ │ ├── ... │ ├── settings.py │ ├── urls.py │ └── ... ├── first_app/ │ ├── ... │ ├── urls.py │ ├── views.y │ └── ... ├── templates/ │ └── first_app/ │ └── index_view.html └── manage.py Default settings.py file with .... INSTALLED_APPS = [ ... 'first_app', ... ] 'DIRS': [BASE_DIR / 'templates'] .... project/urls.py .... urlpatterns = [ path('', include('first_app.urls') ] .... first_app/views.py .... class IndexView(generic.TemplateView): template_name = 'first_app/index_view.html' ... first_app/urls.py .... urlpatterns = [ path('', views.IndexView.as_view(), name='index') ] .... templates/first_app/index_view.html .... <p> Test paragraph 1 </p> .... I run the server locally with py manage.py runserver When I change 'paragraph' to 'example' in index_view.html and save it, it is supposed to automatically refresh the browser and display Test example 1. But the browser doesn't reload. I have … -
Google maps doesn't zoom on polyline in modal with django
I have page that contains information about clients. In this page a have a button that open a modal with some specific information and another button that open another modal that contains google map. In this map I draw a polyline and I want to zoom in this polyline. When the button to open the modal with the map is clicked, I get information about the polyline with ajax and load the map. The this modal is open in the web page it has no zoom. Here is my code: HTML definition of modal: <!-- Div class to show path map with modal --> <div class="modal fade" id="modalPath" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered" id="modal-path-type"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Tratte</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="modal-body-for-path"> <div class="container shadow-lg p-3 mb-5 bg-body rounded-3 border border-secondary" id="map" style="width: 100%; height: 400px;"></div> <div id="map"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#modalPathsList" id="go_back">Indietro</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> Here javascript code to get data with ajax and load the map: function get_and_show_route(path_id, pilot_id){ const modal_body = document.getElementById('modal-body-for-path'); $.ajax({ type: 'GET', // Request's type url: '/modal-path-info/' + path_id, // Request's url … -
How to authenticate Django URLs using bearer token generated by Angular Azure AD?
I have a situation, currently, my application is built using Django and Angular for UI and Backend. In Angular UI I'm using Azure AD for user login to access the application, then it generates the bearer token. I have written all the APIs in Django which are unprotected/less secured Now my question is how can I use the "Bearer token" which got generated by Angular UI for all the Django API calls or Django URLs? How can I validate the Django URLs using Azure AD??? -
[Pyinstaller][Django] Overwrite file in third-party libraries only for exe
I need to overwrite third-party library to working with pyinstaller. I need this only for compile my django project to working as exe on windows so i don't wanna overwite all packages in my project, just change this one file for compilation purpose. In coreschema witch use one of the package required for django i need to change (path _MEIPASS witch is use for pyinstaller) : loader = jinja2.PackageLoader('coreschema', 'templates') to if getattr(sys, 'frozen', False): # we are running in a bundle bundle_dir = sys._MEIPASS loader = jinja2.FileSystemLoader(bundle_dir) else: loader = jinja2.PackageLoader('coreschema', 'templates') env = jinja2.Environment(loader=loader) How to do this ? -
Project django files(or path) in frontend
I have a model Flights : class Flights(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=timezone.now()) nir = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) red = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) rededge = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) green = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) which have a lot of Filefields. Im trying to print all the flights in a datatable and i have no idea how to implement something like that for so many files. I tried : <tbody> {% for flight in flights%} <tr> <td>{{flight.datetime}}</td> {% for file in request.FILES%} <th>{{flight.request.FILES.name}} </th> {% endfor %} <td><button type="button" class="stressbtn btn btn-danger"</td> </tr> {% endfor %} </tbody> but it doesnt work . I can access the files when im POSTing them in the db, but now i want to retrieve them so i can put them in the datatable,either just the path or the whole image . -
Django Rest Framework app security preparation for production
Intro I've built a web application with multiple services: frontend (react) backend (API and admin panel) (Django Rest Framework + simple jwt auth) Redis, DB, Nginx and etc Kubernetes cluster The app isn't small like 60k+ lines of code. It's a startup. I mentioned it to let you know that probably I wouldn't have that much attention from hackers or traffic at all. Hence I have a space to improve gradually. The auth is done with DRF simple jwt library. Expiring Access + Refresh token. Problem statement I did a security audit and found imperfections from the security architecture perspective. I don't know how those issues are crucial, how should I fix them, or what issues can be fixed later. So I'm seeking solutions and advice. I would prefer an optimal proportion between the speed and quality rather than quality only (If I miss about that let me know) hence if something is "nice to have" rather than "important" I would put it to the backlog of next releases. The actual list of issues Let's refer by its number if you want to. #1 Authentication methods My current setup: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', … -
Django - Datatable multiple models with json format
I'm able to use datatable with one class model by getting json data. https://datatables.net/ However, I would like to add another class with foreign key to models.py. Something like this: class AnotherModel(models.Model): description = models.CharField(max_length=256) ibvs = models.ForeignKey(Ibv, on_delete=models.CASCADE) How I can arrange json get_data function and ajax? And, I am super confused about json file format & how to pass AnotherModel values to the table.(I'd like to show all models in one table) MODELS.PY class Ibv(models.Model): MUESTRAS = ( ('cDNA', 'cDNA'), ('RNA', 'RNA'), ) # id = models.IntegerField(primary_key=True) code = models.CharField(max_length=256) muestra = models.CharField(max_length=256, null=True, choices=MUESTRAS) ship = models.CharField(max_length=256) num = models.CharField(max_length=256) enc = models.CharField(max_length=256) obv = models.CharField(max_length=256) result = models.TextField() created_at = models.DateField(auto_now=True) def __str__(self): return self.result # json def get_data(self): return { 'id': self.id, 'code': self.code, 'muestra': self.muestra, 'ship': self.ship, 'num': self.num, 'enc': self.enc, 'obv': self.obv, 'result': self.result, 'created_at': self.created_at, } VIEWS.PY def ibv_json(request): ibvs = Ibv.objects.all() data = [ibv.get_data() for ibv in ibvs] response = {'data': data} return JsonResponse(response) BASE.HTML var table = $('#example').DataTable({ // json to fill the table rows and columns "ajax": { url: "/json", type: "GET" }, "columns": [ {"data": "id"}, {"data": "code"}, {"data": "muestra"}, {"data": "ship"}, {"data": "num"}, {"data": "enc"}, {"data": "obv"}, … -
How to insert data in child table from react to django rest framework models
I'm new to React and Django rest framework. I want to insert profile data into the Django model using fetch API in react. I'm continuously getting response header as: {"user":["Incorrect type. Expected pk value, received str."]} I've checked by printing response on console, and it gives status code '200 OK'. But it didn't update the database as well. My submit form function in react is: const handleSubmit = (e) => { e.preventDefault(); const profile = profileObj(selectedProfileImg, contact, city, country, address); localStorage.setItem('profile', JSON.stringify(profile)) let form_data = new FormData() // ************************* // this is the foreign key in the model and it gives the problem. // ************************* form_data.append('user',JSON.parse(localStorage.getItem('data')).id) // (foriegn key value) User added by signing up form_data.append('profile_img', profile.prof_img) form_data.append('contact',profile.contact) form_data.append('city',profile.city) form_data.append('country',profile.country) form_data.append('address',profile.address) form_data.append('store_title','storename') // (foriegn key value) Data with this key exists in database form_data.append('cus_status',profile.cus_status) // ********************************* // Also I want to know what the boundary means in content // type. As I see it on google so I used it but removing it // gives another boundary error. // ********************************* fetch('http://localhost:8000/customer_apis/addCustomer/', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' }, body: form_data }) .then(res => { console.log(res) console.log(res.status) if (res.status !== 200) document.getElementById('text-error').innerHTML = res.statusText else { navigate('/create_store') } }) … -
Uploading images with HTMX in django
I am trying to implement image adding functionality through HTMX. Adding the photo is no problem. However, once the photo is added in the view, the image link does not show up. It looks like no photo has been added but when I hit the refresh button, the link is being displayed. What I am trying to achieve is that, once the photo is uploaded and the form is saved, I want the link to show up to confirm for the user that their photo is uploaded. This is my form template <form action='' method="POST" class="form" hx-post='' hx-swap='outerHTML' enctype="multipart/form-data" hx-post="{{request.path}}" hx-encoding="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{field}} </div> {% endfor %} <div class='htmx-indicator'>Loading...</div> <div class="text-center"> <button class='htmx-inverted-indicator' style='margin-top:10px;' type='submit' >Save</button> </div> {% if message %} <p>{{ message }}</p> {% endif %} </form> I am then including this template in the update template. Is there anyway to get the wished result without using JavaScript? -
Getting null when doing request from browser but it is not null when same is done using postman
I am using django as a backend, React as frontend and cloud firestore is my DB. I am setting the batch id as the django session whenever any user login or create an account and the sending the request from the frontend to know which batch is currently logged in. This is my backend code class UserInHomepage(viewsets.ModelViewSet): def list(self, request, format=None): print("abc",self.request.session.get('batch_code')) if not self.request.session.exists(self.request.session.session_key): self.request.session.create() data={ 'code': self.request.session.get('batch_code') } print(self.request.session.get('batch_code')) if data['code'] == None: return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST) return JsonResponse(data, status=status.HTTP_200_OK) And this is my frontend througn which i am requesting which user is currently logged in useEffect(async ()=>{ fetch('/student/user-in-homepage/') .then((response) => response.json()) .then((data) => { console.log(data.code) }) },[]) But it prints null And the same request on postman gives the batch id which is currently logged in. -
Is there any solution to encrypt integer in Django using Django Cryptography package
I am trying to encrypt Django Integer Choices field using Django Cryptography package, here is the documentation: https://django-cryptography.readthedocs.io/en/latest/examples.html. Here is my code. from django_cryptography.fields import encrypt class NumberOfCars(models.IntegerChoices): One_Vehicle = 1 Two_Vehicle = 2 Three_To_Four = 4 Five_To_Eight = 7 More_than_Eight = 9 NumberOfCars = encrypt(models.IntegerField(choices=NumberOfCars.choices)) I am using Mysql database, Python==3.10 Django==4.0.4 While running migrations i got this error: PS C:\Users\lumkile\Desktop\Django\thariauth> py manage.py makemigrations Traceback (most recent call last): File "C:\Users\lumkile\Desktop\Django\thariauth\manage.py", line 22, in <module> main() File "C:\Users\lumkile\Desktop\Django\thariauth\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 455, in execute self.check() File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1442, in check *cls._check_fields(**kwargs), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1554, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django_cryptography\fields.py", line 121, in check errors = super().check(**kwargs) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1931, in check *super().check(**kwargs), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 252, in check *self._check_validators(), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 413, in _check_validators for i, validator in enumerate(self.validators): File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", … -
Django ORM - Condition or Filter on LEFT JOIN
I will try to be precise with this as much as possible. Imagine these two models. whose relation was set up years ago: class Event(models.Model): instance_created_date = models.DateTimeField(auto_now_add=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="car_events") ... a lot of normal text fields here, but they dont matter for this problem. and class Car(models.Model): a lot of text fields here, but they dont matter for this problem. hide_from_company_search = models.BooleanField(default=False) images = models.ManyToManyField(Image, through=CarImage) Lets say I want to query the amount of events for a given car: def get_car_events_qs() -> QuerySet: six_days_ago = (timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=6)) cars = Car.objects.prefetch_related( 'car_events', ).filter( some_conditions_on_fields=False, ).annotate( num_car_events=Count( 'car_events', filter=Q(car_events__instance_created_date__gt=six_days_ago), distinct=True) ) return cars The really tricky part for this is the performance of the query: Cars has 450.000 entries, and Events has 156.850.048. All fields that I am using to query are indexed. The query takes around 4 minutes to complete, depending on the db load. This above ORM query will result in the following sql: SELECT "core_car"."id", COUNT("analytics_carevent"."id") FILTER (WHERE ("analytics_carevent"."event" = 'view' AND "analytics_carevent"."instance_created_date" >= '2022-05-10T07:45:16.672279+00:00'::timestamptz AND "analytics_carevent"."instance_created_date" < '2022-05-11T07:45:16.672284+00:00'::timestamptz)) AS "num_cars_view", LEFT OUTER JOIN "analytics_carevent" ON ("core_car"."id" = "analytics_carevent"."car_id") WHERE ... some conditions that dont matter GROUP BY "core_car"."id" … -
Is it possible to make 'cart' with django Class Based View?
I am trying to make a simple e-commerce website and followed some tutorials. However, the author of the book used complicated function based view to make cart function.. there are bunch of session stuffs.. and I don't understand the logic.. and I am trying to think the other way.. what about use database to store all the cart related data, and use CBV to build it? for example, CartListView to see the contents of the cart, and CartUpdateView to change the quantity.. then are they going to be two different pages? separated page that user should go to the different page to change the value?? please help me T T