Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i always get error on this statement even if statement is false or true if password != confirm_password: print("Password error")
if password != confirm_password: print("Password error") return redirect("user_register") else: if User.objects.filter(email=email).exists(): print("Email already exists") return redirect("user_register") else: if User.objects.filter(username=username).exists(): print("Username error") return redirect("user_register") else: user = User.objects.create_user(username=username, email=email, password=password) user.save() data = Customer(user=user, phone_field=phone) data.save() # Code for login user again our_user = authenticate(username=username, password=password) if our_user is not None: login(request, our_user) return redirect("") else: print("Authentication error") return redirect("user_register") return render(request, 'accounts/register.html') i want when my all statement got true then data save to database and redirect page to login page and after that redirect from login to home page -
Why do I need to restart docker container to update code changes
I am developing a Django-based application in a Docker container. All the volumes are set up correctly but I noticed something concerning file updates in the docker container. After some time, the docker container cannot update the file in the container despite changes in my host machine. I am forced to restart the container to make the changes reflect. What could be the cause of this issue? Why files in a docker container may be out of sync with files in the host machine yet the volumes are correctly mapped? I tried to restart the container and the changes reflected but I want to know what causes this issue? -
How to Pass Tenant ID to FastAPI Microservices for Database Operations in a Django-Tenants Setup?
I'm relatively new to Django-tenants. My goal is to develop a SaaS application that runs on Kubernetes, where each tenant has its own database. For scalability and fault tolerance, I'm considering using FastAPI as microservices to manage individual modules separately. Architecture example Would it be advisable to structure the application this way, or would it be better to stick with a monolithic Django architecture and compromise on individual scalability? If it is recommended, how should I structure FastAPI to handle tenant-specific operations, such as using an X-Tenant-ID header in AJAX requests to determine the appropriate CRUD operations? I tried to send the tenant ID via AJAX (Header: X-Teantn-ID: 1) to the FastAPI microservice, but FastAPI is unable to establish a connection to the database using the tenant ID. -
Django Nginx And Gunicorn subdomain hosting gets 400 error
Nginx and Django Setup Results in Bad Request (400) Error I'm trying to configure Nginx to serve my Django application, but I'm encountering a "Bad Request (400)" error. I've set up my Nginx server block and Django settings as follows: server { listen 80; server_name subdomain.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/diagrjxt/medinote/staticfiles/; } location /media/ { alias /home/diagrjxt/medinote/media/; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/medinote.sock; } } DEBUG = False ALLOWED_HOSTS = ['*'] Issue: I've restarted both Gunicorn and Nginx, but I still receive a "Bad Request (400)" error when I try to access the site. There are no errors in the Nginx error log, but the access log shows the following entries: 103.121.239.95 - - [31/Jul/2024:06:22:40 +0000] "GET / HTTP/1.1" 400 154 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/5127.36" "-" 103.119.239.95 - - [31/Jul/2024:06:22:40 +0000] "GET /favicon.ico HTTP/1.1" 400 154 "http://medinote.diagnotech-ai.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" "-" -
Keycloak 25.0.2 - Django - Force Login
I need to add an external auth in my Django + Keycloak application. Unfortunally there is no native plugin for this auth (is specific for my Country) so I need to manage it with Python and then force a user login using PythonKeycloack (that use api) without knowing the user password. What I have is an admin account, and relative tokens, that may be usefull to achieve this goal. Thanks -
How to change the Display Name on sent emails with django allauth?
I'm using django allauth to sign up users and sending confirmation emails to new users and it's working fine except that it shows "support" as in "support@example.com" as my name. I'd like it to change that to "Khaled from XYZ". I tried the following but it actually crashed the smtp connection: EMAIL_HOST_USER = 'Khaled from XYZ <support@example.com>' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
db.sqlite to postgresql conversion in a django project
Error : RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres.railway.internal" to address: No such host is known. warnings.warn( No changes detected DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': '*****************', 'HOST': 'postgres.railway.internal', 'PORT': '5432', } }```` Earlier the database support was made via db.sqlite by sql is not supportd by vercel for deployment so had to convert it to postgresql but this error is showing up I do not have command over postgresql so i do not have it installed rather I have used railway.app for the purpose -
How can i manage boolean flags in Django?
Can somebody explain, which best practice should i use for managing flags in my Django Models, that will be serialize in DRF I have this model: class Project(models.Model): * Logic * is_free = models.BooleanField(default = True) is_paid = models.BooleanField(default = False) is_free_or_donate = models.BooleanField(default = False) How should i manage this flags in Django? Should I use model methods for this purpose to incapsulate logic within model? Or maybe overwrite save methods and do it there? I appreciate for having tips about best practices -
CommandError: This field cannot be blank. This field cannot be null.This field cannot be blank.; This field cannot be blank. when creating a superuser
I have seen similar concerns here but none fixes my problem. I am making my first project in Django and wagtail. I am fairly new with both of them, so please be nice :). I am using a custom user for django authentication and I keep getting the error in teh title every time I try to create a super user. The more confusing thing is, the user seems to be registered because when I try to use the email in the next creation, it says that teh email has been used but then when I try to login, it says that the user has no profile. Here is my code, any answers will be appreciated. The user model has the following code: from typing import ClassVar from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, Group, Permission from django.db import models from django.db.models import BooleanField from django.db.models import CharField from django.db.models import EmailField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from rhs_soccer.users.enums import UserRoles from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): """ Default custom user model for RHS Boys Soccer Club. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. … -
How to create and use multiple standalone vue apps in one html page (Vue2 + Django)
Im kind off new to vue and I'm trying to implement a vue + vuetify + vuex frontend in my already half written django application, I want the vue applications to connect independently of each other in different divs of html pages At the moment, with this connection: <div class="tab-content" id="settings-tab-content"> <script type="application/json" id="initial-data"> { "is_superuser": {{ is_superuser|lower }} } </script> <div class="tab-pane fade" id="groups-tab-content" role="tabpanel" aria-labelledby="groups-tab"> <div id="userGroups"></div> </div> <div class="tab-pane fade" id="structure-tab-content" role="tabpanel" aria-labelledby="structure-tab"> <div id="app"></div> </div> </div> import Vue from 'vue' import clinicStructure from './clinicStructure.vue' import userGroups from './userGroups.vue' import router from './router' import store from './store' import vuetify from './plugins/vuetify' import '@mdi/font/css/materialdesignicons.css' import 'vuetify/dist/vuetify.min.css' Vue.config.productionTip = false new Vue({ router, store, vuetify, render: h => h(clinicStructure) }).$mount('#app') new Vue({ router, store, vuetify, render: h => h(userGroups) }).$mount('#userGroups') Components and building with this "build": "vue-cli-service build --dest=../../static/builds/prod", "dev": "vue-cli-service build --dest=../../static/builds/dev --mode=development --watch" works fine but modal windows from one element open in another (in the one that is mounted first) So, how can I make a separate vue component connect to a specific div without affecting other components p.s. I can't make one entry point for frontend and then process paths through vue router, I need … -
SSE react '406 (Not Acceptable)'
I have some problem with react and django application. I want to use SSE to let the two of them communicate, but I get 406 responses from the front end. I think I fail when I try to connect. I can't get a response from the backend. This is my django code class Test(viewsets.ViewSet): def list(self, request): def test(): i = 1 while i < 6: yield f'data: {i}\n\n' i += 1 return StreamingHttpResponse(test(), content_type='text/event-stream') And my react code import { NativeEventSource, EventSourcePolyfill } from 'event-source-polyfill'; export default function Teset() { const test = () => { const EventSource = EventSourcePolyfill; const eventSource = new EventSource( "http://localhost:30018/test/", { headers: { "Content-Type": "text/event-stream", }, withCredentials: true, } ); }; return ( <> <button onClick={test}>button</button> </> ) } If you know the answer, please leave an answer. I saw an answer on Google saying you just need to specify what type you will receive in the header, but to no avail. -
How to get Parent Thread request data to all Child threads. using DRF
How to get Parent Thread request data to all Child threads. using DRF. I store request data using middleware and i get this request in subthread i not get that values. middleware.py class GlobalHttpRequestMiddleware(MiddlewareMixin): global_request.set_request(request) global_request.py class GlobalRequest(local): """Thread local class to store Http request object""" def __init__(self): self.__request: Optional[HttpRequest] = None def get_request(self) -> Optional[HttpRequest]: """ getter() to get the request""" return self.__request def set_request(self, request: HttpRequest) -> None: """ setter() to set the request""" self.__request = request global_request = GlobalRequest() class ThreadGlobal: """Create a Custom request object for a thread""" def __init__(self, current_scheme: Optional[str], meta_data: Optional[dict]): self.current_scheme = current_scheme self.meta_data = meta_data sample.py request = global_request.get_request() thread = CustomThread(target=Trigger.samplefn, args=([a1, a2]), initialize_env=_set_custom_app_env) thread.start() thread_callback.py def _set_custom_app_env() -> Callable[[], None]: # getting the global request from current thread and storing it into the variable to pass inside child function global_request_data = global_request.get_request() currect_scheme = global_request_data._current_scheme_host meta_data = global_request_data.META request = ThreadGlobal(currect_scheme, meta_data) def _set_env() -> None: '''This inner function will be executed inside the child threads''' global_request.set_request(request) return None return _set_env in global_request.set_request(request) in side the _set_env closer funtion i get request is NONE why... Give solution -
Difference in date translation between localhost and production - django
Localhost: Production (nginx + gunicorn): Do you have any idea why this happens? And it happens only in polish. German, japanese, english and spanish work perfectly on production as well. Settings.py: LANGUAGE_CODE = "en-us" LANGUAGES = [ ("pl", "Polski"), ("en", "English"), ("es", "Español"), ("de", "Deutsch"), ("ja", "Japanese"), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) TIME_ZONE = "Europe/Warsaw" USE_I18N = True USE_L10N = True USE_TZ = True HTML: {% for concert in concerts %} <div class="detailed-page-text calendar"> <p class="concert-title">{{ concert.title }}</p> <p class="concert-date">{{ concert.date }}</p> <p class="concert-time"><bold>{{ concert.time }}</bold></p> <p class="concert-location">{{ concert.location_main_name }}</p> <p class="concert-address">{{ concert.location_address }}, {{ concert.city }}</p> {% if concert.link_to_details %} <a class="more" href="{{ concert.link_to_details }}"> {% trans "More" %}</a> {% endif %} <br> </div> {% endfor %} I tried clearing nginx cache manually - no result. restarting, reloading server. Did not help much. I have also restarted gunicorn and gunicorn.socket. No result. -
Using Django as the SSO Identity Provider?
Instead of using a 3rd-party SSO tool (Okta, Auth0, Outseta...), I want to use my Django app as it's own Identity Provider (to maintain my custom-built registration and login flows) ...BUT I can't seem to find any resources/tutorials/examples of this being done. Specifically, I want my registered users to access my BetterMode instance via their "Custom Oauth2" option (Their support says they support my use case). Question: Are there Django libraries that support Django being it's own identity provider? Is this wildly uncommon for reasons I'm not seeing? Otherwise, is the solution just custom code with the django.authlib library? (ex: client_id/secret > Auth/token/callback_Urls...) -
using variable to reference Panda Column name in python
i'm trying to write a function to simplify my code, as a result i'm passing variables containing column names. its for a Django app and the debugger is not giving any feedback on where my error is, just 'internal server error'. My code works fine written NOT as function: df_trips['trip_time_prep_starts'] = df_trips["trip_time_prep_starts"].map(str) df_trips.trip_time_prep_starts = pd.to_datetime(df_trips.trip_time_prep_starts) df_trips['trip_time_left_house'] = df_trips['trip_time_left_house'].map(str) df_trips.trip_time_left_house = pd.to_datetime(df_trips.trip_time_left_house) df_trips['stage1_duration']=(df_trips['trip_time_left_house']-df_trips['trip_time_prep_starts']).dt.total_seconds() written as a function, passing the following variables: stage_name="stage1_duration" stage_start="trip_time_prep_starts" stage_end="trip_time_left_house" my function: def calc_stage_duration(df_trips, stage_name, stage_start, stage_end): df_trips[stage_start] = df_trips[stage_start].map(str) df_trips.[stage_start] = pd.to_datetime(df_trips.[stage_start]) df_trips[stage_end] = df_trips[stage_end].map(str) df_trips.[stage_end] = pd.to_datetime(df_trips.[stage_end]) df_trips[stage_name]=(df_trips[stage_end]-df_trips[stage_start]).dt.total_seconds() I can't find my mistake and I'm not clear on the proper use of brackets and periods, for example df_trip.[stage_end] versus df_trips[stage_end] -
Django nginx 502
Looking for a solution how to fix nginx 502 Bad Gateway with Django using Elastic Beanstalk. Django application is correct, locally everything works seamlessly. Problems occurs when I am trying to deploy that application to AWS EC2. I use AWS PostgreSQL Database. All environment variables are saved in AWS environments correctly. Have traversed through all solutions but, nothing helped. Is it ever possible that some libraries create a conflict that results 502 Bad Gateway? Using Python 3.11.9 **requitements.txt** asgiref==3.8.1 boto3==1.34.141 botocore==1.34.141 certifi==2024.7.4 charset-normalizer==3.3.2 colorama==0.4.6 crispy-bootstrap5==2024.2 Django==5.0.6 django-autoslug==1.9.9 django-crispy-forms==2.2 django-environ==0.11.2 django-mathfilters==1.0.0 django-storages==1.14.4 django-utils-six==2.0 djangorestframework==3.15.2 gunicorn==20.1.0 idna==3.7 jmespath==1.0.1 packaging==24.1 phonenumbers==8.13.40 pillow==10.3.0 psycopg2-binary==2.9.9 requests==2.32.3 s3transfer==0.10.2 six==1.16.0 sqlparse==0.5.0 tzdata==2024.1 urllib3==2.2.2 Then **.ebextensions/django.config** option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ecommerce.wsgi:application Then **Procfile** web: gunicorn ecommerce.wsgi:application --bind 0.0.0.0:8000 Then **ecommerce/ecommerce/wsgi.py** import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings") application = get_wsgi_application() Then **.ebignore** requirements.dev.txt .pytest_cache/ tests/ .pytest_cache/ *.test.py test_*.py *.local .env .env.example .git/ README.md .prettierignore .vscode/ .idea/ *.pyc __pycache__/ .mypy_cache/ .nox/ .coverage .tox/ .venv/ CMD Output: >eb logs Retrieving logs... =========================== ---------------------------------------- /var/log/web.stdout.log web[2267]: File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/gunicorn/util.py", line 359, in import_app -
Message delievering through local host of react app but not after deploying on netlify
I have a react app which is basically my portfolio app with backend made with django. But, the message is delievering through local host of react but after deploying it on netlify i am not able to deliever the message. i tried to use CORS_ALLOW_ORIGINS with specific list of my local host as well as of my backend server but still not working. The error on deployed app console is :- Blocked loading mixed active content “http://wahab901278.pythonanywhere.com/contact/submit/” index-DUkXO2lH.js:628:7274 Error: Network Error index-DUkXO2lH.js:631:4990 How to fix that anyone please assist -
Update columns of DataTable after having the data from server
I'm new at DataTables js, I need a solution for my problem. I have a Django app where I use DataTables with server-side processing, the table template is dynamic for all the models I have, I just pass the columns (a list of dicts with data, name and title) within the context of the template, pretty straightforward... def my_page_view(request): columns = generate_datatables_columns("MyModel") return render( request, "my_page.html", {"columns": columns} ) <script> $(document).ready(function() { var columns = []; {% for col in columns %} var jsObject = { {% for key, value in col.items %} "{{ key }}": "{{ value }}", {% endfor %} }; columns.push(jsObject); {% endfor %} var table = $('#my-table').DataTable({ "processing": true, "serverSide": true, "ajax": { "url": "/my/url", "type": "GET", }, "columns": columns, }); }); </script> <table id="my-table" class="display" width="100%"> <thead> <tr> {% for column in columns %} <th id="dt_col_{{column.data}}">{{ column.name }}</th> {% endfor %} </tr> </thead> </table> After that, I needed to make some changes on the columns, but depending on the data received, meaning I should be able to update my columns inside the DataTable definition after having the data. To make the idea clearer, the following code represents one of the attempts I tried, using ajax.dataSrc … -
How to properly load data into a ComboBox in Django with m3_ext and objectpack?
I am developing a Django application using m3_ext and objectpack for the UI components. I need to load ContentType objects into a ComboBox directly from the database. However, my current implementation is not working as expected. The combo box does not show the ContentType of an existing record when editing. You still can choose from combo box, but i really need existing value shoving in combo box for editing. from objectpack.actions import ObjectPack from objectpack.ui import ModelEditWindow, BaseEditWindow, make_combo_box from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission, Group, User from m3_ext.ui import all_components as ext class ContentTypePack(ObjectPack): model = ContentType add_to_desktop = True add_window = edit_window = ModelEditWindow.fabricate(ContentType) class PermissionEditWindow(BaseEditWindow): def _init_components(self): super(PermissionEditWindow, self)._init_components() self.field__name = ext.ExtStringField( label='Name', name='name', allow_blank=False, anchor='100%') self.field__content_type = make_combo_box( label='Content Type', name='ContentType', allow_blank=False, anchor='100%', data=[(ct.id, ct.model) for ct in ContentType.objects.all()]) self.field__codename = ext.ExtStringField( label='Codename', name='codename', allow_blank=False, anchor='100%') def _do_layout(self): super(PermissionEditWindow, self)._do_layout() self.form.items.extend(( self.field__name, self.field__content_type, self.field__codename, )) def set_params(self, params): super(PermissionEditWindow, self).set_params(params) self.height = 'auto' class PermissionPack(ObjectPack): model = Permission add_to_desktop = True add_window = edit_window = PermissionEditWindow def save_row(self, obj, create_new, request, context): obj.name = request.POST.get('name') content_type_id = request.POST.get('ContentType') if content_type_id: obj.content_type = ContentType.objects.get(pk=content_type_id) obj.codename = request.POST.get('codename') obj.save() return obj In edit window content type … -
A discussion on data fetching in Nextjs: Adding types to requests and response and using the fetch API
Context I've been building a web app with nextjs and a custom backend in Django Python and I've been struggling to find a clean way to make API requests to my backend from Nextjs. What I'm looking for is a way to centralise the logic for the fetch function while adding type safety to the request body and responses. Current approach const api = { get: async function (url: string): Promise<any> { console.log("get", url); return new Promise((resolve, reject) => { fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${url}`, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, cache: "no-store", }) .then((response) => response.json()) .then((json) => { console.log("Response:", json); resolve(json); }) .catch((error) => { reject(error); }); }); }, post: async function (url: string, data: any): Promise<any> { console.log("post", url, data); return new Promise((resolve, reject) => { fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${url}`, { method: "POST", body: JSON.stringify(data), headers: { Accept: "application/json", "Content-Type": "application/json", }, }) .then((response) => response.json()) .then((json) => { console.log("Response:", json); resolve(json); }) .catch((error) => { reject(error); }); }); }, } In this approach, I am centralising the logic for get and post requests in the sense that now I can just import api and call api.post/get to make a request to my backend. However, I don't like repeating code … -
ASGI for django not compatible with Server-sent-events?
I previously wrote an SSE (Server sent event) request using Django and it looked all right. def event_stream(): """ Generator function to yield messages. """ for i in range(10): yield f"data: Message {i}\n\n" time.sleep(1) # Simulate delay in message generation response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['Connection'] = 'keep-alive' return response Later, I installed channels because I needed to use websocket, and switched from WSGI to using ASGI. At this point, I noticed that the request was not returning properly, but was returning all the data at once at the end. I'm not sure what is causing this or how to fix it. python version:3.11.7 django version:5.0.6 channels version:3.0.5 -
Django deployment. Apache, wsgi, python 3.12
Everything worked fine on python 3.8, but I need to update python to version 3.12. libapache2-mod-wsgi-py3 apparently does not support version 3.12. After starting the server, I get the error module django not found. What should I do?) <VirtualHost *:443> DocumentRoot /.../back/... <Directory /.../back/.../.../...> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> <Directory /.../back/...> Require all granted </Directory> WSGIDaemonProcess ... lang='en_US.UTF-8' locale='en_US.UTF-8' python-path=/.../back/... python-home=/.../back/venv WSGIProcessGroup ... WSGIScriptAlias / /.../back/.../.../wsgi.py WSGIPassAuthorization On ServerName ... ServerAlias ... ErrorLog /.../back/logs/back-error.log CustomLog /.../back/logs/back-access.log combined SSLEngine on SSLCertificateFile "..." SSLCertificateKeyFile "..." SSLCertificateChainFile "..." </VirtualHost> -
drf and simplejwt error in coreapi : None type object has no attribute 'Field'
I have DRF project documented with drf_yasg and validator rest framework simple jwt. this is my requirements.txt file. File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\urls\accounts.py", line 5, in <module> from .. import views File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\views.py", line 4, in <module> from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_fra File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\views.py", line 4, in <module> from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_fra from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 21, in ObtainAuthToken coreapi.Field( ^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'Field' this is my requirements.txt file: # general modules django<4.3,>4.2 python-decouple Pillow # third party modules djangorestframework markdown django-filter drf-yasg[validation] djangorestframework-simplejwt[crypto] # deployment modules this is my created CustomObtainAuthToke class: class CustomObtainAuthToken(ObtainAuthToken): serializer_class = CustomAuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={"request": request} ) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return Response( { "user_id": user.pk, "email": user.email, "token": token.key, } ) and this is how I import that in line 4 from rest_framework.authtoken.views import ObtainAuthToken I tried to reversion the requirements.txt modules. I changed the DRF to different version for testing purposes to 3.12, 3.13, 3.14, 3.15 and the latest version … -
Invalid Token Error with Static Files in Django Template
I'm encountering an issue with my Django project where I'm trying to include a static CSS file in my HTML template. Despite trying multiple solutions, I keep getting the error: ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead. Here's my HTML template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Image</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <h1>This is a pic</h1> <img src="{% static 'images/pic.jpg' %}" alt="pic"> </body> </html> I getting this error on this line <link rel="stylesheet" href="{% static 'css/style.css' %}"> by hovering on this line on my editor(vs code). Solutions I've Tried: Placed {% load static %} at the top. Verified no syntax errors. Checked static settings in settings.py. Confirmed template backend setup. Ensured correct directory structure. Restarted server and cleared cache. -
How can I check if the item is the last item in the list in Django template?
While working on dictionaries, How can I check if the item is the last item in the list in Django template? dict = { "items":[3,4,7,0,6] } # I am mixing things here in my poor attempt {% with dict.items|length as range %} {% for i in range %} {% if i != range %} <a> dict.items[i] </a> {% elif i == range %} <a> Last item: dict.items[i] </a> # 6 {% endif %} {% endfor %} {% endwith %}