Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I got athentication error when im trying to post a request using axios api in vue.js
commerce website and this is my checkout.vue code when post request an authenticated error 401 and i don't know where the problem is some says its becuase axios and i should replace it with fetch api,any suggestion? const data={ 'first_name':this.first_name, 'last_name':this.last_name, 'eamil':this.eamil, 'address':this.address, "zipcode":this.zipcode, "place":this.place, "phone":this.phone, "items":items, 'stripe_token':token.id } await axios .post("/api/v1/checkout/",data) .then(response=>{ this.$store.commit("clearCart") this.$router.push("/cart/success") }) .catch(error=>{ this.errors.push("Something went wrong. Please try again") console.log(error) }) this.$store.commit('setIsLoading',false) } -
CSRF Failed: CSRF token missing django REST + Vuejs obtain_auth_token
I am making POST request to get the token from the backend. I have traefik to provide https for security reason. It works. But when I deploy Vuejs and make POST with the same payload. I got the error in the Chrome browser. detail: "CSRF Failed: CSRF token missing." I have search over the stackoverflow. I would like to follow the security concept then disable CSRF is not an option. import {ref} from "vue"; import {BACKEND_URL} from "../constants"; const getLoginToken = () => { const token = ref('') const tokenError = ref(null) const fetchToken = async(username, password) => { try{ const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "username": username, "password": password }), redirect: 'follow', } const url = BACKEND_URL + '/api/auth-token/' console.log(url) let data = await fetch(url, requestOptions) if(!data.ok){ throw Error(data.statusText) } token.value = await data.json() } catch(err){ tokenError.value = err.message console.log(tokenError.value) } } return { token, tokenError, fetchToken } } export default getLoginToken settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } `urls.py from django.views.decorators.csrf import csrf_exempt ... path("api/auth-token/", csrf_exempt(obtain_auth_token)), ... But does not work. Problem: I am unable to … -
Friendly duration picker ready to be used as a form widget in a Django application
I need to let a user select a duration in a form field of a Django application. I'm already using bootstrap (namely django-bootstrap-datepicker-plus) to select other fields such as Date, Time and DateTime. But duration is something lightly different. I'm currently having a simple integer field where the user is asked to input the duration value in minutes. But once the duration last for some hours, e.g. 07h24, the user has to compute to how many minutes it corresponds before entering the right value. This is error prone. On the opposite, if I ask the user to input values in hours, 7h20 would become 7.3333. This is also error prone and it's not precise in that case. That's why I'm searching for a true duration picker. Using two DateTime pickers and computing the timedelta is also not an option for the lack of user-friendliness. Hence my question: does a friendly duration picker exists inside bootstrap for Django and if not, does something other exist? I guess I don't have to reinvent the wheel, but I wasn't able to figure out something which integrates well with Django 4. Ideally, jQuery should also be avoided. My current research led me to these … -
How to setup email verification with Django-Verify-Email
I get an invalid link in the email every time i register a new user with this package here is my code def signup(request, form_class, template_name, success_message, redirect_url): if request.user.is_authenticated: return redirect(redirect_url) form = form_class() if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): send_verification_email(request, form) form.save() messages.success(request, success_message) return redirect(redirect_url) else: messages.error( request, f'Error creating account. Please check the form.') return render(request, template_name, {'form': form}) context = {'form': form} return render(request, template_name, context) def student_signup(request): return signup( request, StudentRegistrationForm, 'user/student/signup.html', 'Student account created successfully.', 'user:signin' ) Am i just using the standard setting. Am i missing anything? -
Error 508 Invalid data in MERCHANT_ID field. Please contact the merchant
Can anyone help me understand why do I get this error? I used the merchant_id that I was given at https://developer.globalpay.com/ <<script> $(document).ready(function() { $.getJSON("sdkRequestEndpoint", function(jsonFromRequestEndpoint) { RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay"); RealexHpp.lightbox.init("payButtonId", "responseEndpoint", jsonFromRequestEndpoint); }); }); </script> <!DOCTYPE html> <html lang="en"> <head> <!-- Add these links in the head section of your HTML file --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> </head> <body> <center> <h2>Make a Booking</h2> <form action="https://pay.sandbox.realexpayments.com/pay" method="POST" target="iframe"> <input type="hidden" name="TIMESTAMP" value="20180613110737"> <input type="hidden" name="MERCHANT_ID" value="MER_7e3e2c7df34f42819b3edee31022ee3f"> //my Merchant_ID <input type="hidden" name="ACCOUNT" value="internet"> <input type="hidden" name="ORDER_ID" value="N6qsk4kYRZihmPrTXWYS6g"> <input type="hidden" name="AMOUNT" value="1999"> <input type="hidden" name="CURRENCY" value="EUR"> <input type="hidden" name="AUTO_SETTLE_FLAG" value="1"> <input type="hidden" name="COMMENT1" value="Mobile Channel"> <input type="hidden" name="HPP_VERSION" value="2"> <input type="hidden" name="HPP_CHANNEL" value="ECOM"> <input type="hidden" name="HPP_LANG" value="en"> <!-- Begin 3D Secure 2 Mandatory and Recommended Fields --> <input type="hidden" name="HPP_CUSTOMER_EMAIL" value="test@example.com"> <input type="hidden" name="HPP_CUSTOMER_PHONENUMBER_MOBILE" value="44|789456123"> <input type="hidden" name="HPP_BILLING_STREET1" value="Flat 123"> <input type="hidden" name="HPP_BILLING_STREET2" value="House 456"> <input type="hidden" name="HPP_BILLING_STREET3" value="Unit 4"> <input type="hidden" name="HPP_BILLING_CITY" value="Halifax"> <input type="hidden" name="HPP_BILLING_POSTALCODE" value="W5 9HR"> <input type="hidden" name="HPP_BILLING_COUNTRY" value="826"> <input type="hidden" name="HPP_SHIPPING_STREET1" value="Apartment 852"> <input type="hidden" name="HPP_SHIPPING_STREET2" value="Complex 741"> <input type="hidden" name="HPP_SHIPPING_STREET3" value="House 963"> <input type="hidden" name="HPP_SHIPPING_CITY" value="Chicago"> <input type="hidden" name="HPP_SHIPPING_STATE" value="IL"> <input type="hidden" name="HPP_SHIPPING_POSTALCODE" value="50001"> <input type="hidden" name="HPP_SHIPPING_COUNTRY" value="840"> <input type="hidden" name="HPP_ADDRESS_MATCH_INDICATOR" value="FALSE"> <input type="hidden" name="HPP_CHALLENGE_REQUEST_INDICATOR" value="NO_PREFERENCE"> <!-- … -
Custom user model vs. additional model
Due to lack of knowledge, when faced with the need to store additional information about users, I created additional UserInfo model and referenced it by foreign key to the standard User model. I have since learned two things: It is recommended to have a custom user model. It is tricky to switch mid-project (this being the best way so far as far as I understand). I would like to understand: If the fields in UserInfo are not used for authentication, is there any reason to merge those into the user model? What do I stand to gain by taking the time to abandon my current approach and switch to a custom user model? -
React and Django deployment blank page and 404 errors on static files with cpanel
I wanted to deploy my django and react application on my domain name via my host I have setup my python because when we go to the url dimitridenis.com/admin we arrive at my django admin portal, I implemented React and did the npm install then the build in my cpanel terminal, however I found myself with a white screen and 404 errors on static files, I tried several times to change my build, the paths in my settings.py file but I still don't understand White screen with errors If you have any ideas to give me, I'm interested -
Can we use django-distill to host a Django website in Github pages?
I'm exploring options for hosting a Django website on GitHub Pages, and I came across the django-distill package. I'm wondering if it's feasible to use django-distill for hosting a Django website on GitHub Pages. Here are some specific points I'm curious about: *Has anyone successfully used django-distill to deploy a Django website on GitHub Pages? *Are there any specific configurations or steps that need to be taken to make it work with GitHub Pages? I appreciate any insights or experiences you can share regarding using django-distill or any other approach for deploying a Django site on GitHub Pages. I attempted to use django-distill to deploy a Django website on GitHub Pages. My approach involved configuring django-distill and following the standard steps for deploying a Django project. However, despite my efforts, I encountered challenges, and the deployment did not work as expected. Link: https://django-distill.com/ -
Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented')
seem to be getting a script error that mentions both bootstrap alert and my own close alert tag. I have a script that closes alerts after 2.5s when a script is created. It is tied to user actions, for example if a user creates a blog post or deletes a comment, an alert shows with the User task and then auto closes the tag. i seem to be getting a Uncaught TypeError in console and cant figure out why, i can only speculate that its because its looking for a alerts msg that isnt there yet? script.js // // Event listener for auto close message function using DOM Content Loaded // // Javascript function for auto close messages // document.addEventListener("DOMContentLoaded", alertTimeout); document.addEventListener("DOMContentLoaded", (alertTimeoutalertTimeout) => { setTimeout(function () { let messages = document.getElementById("msg"); let alert = new bootstrap.Alert(messages); alert.close(); }, 2500); }); index.html bootstrap script <!-- Bootstrap Scripts --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </html> Console Error code Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented') at Q.close (alert.js:38:60) at script.js:11:11 close @ alert.js:38 (anonymous) @ script.js:11 setTimeout (async) (anonymous) @ script.js:7 I have tried to add a document ready to the script and have tried different … -
django get all the likes made for a post
i am trying to get all the likes for a specific in the home templates and also they are many products in the template. this is my views.py @login_required def home(request): products = Product.objects.all() like_counts = {product.id: Like.objects.filter(product=product).count() for product in products} liked_products = Like.objects.filter(user=request.user, product__in=products).values_list('product', flat=True) context = { "products": products, "liked_products": liked_products, "like_counts": like_counts, "categories": Category.objects.all(), } return render(request, 'shop/index.html', context) @login_required def likeProduct(request, product_id): product = get_object_or_404(Product, id=product_id) # Check if the user has already liked the product if not Like.objects.filter(user=request.user, product=product).exists(): # Create a new Like object Like.objects.create(user=request.user, product=product) print('product liked') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) else: liked = Like.objects.get(user=request.user) liked.delete() print('product like removed') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) def views_count(request,product_id):` item = Product.objects.get(id=product_id) item.views_count += 1 item.save() return redirect('home') this is my index.html and i am got stuck here now the django is giving all sorts of weird errors and do not know how to solve it: {% csrf_token %} <div class="d-flex justify-content-between"> <button onclick="likeProduct({{ product.id }})" class="btn shadow-none bg-transparent rounded-pill"> <i class="{% if product.id in liked_products %}fas{% else %}far{% endif %} fa-heart"></i> {{ like_counts|default:"0"|get:product.id }} </button> <button class="btn shadow-none bg-transparent rounded-pill"><i class="fas fa-star"></i></button> <button class="btn btn-outline-primary"><i class="fas fa-comment"></i></button> </div> -
Problem connecting a django project with a mysql database in a docker container
I can't access the db from tableplus, mysqlworkbench or django, but I can access it from the docker container console. when i try to connect with docker exec -it 2ac7cefb3198 /bin/bas mysql -proot -uroot i can access Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 Server version: 8.2.0 MySQL Community Server - GPL Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> show databases; +--------------------+ | Database | +--------------------+ | hbrs_bd | | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.01 sec) but when i try with django 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hbrs_bd', 'HOST': 'localhost', 'USER': 'root', 'PORT':'3308', 'PASSWORD': 'root' } }``` i had this response (1045, "Access denied for user 'root'@'localhost' (using password: YES)") this is my dockerfile FROM mysql:8 ENV MYSQL_ROOT_PASSWORD root COPY ./hbrs_bd.sql /docker-entrypoint-initdb.d/hbrs_bd.sql and this is my docker compose file services: database: build: . ports: - "3308:3308" some body had some expierencie with … -
What framework should I learn for backend [closed]
What framework should I learn for backend in 2024? I have tried Django and Laravel I just do not know witch one is better to get a job these times and I am going with react too so I see a lot of people use node js but I just know it is no good in my country to learn int. that is why I am going with these two frameworks ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, do not read the next lines : it is just nothing so that stack overflow tkae my qustion it said 220 but i just do nt know why it still do not want to send this qustion to you all man come onnnnnnnnnnnnnnnnnnnn it is my first time on this website and I am thinking of going back to chat gpt 3 not even 4 if u do not allow this man come on -
ModuleNotFoundError: No module named '_sqlite3' trying to connect with sqlalchmey and pandas
I am using Python version 3.10. I'm attempting to connect a MySQL database to SQLalchemy and Pandas. The local environment is working fine. But when I deployed in Ubuntu, I got ModuleNotFoundError: No module named '_sqlite3'. Note:- But I tried to connect with Django Orm with Ubuntu, which was also working as expected. the only problem with sqlalchemy and Pandas. from sqlalchemy import create_engine import pandas as pd engine = create_engine(url,echo=False) ## en conn = engine.connect() df = pd.read_sql_query('SELECT * FROM role_master', con=engine) Need solution to fix this issue. -
How to convert a synchronous view to async view in Django
I'm working on a django view to get list of available riders. I first created in a synchronous context and when I tested it, it worked as expected. I need it to be in an asynchronous context, but when I tried to convert i to an async context, I get this error message below: raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Here's the code in an async context I came up with trying to convert to an async context, but got the error above: riderexpert_db = firestore.AsyncClient(project="riderexpert", database="riderexpert-db") class GetAvailableRidersView(APIView): permission_classes = [IsAuthenticated] SEARCH_RADIUS_METERS = 10 async def get_google_maps_client(self): """Initialize and return the asynchronous Google Maps API client.""" return GoogleMapsClient(key=settings.GOOGLE_MAPS_API_KEY) async def validate_parameters(self, order_location, item_capacity, is_fragile): """Validate input parameters.""" try: item_capacity = float(item_capacity) is_fragile = str_to_bool(is_fragile) except (ValueError, TypeError): return False, "Invalid or missing parameters" if not all( [ order_location is not None and isinstance(order_location, str), item_capacity is not None and isinstance(item_capacity, (int, float)), is_fragile is not None and isinstance(is_fragile, bool), ] ): return False, "Invalid or missing parameters" return True, "" def handle_google_maps_api_error(self, e): """Handle Google Maps API errors.""" return Response( {"status": "error", "message": f"Google Maps API error: {str(e)}"}, … -
Token is automatically changing on every request
I get access and refresh token after logging in by following code. class Employee_Login(APIView): permission_classes=[AllowAny] employee_login_data = serializers.employee_login_serializer def post(self,request): try: employee_data = self.employee_login_data(data=request.data) employee_data.is_valid(raise_exception=True) data = employee_data.validated_data employee = authenticate(request,email=data.get('email'), password= data.get('password')) if not employee: return Http404("Employee not found") if not employee.is_verified: raise ForbiddenException("Employee is not verified") payloads = { "user": "admin" if employee.is_admin and employee.is_verified and employee.is_staff else "staff" if employee.is_staff and employee.is_verified else "" } employee_detail = { "name":employee.name, "email":employee.email, "type":"admin" if employee.is_admin and employee.is_staff and employee.is_verified else "staff" if employee.is_admin and employee.is_verified else "" } refresh = RefreshToken.for_user(employee) refresh.payload.update(payloads) acess_token = str(refresh.access_token) refresh_token = str(refresh) return Response({"success":True, "data":employee_detail, "token":{"access":acess_token,"refresh":refresh_token}}) except Exception as e: return Response({"success":False,"message":str(e)}) The problem is, when I use the access token obtained from above code in below custom permission class class AdminPermission(permissions.BasePermission): def has_permission(self, request, view): print("Here",AccessToken(request.auth).payload) STAFF_METHODS = ['GET','POST','PATCH'] USER_METHODS = ['GET'] if request.method in USER_METHODS: return True print(AccessToken(request.auth)) if request.user.is_authenticated: if request.user.is_admin and request.user.is_staff and request.user.is_verified: return True if not request.user.is_admin and request.user.is_staff and request.user.is_verified and request.method in STAFF_METHODS: return True return False The print(AccessToken(request.auth)) is printing different token than the token that I passed from request. And it is printing different things in every request. I am frustrated by this … -
Unable to create a google meet link in Django
I am getting credentials from the service account. SCOPES = ['https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.events'] credentials = Credentials.from_service_account_file(path , scopes=SCOPES) To generate the meet link here's my body code event = { "end": { "dateTime": "2023-12-29T11:00:00", "timeZone": "UTC" }, "start": { "dateTime": "2023-12-29T10:00:00", "timeZone": "UTC" }, "conferenceData": {"createRequest": {"requestId": "sample123", "conferenceSolutionKey": {"type": "hangoutsMeet"}}}, } event_response = service.events().insert(calendarId=calendarId, body=event,conferenceDataVersion=1).execute() I am getting the error:- returned "Invalid conference type value.". Details: "[{'domain': 'global', 'reason': 'invalid', 'message': 'Invalid conference type value.'}]"> -
Locking a row for the duration of the inner transaction
Consider: with transaction.atomic(): ... with transaction.atomic(): row = MyModel.objects.select_for_update().get(...) ... # I need the lock on the row to be released here ... # It is actually released here, which is not what I need As this article puts it: In many database engines, such as PostgreSQL, there’s no such thing as a nested transaction. So instead Django implements this using a single outer transaction. I have confirmed that the lock is released only when the outer transaction ends. How can I achieve the effect explained in the comments in the above code block, i.e. that a row locked in the inner transaction become released upon the completion of that transaction? -
Payload is missing from jwt token in djanog
I'm setting updating payload of token by following way. payloads = { "user": "admin" if employee.is_admin and employee.is_verified and employee.is_staff else "staff" if employee.is_staff and employee.is_verified else "" } refresh = RefreshToken.for_user(employee) refresh.payload.update(payloads) acess_token = str(refresh.access_token) refresh_token = str(refresh) And when I print the payloads of token by print(refresh.access_token.payload) it is showing {'token_type': 'access', 'exp': 1703799022, 'iat': 1703763022, 'jti': '7b09308f00194f149cadd7ec6f1728cc', 'user_id': 3, 'user': 'admin'} I have set custom permission class as follows class AdminPermission(permissions.BasePermission): def has_permission(self, request, view): print(AccessToken(request.auth).payload) STAFF_METHODS = ['GET','POST','PATCH'] USER_METHODS = ['GET'] if request.method in USER_METHODS: return True print(request.user) if request.user.is_authenticated: if request.user.is_admin and request.user.is_staff and request.user.is_verified: return True if not request.user.is_admin and request.user.is_staff and request.user.is_verified and request.method in STAFF_METHODS: return True return False When this permission class is called print(AccessToken(request.auth).payload) is printing only {'token_type': 'access', 'exp': 1703799137, 'iat': 1703763137, 'jti': '402403953a4d4810b3d453385d005330'}. user_id and user field is missing from the token. I don't know where I went wrong. I have been stucked in this from several hours. How can I solve this? Please help. I'm passing Bearer token -
multi-tenant with multiple database
I am trying to create database per tenant automatically and also trying to do makemigrations and migrant automatically but this error comes, give me solution of it: ProgrammingError at /account/register/ relation "account_user" does not exist LINE 1: SELECT 1 AS "a" FROM "account_user" WHERE "account_user"."us... POV: I am uisng DRF, Postgresql -
My static files are not loading due to permission denied?
ubuntu@ip-172-26-13-151:~$ sudo tail /var/log/nginx/error.log 2023/12/28 05:14:20 [error] 17570#17570: *14 open() "/home/ubuntu/Donor/static/assets/plugins/slick-carousel/slick/slick.css" failed (13: Permission denied), client: 182.191.136.55, server: 44.222.2.190, request: "GET /static/assets/plugins/slick-carousel/slick/slick.css HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" 2023/12/28 05:14:21 [error] 17570#17570: *12 open() "/home/ubuntu/Donor/static/assets/plugins/slick-carousel/slick/slick.min.js" failed (13: Permission denied), client: 182.191.130.7, server: 44.222.2.190, request: "GET /static/assets/plugins/slick-carousel/slick/slick.min.js HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" 2023/12/28 05:14:21 [error] 17570#17570: *13 open() "/home/ubuntu/Donor/static/assets/plugins/bootstrap/bootstrap.min.js" failed (13: Permission denied), client: 182.191.130.7, server: 44.222.2.190, request: "GET /static/assets/plugins/bootstrap/bootstrap.min.js HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" This is the error how could I solve this I am using Nginx and Gunicorn for deploying my django app. -
How to customize the default Token invalid json response in django for JWTAuthentication
In my django rest app i like to change the default error response from JWTAuthentication. Currently my application is using JWT With django to work on login and logout (which blacklists the token). Below is my code. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } account app views.py from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken, BlacklistMixin class BlacklistRefreshTokenView(APIView, BlacklistMixin): def post(self, request): token = RefreshToken(request.data.get('token')) token.blacklist() # return Response({'message': 'Token blacklisted successfully.'}) return json_response('Logout successful', None, 200) class CustomTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): # Call the base class's post method to continue with the login process response = super().post(request, *args, **kwargs) return response urls.py from django.urls import path from .views import CustomTokenObtainPairView, BlacklistRefreshTokenView urlpatterns = [ path('login/', CustomTokenObtainPairView.as_view(), name="login"), path('logout/', BlacklistRefreshTokenView.as_view(), name='blacklist_token'), ] response im getting when token is invalid { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } expected response { "message": "Given token not valid for any token type", "status": "401" } -
Nginx returns 502 errors with Gunicorn/Daphne with bursts connections
Kubernetes deployment contains 2 containers: Django application with Daphne, binded on Unix socket Nginx is in front of it as reverse proxy UDS is shared as volume between app and Nginx container, Memory type. Configuration works as expected except when there are burst in connections, eg, when pod is restarted and all connections from killed pod are spreaded to remaining pods. When connections are being terminated, we can observe HTTP 502 errors that upstream server is not available on /var/run/daphne.sock. It lasts for some period, usually up to 20 seconds and it starts working again. If we switch to TCP port instead of UDS, it works slightly better, but 502 errors are still present. Nginx config: worker_processes 1; user nobody nogroup; error_log /var/log/nginx/error.log warn; pid /tmp/nginx.pid; events { worker_connections 16384; } http { include mime.types; # fallback in case we can't determine a type default_type application/octet-stream; sendfile on; access_log off; upstream ws_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/var/run/daphne.sock fail_timeout=0; } server { listen 8443 ssl reuseport; ssl_certificate /etc/nginx/ssl/TLS_CRT; ssl_certificate_key /etc/nginx/ssl/TLS_KEY; ssl_client_certificate /etc/nginx/ssl/CA_CRT; ssl_protocols TLSv1.2 TLSv1.3; client_max_body_size 5M; client_body_buffer_size … -
How to make a form that can add an unlimited amount of elements
I'm trying to make my schools web-site for students. In this site i want to allow them create project page. In project page I want to allow them to upload unlimited number of files that can be dowloaded by other users. Image from template How I can do that from django.db import models from django.contrib.auth.models import User import uuid from phonenumber_field.modelfields import PhoneNumberField class News(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, editable = False) name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) images = models.ImageField(upload_to='media/', default=None, null=True, blank=True) face_image = models.ImageField() created = models.DateTimeField(auto_now_add=True) text = models.TextField() id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) class Meta: ordering = ["-created"] class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) profile_image = models.ImageField(upload_to='profileimages/', default=None, null=True, blank=True) bio = models.CharField(null=True, blank=True, max_length=130) Date_of_birth = models.DateField(null=True, blank=True) phone_number = PhoneNumberField(null=True, blank=True, region="UZ") job = models.CharField(null=True, blank= True, max_length=50) id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) about = models.TextField(null=True, blank=True) # Create your models here. class Skills(models.Model): skills = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) class Project(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() category = models.CharField(null=True, blank=True, max_length=20) cost = models.CharField(null=True, blank=True, default="0.0$", max_length=10) profit = models.CharField(null=True, blank=True, default="Non-profit", max_length = … -
Custom Filtering Based on Published Posts (In Django admin)
I'm working on a training project for a social network where users can post their recipes. I want to add the ability to filter users in Django admin based on whether they have published recipes or not. My filter class is: class UserHasRecipeFilter(admin.SimpleListFilter): title = _('Posted recipes') parameter_name = 'posted_recipes' def lookups(self, request, model_admin): return ( ('yes', _('Yes')), ('no', _('No')), ) def queryset(self, request, queryset): if self.value() == 'yes': return queryset.annotate(recipes_count=Count('recipes')).filter(recipes_count__gt=0) elif self.value() == 'no': return queryset.annotate(recipes_count=Count('recipes')).filter(recipes_count=0) Custom filter is added: @admin.register(UserProfile) class UserAdmin(UserAdmin): list_filter = ('is_active', 'UserHasRecipeFilter’,) But when I try to run make migrations, It is failing with an following error : ERRORS: <class 'recipes.admin.UserAdmin'>: (admin.E116) The value of 'list_filter[2]' refers to 'UserHasRecipeFilter', which does not refer to a Field. Please advise where I made a mistake.. -
Applying Additional Styles to Inherited Django Templates with Jinja Templating
In my Django project, I've set up a base HTML template (base.html) with a set of CSS styles. This base template is inherited by several other templates across my project. The challenge I'm facing is that some of these inherited templates require additional styles that are specific to each template. While I attempted to include all styles in base.html, I found that it doesn't work seamlessly for templates with unique styling needs. What is the recommended approach for applying additional styles to individual templates while still leveraging the common styles defined in base.html? Are there best practices or Django conventions for managing such scenarios effectively? I appreciate any insights or suggestions on how to structure my templates and styles to achieve a cohesive design across the project. I initially attempted to consolidate all styles within the base.html file, expecting them to seamlessly apply to all templates. However, this approach didn't work as intended. The additional styles for individual templates were not being applied correctly.