Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-compressor not finding blocks to compress in a GitHub Action
I have a Django project that's using django-compressor to minify and concatenate CSS files, using offline compression. I haven't yet put it on a server, but when I run manage.py compress in a GitHub Action, before running tests, it can't find the {% compress %} block, even though it can find the template containing them. I have a single template that uses CSS files, templates/myapp/layouts/base.html: <!DOCTYPE html> {% load compress static %} <html lang="en"> <head> <!-- ... --> {% compress css file global %} <link rel="stylesheet" href="{% static 'oohdir/css/global/variables.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/reset.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/form.css' %}"> <!-- etc --> {% endcompress %} When running the site locally I can have these Django settings: DEBUG = False COMPRESS_ENABLED = True COMPRESS_OFFLINE = True and when I run manage.py compress it generates a single CSS file, as expected, in static_collected/CACHE/CSS/. That file is linked in the HTML when I view pages in the browser (using manage.py runserver --insecure). But when I run my GitHub Action many tests fail because of a missing file, which django-compressor didn't generate. If I run manage.py compress --verbosity 2 in the Action I can see it finds the correct template among … -
Django: problem trying to post data to django model database
ProgrammingError at /admin/formRegister/formregister/ column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Request Method: GET Request URL: http://localhost:8000/admin/formRegister/formregister/ Django Version: 4.0.5 Exception Type: ProgrammingError Exception Value: column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Exception Location: C:\Users\hp\Desktop\Django\django3.9\lib\site-packages\django\db\backends\utils.py, line 89, in _execute Python Executable: C:\Users\hp\Desktop\Django\django3.9\Scripts\python.exe Python Version: 3.9.13 Python Path: ['C:\Users\hp\Desktop\Django\teluskoa', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\hp\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\hp\Desktop\Django\django3.9', 'C:\Users\hp\Desktop\Django\django3.9\lib\site-packages'] Server time: Thu, 11 Aug 2022 16:02:26 +0000 -
resource objects need to have a primary key value before you can access their tags
I am using django-taggit. When i used pre-save signal then I got the error below. resource objects need to have a primary key value before you can access their tags. model.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) pre-save signal function is def tag_set(sender, instance, **kwargs): print(instance.Tags) pre_save.connect(tag_set, sender=resource) -
Django prefetch_related multiple fields
Let's assume I have the following model class Store: name = models.CharField() location = models.CharField() clients = models.ManyToManyField('Client', related_name='stores', on_delete=models.CASCADE) providers = models.ManyToManyField('Provider', related_name='stores', on_delete=models.CASCADE) rating = models.CharField(max_length=128, choices=Rating.choices(), blank=True) I am aware I can do something like Store.objects.all().prefetch_related('clients') to prefetch the clients; however, I need to prefetch for providers as well, I could write to different queries, but I am wondering if I can something like Store.objects.all().prefetch_related('clients', 'providers') Additionally, what would be the best way to group them by rating? There might be betters way to this, any feedback is more than welcome. Thank you all!! -
I am getting this error in context_processors 'NoneType' object is not iterable
I want to show messages in every template that's why I need a context processor. But I am getting this error 'NoneType' object is not iterable. I can not resolve this problem. Can anyone see the code and give a solution for it. # context_processors.py from django.contrib import messages from .models import Loan def message_notification(request): loan_requested_lists = Loan.objects.filter(loan_req_user=request.user, active=True, status='Pending') if loan_requested_lists.exists(): if loan_requested_lists.count() == 1: for i in loan_requested_lists: return messages.info(request, f'{i.user.username}({i.user.account_number}) was requested for loan.') else: return messages.info(request, f'{loan_requested_lists.count()} users were requested for loan.') This is my models.py from django.utils import timezone from django.db import models from accounts.models import User from django.core.exceptions import ValidationError # Create your models here. STATUS = ( ('Pending', 'Pending'), ('Accepted', 'Accepted') ) EDITABLE_STATUS = ( ('Not Applicable', 'Not Applicable'), ('Requested', 'Requested'), ('Approved', 'Approved'), ('Not Approved', 'Not Approved'), ('Updated', 'Updated'), ) def validate_date(date): if date < timezone.now(): raise ValidationError("Date cannot be in the past") class Loan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) loan_req_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='loan_given_user_list', verbose_name='Loan Requested From User') amount = models.PositiveIntegerField(verbose_name='Loan Amount') date = models.DateTimeField(default=timezone.now, validators=[validate_date], verbose_name='Loan Return Date') status = models.CharField(max_length=8, choices=STATUS, default='Pending') editable = models.CharField(max_length=14, choices=EDITABLE_STATUS, default='Not Applicable') active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, verbose_name='Loan Requested Date') def __str__(self): return self.user.username -
Send email with attach in python error under https
i have an error trying to send email with attach pdf in python (Django) under https active but not do under http, this is my code: from django.conf import settings import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders sender_email_address = sender@mail.com email_password = myPass email_smtp = smtp.gmail.com email_subject = self.titulo receiver_email_address = receiver@gmail.com remitente = sender_email_address destinatarios = [receiver_email_address] asunto = email_subject cuerpo = self.cuerpo ruta_adjunto = 'file.pdf' nombre_adjunto = 'file.pdf' mensaje = MIMEMultipart() mensaje['From'] = remitente mensaje['To'] = ", ".join(destinatarios) mensaje['Subject'] = asunto mensaje.attach(MIMEText(cuerpo, 'plain')) archivo_adjunto = open(ruta_adjunto, 'rb') adjunto_MIME = MIMEBase('application', 'octet-stream') adjunto_MIME.set_payload((archivo_adjunto).read()) encoders.encode_base64(adjunto_MIME) adjunto_MIME.add_header('Content-Disposition', "attachment; filename= %s" % nombre_adjunto) mensaje.attach(adjunto_MIME) sesion_smtp = smtplib.SMTP(email_smtp, '587') sesion_smtp.set_debuglevel(1) sesion_smtp.ehlo() sesion_smtp.starttls() sesion_smtp.login(sender_email_address, email_password) texto = mensaje.as_string() sesion_smtp.sendmail(remitente, destinatarios, texto) sesion_smtp.quit() -
Django debug toolbar loads but doesn't show on the local server even after proper installation
I have installed django debug toolbar correctly on a pipenv environment and done the main steps, such as adding internal_ips of 127.0.0.1 and adding the debug toolbar to installed_apps and middleware but still whenever I run the server and open a template of an app the debug toolbar doesn't show. However if I open the page source in the browser, it shows all the elements of the toolbar however the toolbar doesn't display, does anyone know what is going wrong and how I could fix it. -
Filtering data from 3 different tables in django with 1 intermediate table
I have four models in my django application with following structure: class User(models.Model): first_name = models.CharField() last_name = models.CharField() class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class SomeItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class SomeOtherItem(models.Model): some_item = models.ForeignKey(SomeItem, on_delete=models.CASCADE, unique=True) I have to create an API and I have been given a list of SomeItem. I have to write a django queryset line to filter first_name and last_name from User model, all details of SomeItem model and all details of SomeOtherItem model(if present). I also have to create a serializer to parse the data as a Python dict. Will be great if one can help me in this. -
"detail": "Authentication credentials were not provided." in django rest framework
I am trying to do an app on flutter with django rest framework backend. I want to log in as an already registered user and then I want to see only my active tasks, because further I want to end them after some time. The problem is I get "detail": "Authentication credentials were not provided." when I have made some changes in my code. I do the authentification with username and password. views.py class LoginAPI(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] user = User.objects.filter(username=username).first() Token.objects.create(user=user) if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, #'username': user.username, #'password': user.password } token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') response = Response() response.set_cookie(key='token', value=token, httponly=True) response.data = { 'token': token } print(user.id) return response class seeActiveTasks(ListAPIView): queryset = Tasks.objects.filter(is_active = 1) serializer_class = taskSerializer permission_classes = [IsAuthenticated] def get_queryset(self): print(self.request.user) print(self.request.user.id) # added string #return super().get_queryset().filter(user=self.request.user.id) return super().get_queryset().filter(user_id = self.request.user.id) login_page.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:phoneapp/main.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:phoneapp/screens/get_tasks.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { bool _isLoading = false; @override Widget build(BuildContext context) { … -
Pytest does not raise ValidationError
I'm trying to test that a user can't be both agent and organizer but pytest doesn't raise ValidationError. models.py class User(AbstractUser): email = models.EmailField(unique=True) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=False, ) def clean(self): super().clean() if self.is_organizer and self.is_agent: raise ValidationError("User can't be Agent and Organizer at the same time") test @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) pytest error core\tests\test_users.py:21 (test_user_cant_be_organizer_and_agent_at_the_same_time) @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): > User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) E Failed: DID NOT RAISE <class 'django.core.exceptions.ValidationError'> test_users.py:28: Failed Destroying test database for alias 'default' ('test_crm')... -
google declined when i try to send email confirmation in django
This is the error when I try to send an email confirmation, any help rather than enabling a less secured app thank you (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials kw21-20020a170907771500b00731219a2797sm3559534ejc.210 - SMTP) -
How can I make django require a data migration when a condition changes?
I have a table containing a list of subclasses of a certain class in my django app. How can I make django require a data migration when this table is edited ? Is there some exception I can raise if django is started and one of these classes isn't in the table ? I'd also like to be able to hook into makemigrations so I can generate the correct data migration if possible. -
Docker doesn't see the table in the database after django migration
A Django project can be run in two ways: python manage.py runserver and using docker compose docker-compose up --build If run it the standard way (without docker), it works. If run it with docker, get an error that the database doesn't have the table relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... There are two containers gpanel_gpanel_1 and gpanel_db_1 I have tried migrations in 3 ways python manage.py migrate and docker-compose exec gpanel_db_1 python manage.py migrate and docker-compose exec gpanel_gpanel_1 python manage.py migrate And the last two methods did not display any information about the migration application in the console I also deleted the volumes gpanel_db_1 gpanel_gpanel_1 and re-created the container. But the error is still there. docker-compose.yaml version: "3.9" services: gpanel: restart: always build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/gpanel depends_on: - db environment: - DB_HOST=db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} volumes: postgres_data: -
Python based HMI (communication between python-script and webapp)
I build a machine for quality-checking of assembled parts by capturing images and running a SVM on them. It's written in Python. Right now it's used via command line and displaying the captured images and inference-results in an OpenCV-Window. The main.py also handles other stuff like camera-communication and stepper-motor-control. Now I want to move the prototype to production so it has to be more user friendly. This means I need a webapp as Human-Machine-Interface. For now it just needs a button for the user to start the quality-check (trigger a function) and to display the momentary state ("moving", "idle", "error", "checking" etc.) as well as the resulting image. My initial approach is to just keep the main.py idle-ing until the start-button is pressed. But what would be the best way to interact between the webapp and the main.py? Would Websockets make sense? (I have never used them, just read about it) Or RESTAPI? I originally am a mechanical engineer, just self-taught the necessary python-skills for the task, so it's a little hard for me to properly describe the problem ;) Thanks! -
Django: Couldn't import Django, But django is installed (checked with django-admin --version, returns 4.1)
So i tried this: py manage.py runserver And got this error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The virtual environmeent is activated (I have a little (venv) next to the path). Thing is, I just reinstalled django-admin via the virtual environment. Not only that but I did django-admin --version And got the result 4.1 Clearly it is installed. I can import django in IDLE just fine, but it won't run manage.py for some godforsaken reason. Any idea on how to fix this? -
How to get MIME type of FileField in DRF and send to parameters?
i hope everyone is good. I want to send mime type of the FileField in drf. but i dont know how to... { "id": 1, "document": "http://127.0.0.1:8000/images/articles_auth_with_user_eZUJmTW.png", "filesize": "239.55 KB", "filename": "articles_auth_with_user_eZUJmTW.png" "mimetype": "" }, This is response i am sending. I want to send mime type here... class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField() class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def filesize(self): x = self.document.size y = 512000 if x < y: value = round(x / 1024, 2) ext = ' KB' elif x < y * 1024: value = round(x / (1024 * 1024), 2) ext = ' MB' else: value = round(x / (1024 * 1024 * 1024), 2) ext = ' GB' return str(value) + ext @property def filename(self): return self.document.name Above is my models file class DocumentSerializer(serializers.ModelSerializer): class Meta: model=DocumentModel fields = ['id', 'document', 'filesize', 'filename'] This is serializer code. Please kindly help ... -
How to let WebSocket in React through Content Security Policy on a deployed server
I am currently using Websockets in React to connect to Django channels. It works locally, but on a deployed server I get the following error, "Refused to connect to 'WEBSOCKET_URL' because it violates the following Content Security Policy directive: "default-src https: data: 'unsafe-inline' 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback." I have tried the meta tag 'meta http-equiv="Content-Security-Policy" content="content-src 'self' ws://URL" /' but my login starts violating the Content Security Policy. Is there a way to add the websocket to the CSP without it interfering with other functions? -
Django/Flask : Rewritting an Flask Azure B2C authentication in Django
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask. I used the documentation/tutorial of microsoft that share a github with the flask code to do it : https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows https://github.com/Azure-Samples/ms-identity-python-webapp I try to convert it in Django however I have an error that I do not understand ! The error message : Internal Server Error: /login/ TypeError: Object of type HttpResponseRedirect is not JSON serializable Here is the code views.py def index(request) : if not request.session.get("user"): return redirect("login") return render('index.html', user=request.session["user"] ) def login(request): # Technically we could use empty list [] as scopes to do just sign in, # here we choose to also collect end user consent upfront request.session["flow"] = _build_auth_code_flow(scopes=list(json.loads(os.getenv("SCOPE")))) return render(request, "login.html", {'auth_url' : request.session["flow"]["auth_uri"]}) def authorized(request): try: cache = _load_cache(request=request) result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( request.session.get("flow", {}), request.args) if "error" in result: return render("auth_error.html", result=result) request.session["user"] = result.get("id_token_claims") _save_cache(cache=cache, request=request) except ValueError: # Usually caused by CSRF pass # Simply ignore them return redirect("index") def _load_cache(request): cache = msal.SerializableTokenCache() if request.session.get("token_cache"): cache.deserialize(request.ession["token_cache"]) return cache def _save_cache(cache, request): if cache.has_state_changed: request.session["token_cache"] = cache.serialize() def _build_msal_app(cache=None, authority=None): return msal.ConfidentialClientApplication( os.getenv("CLIENT_ID"), authority=authority … -
Админка Django не обрабатывает Html теги для постов приложения
Создал приложение на Django, которое выводит посты на сайт. Когда пишу в админке теги html, по типу strong или em и т.д. во время создания поста. Оно так и выводится, то есть не интерпретируется. Как решить данную проблему? -
Docker database does not exist
I am developing using docker in a Django project. For this project I need multiple PostgreSQL database live at the same time to work. So, I put in the env file all the current settings: DB_ENGINE="django.db.backends.postgresql_psycopg2" POSTGRES_USER="zwap_user_settings_db" POSTGRES_DB="zwap_user_settings_db" DB_HOST="zwap_user_settings_postgres" DB_PORT="5432" POSTGRES_PASSWORD=zwap_settings_postgres_db And I created the docker-compose.yml file to create all the needed postgresql instance at once version: '3.7' services: ... zwap_settings_postgres: container_name: zwap_user_settings_postgres image: postgres ports: - 6003:5432/tcp environment: - POSTGRES_USER=zwap_user_settings_db - POSTGRES_PASSWORD=zwap_settings_postgres_db - POSTGRES_DB=zwap_user_settings_db volumes: - zwap_settings_postgres:/var/lib/postgresql/data/ ... volumes: ... zwap_settings_postgres: So, I try to run the Django project and this error occurs: django.db.utils.OperationalError: FATAL: database "zwap_user_settings_db" does not exist and this error appears also in the docker terminal. But I don't understand where is the error. The code is the same everywhere. Maybe it is simply a silly thing that needs to be changes. IF someone knows how to fix, please help me. Thank you -
Secure storage of passwords in the database with the possibility of obtaining the original password?
The user can add his account from a third-party service (login, password), which is the best way to store the password in the database with the possibility of obtaining the original password in the future. -
How pass data from template to Updateview
I'm very new to programming. I would like to pass data from html input to update view and then save it to my database. Tried to search for it but with no luck. Here is my html code: <form action="{% url 'darbai:taskasupdate' pk=taskas.pk %}" method="POST"> {% csrf_token %} <input type="text" name="pavad"> <input type="text" name="atsak"> <button type="submit"/>Update</button> </form> Here is my model: class Taskas(models.Model): pavadinimas = models.CharField(max_length=30, null=True, blank=True) atsakingas = models.CharField(max_length=30, null=True, blank=True) Here is my urls: urlpatterns = [ path('', CreateList.as_view(), name='CreateList'), path('delete/<int:pk>', TaskasDeleteView.as_view(), name='taskasdelete'), path('update/<int:pk>', TaskasUpdateView.as_view(), name='taskasupdate'), ] Here is my view: class TaskasUpdateView(UpdateView): model = Taskas form_class = TaskasForm success_url = reverse_lazy('darbai:CreateList') def post(self, request, **kwargs): self.object = self.get_object() request.POST['pavad'] = self.object.pavadinimas request.POST['atsak'] = self.object.atsakingas -
How to pull variables of the main class from a subclass in django
I have a filter code for the site: def buy_files(request): bdfiles = FeedFile.objects.all() # bdfiles = UploadFile.objects.all() form = FileFilterForm(request.GET) if form.is_valid(): if form.cleaned_data["number_course"]: bdfiles = bdfiles.filter(number_course = form.cleaned_data["number_course"]) if form.cleaned_data["number_semestr"]: bdfiles = bdfiles.filter(number_semestr = form.cleaned_data["number_semestr"]) if form.cleaned_data["subjectt"]: bdfiles = bdfiles.filter(subjectt = form.cleaned_data["subjectt"]) if form.cleaned_data["type_materials"]: bdfiles = bdfiles.filter(type_materials = form.cleaned_data["type_materials"]) if form.cleaned_data["institute"]: bdfiles = bdfiles.filter(institute = form.cleaned_data["institute"]) return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) And models.py: class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок') # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True, verbose_name='Институт') def __str__(self): return self.title class Meta: verbose_name = 'Загрузка файла' verbose_name_plural = 'Загрузка файлов' class FeedFile(models.Model): file = models.FileField(upload_to="files/") feed = models.ForeignKey(UploadFile, on_delete=models.CASCADE) When I start entering data in the filter on the html page, an error occurs that there are no fields number_semestr, number_course and so on, but there are only fields feed, feed_id, file, id. HTML code of the page: <form action="" method="get" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label" for="{{ form.number_course.id_for_label }}">Курс: </label> … -
DRF Authentication is not working in frontend
So, I created registration app. I added registration API, Login API and User profile API. I tested three API's in Postman it is giving results. In my project I used djangorestframework-simplejwt authentication. When I test with browser it is not working what I have to do please anyone can help me out to achieve this. In settings.py # JWT Configuration REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } # JWT Settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=20), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', } INSTALLED_APPS = [ ......... 'rest_framework_simplejwt', ......... ] In Views.py class UserLoginView(APIView): def post(self, request, format=None): q = QueryDict(request.body) query_dict = q.dict() json_object = json.dumps(query_dict, indent=4) reqBody = json.loads(json_object) email = reqBody['email'] password = reqBody['password'] user = authenticate(email=email, password=password) print('user') print(user) if user is not None: token = get_tokens_for_user(user) Account = customer.objects.get(email=email) request.session['email'] = Account.email request.session['id'] = Account.id request.session['name'] = Account.firstname request.session['cust_status'] = Account.cust_status request.session['os_name'] = Account.os_name request.session['user_type'] = Account.flag request.session['username'] = str(Account.firstname) + str(Account.lastname) return Response({'token': token, 'msg': 'Login Success'}, status=status.HTTP_200_OK) else: return Response({'errors': {'non_field_errors': ['Email or Password is … -
How to Join Subqueries in Django ORM
I'm a beginner Django and I have been stuck on the following problem for a while. The basic thing I would like to achieve is that when client makes a GET list api request with a time period parameter (say 3 months) then the server would return an aggregation of the current 3 months data and also show an extra field comparing the difference with previous 3 months. I have models as: class NTA(models.Model): nta_code = models.CharField(max_length=30, unique=True) ... class NoiseComplaints(models.Model): complaint_id = models.IntegerField(unique=True) created_date = models.DateTimeField() nta = models.ForeignKey( NTA, on_delete=models.CASCADE, to_field='nta_code') ... The sample output I would like to get is something like: [ { "id": 1, "nta_code": "New York", "noise_count_current": 30, # this would be current 3m count of NoiseData "noise_count_prev": 20, # this would be prev 3m count of NoiseData "noise_count_diff": 10, # this would be prev 3m count of NoiseData } ... The raw SQL query (in Postgres) is quite simple as below but I'm really struggling on how to make this work in Django. WITH curr AS ( SELECT "places_nta"."id", "places_nta"."nta_code", COUNT("places_noisecomplaints"."id") AS "noise_count_curr" FROM "places_nta" INNER JOIN "places_noisecomplaints" ON ("places_nta"."nta_code" = "places_noisecomplaints"."nta_id") WHERE "places_noisecomplaints"."created_date" BETWEEN '2022-03-31 00:00:00+00:00' AND '2022-06-30 00:00:00+00:00' GROUP BY "places_nta"."id" …