Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Containerized Django application works on local, but not on GKE
Any containerized Django applications work in local, but only return "no healthy upstream" when run on GKE. I tried with this django example: https://github.com/mukulmantosh/cloud-code-helloworld on which I only commented out the mysqlclient in the requirements.txt file. In GKE the application runs behind an ingress internal load balancer (I have no access to Cloud Run for some corporate reason). What I get in local mode: (base) C:\Users\path\to\app>docker run -p 8080:8080 helloworld:1 [21/Feb/2024 10:54:17] "GET / HTTP/1.1" 200 3968 [21/Feb/2024 10:54:17] "GET /static/KE-hello-world.svg HTTP/1.1" 200 116030 [21/Feb/2024 10:54:17] "GET /static/cloud_bg.svg HTTP/1.1" 200 7213 [21/Feb/2024 10:54:17] "GET /static/kubernetes-engine-icon.png HTTP/1.1" 200 6967 [21/Feb/2024 10:54:19] "GET / HTTP/1.1" 200 3968 What I get in the Workload logs on GCP: 2024-02-21 12:03:40.613 CET Not Found: / 2024-02-21 12:03:40.613 CET [21/Feb/2024 11:03:40] "GET / HTTP/1.1" 404 2272 -
Error when starting Django React app with npm start: "Invalid options object" ( 'Something is already running on port 5432' )
`I have a Django-React application with PostgreSQL/MySQL. The app was working fine, until today I attempted to start my frontend using npm start. This is the first time I've encountered the following prompt: ? Something is already running on port 5432. Would you like to run the app on another port instead? » (Y/n) Opting for 'Y' leads to the subsequent error: Would you like to run the app on another port instead? ... yes Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. options.allowedHosts[0] should be a non-empty string. I haven't made any recent changes or installations. What should I do ? I tried to change the start script in the package.json to "start": "set PORT=3000 && react-scripts start", but that didn't work. Additionally, I deleted node_modules, package-lock.json, and ran npm install, but I still got the same error message. -
python Django Field 'id' expected a number but got '{"isTrusted":true}'
mistake:Field 'id' expected a number but got '{"isTrusted":true}' When I attempt to perform the delete operation, an error is being reported, and I'm unsure how to resolve it. view.py class ClassAdminAPI(APIView): @validate_serializer(CreateClassSeriaizer) @super_admin_required def post(self, request): class_data = request.data class_data["title"] = class_data.get("title") class_data["start_time"] = dateutil.parser.parse(class_data["start_time"]) class_data["end_time"] = dateutil.parser.parse(class_data["end_time"]) class_data["created_by"] = request.user if class_data["end_time"] <= class_data["start_time"]: return self.error("Start time must occur earlier than end time") user_data = class_data.pop("users") try: with transaction.atomic(): if Class.objects.filter(title=class_data["title"]).exists(): return self.error("Class with the same title already exists") class_obj = Class.objects.create(**class_data) for data in user_data: if len(data) != 4 or len(data[1]) > 32: return self.error(f"Error occurred while processing data '{data}'") username = data[1] + data[2] user, created = User.objects.get_or_create(username=username, defaults={ "password": make_password(data[1]), "college": data[3], "student_number": data[1] }) if created: profile = UserProfile(user=user, real_name=data[2]) profile.save() class_obj.users.add(user) return self.success(ClassSerializer(class_obj).data) except IntegrityError as e: return self.error(str(e).split("\n")[1]) @super_admin_required def get(self, request): class_id = request.GET.get("id") if class_id: try: class_obj = Class.objects.get(id=class_id) ensure_created_by(class_obj, request.user) return self.success(ClassSerializer(class_obj).data) except Class.DoesNotExist: return self.error("Class does not exist") classes_obj = Class.objects.all().order_by("-create_time") # print("classes_obj:", classes_obj) if request.user.is_admin(): classes_obj = classes_obj.filter(created__by=request.user) print("classes_obj:", classes_obj) return self.success(self.paginate_data(request, classes_obj, ClassSerializer)) @super_admin_required def delete(self, request): Class_id = request.GET.get("id") if not Class_id: return self.error("Invalid Parameter, id is required") class_ids = Class_id.split(",") if Class.objects.filter(id__in=class_ids, created_by=request.user).exists(): return self.error("Current … -
Getting Forbidden (403) CSRF verification failed
I am using Django, DRF , docker, Nginx and AWS EC2 instance for my personal project, application is working fine when it is using HTTP , once i changed to HTTPS i am getting CSRF Verification Failed. used {% csrf_token %} where required in html forms in settings.py CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['http://localhost/', 'example.co.in', 'www.example.co.in'] CORS_ORIGIN_WHITELIST = ['http://localhost/', 'example.co.in', 'www.example.co.in'] Please help me in solving this issue, thank you everyone -
Zegocloud video call Recording issue
How to record video calls using zegocloud,i have created the server call backurl in the admin console but when i call the start record api endpoint of zegocloud its not start recording,Can any body help me to resolve the issue? -
Problem returning context_processor data to html for looping
I'm trying to add categories field to navigation. So far I've made context_processor which querys all the car brands. In my navigation I'm loopin all of the brands and this works. I also want to add dropdowns which contains certain car models for certain car brands. I think the problem lays in returning right data, that is loopable in my _base.html. _base.html <div class="flex pt-3 container w-full"> {% for item in car_brands %} <button id="dropdown-button" data-dropdown-toggle="dropdown-{{item.id}}" class="py-2.5 px-4 text-sm font-medium text-center text-gray-900 bg-gray-100 uppercase" type="button">{{item}}</button> <div id="dropdown-{{item.id}}" class="hidden shadow w-44 bg-gray-100"> <ul aria-labelledby="dropdown-button"> {% for model in models %} <li> <a href="#" class="inline-flex w-full px-4 py-2 hover:bg-gray-50">{{ model }}</a> </li> {% endfor %} </ul> </div> {% endfor %} context_processors.py from .models import CarBrandCategory, CarModel def brand_catalogue(request): car_brands = CarBrandCategory.objects.all() for brand in car_brands: models = [model for model in CarModel.objects.filter(brand_id=brand.id)] print(models) return { 'car_brands': car_brands, 'models': models } If printing, it will give me different lists, consists of different models, eg. [<CarModel: X4>, <CarModel: X5>, <CarModel: 3. Seeria>] [<CarModel: A4>, <CarModel: A6>, <CarModel: A8>] [<CarModel: C klass>, <CarModel: S-Klass>] I was wondering if anyone has experience with this kind of solutions and what could be the most optimal way to … -
Django Rest Framework Pagination isn't working
My settings.py: 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'authentication.authentication.ExpiringTokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } My views.py: permission_classes = [IsAuthenticated] queryset = Post.objects.all().order_by('-id') serializer_class = PostSerializer pagination_class = PageNumberPagination The code should show 10 result in each page. But it's showing all the 13 result. The result is like this: { "count": 13, "next": null, "previous": null, "results": [ { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_SJpZeBc.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_Fs2qSAY.webp", "order": 2 } ], "caption": "my name is ayon", "created_at": "2024-02-21T09:40:46.069468Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_AvXbLoq.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_lRnFcgd.webp", "order": 2 } ], "caption": "friends will be great", "created_at": "2024-02-21T09:40:40.146627Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_XcnIJ6o.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_MPj4huO.webp", "order": 2 } ], "caption": "friends", "created_at": "2024-02-21T09:40:36.631495Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_LdvliP2.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_nLRwhrS.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:33.934885Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_iFAk1XG.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_EEnnvOX.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:27.121978Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_IrIuNi9.jpeg", "order": 1 }, { … -
email activation failing in django
how im sending the activation email current_site = get_current_site(request) email_subject = 'confirm your email !' message2= render_to_string('authentication/emailConfirmation.html',{ 'name':user.first_name + user.last_name, 'domain':current_site.domain, 'uid':urlsafe_b64encode(force_bytes(user.pk)), 'token':generate_token.make_token(user)}) email= EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [user.email], ) email.send() the activate view from django.core.mail import send_mail ,EmailMessage from django.http import Http404, HttpResponse from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes , force_str from django.utils.http import urlsafe_base64_decode from . tokens import generate_token def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link")``` the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator()``` the confirmation email template {% autoescape off %} Confirmation Link: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} whenever i click on the confirmation link it automatically fails -
Django admin: exclude values from dropdown while keeping existing value
I have a site with conference rankings, where FoR codes are one of the fields. The database includes old FoR codes that are no longer used. I'd like to exclude these codes from the dropdown menu of the change form on the admin site, as it takes some scrolling to reach the current codes (screenshot). I tried excluding the old codes by overriding formfield_for_foreignkey, as seen in the below code snippet. However, if a conference entry with an old code is opened in the admin site, then the FoR code dropdown is cleared (screenshot). Is it possible to exclude the old FoR codes while still preserving the FoR code for old entries? In the example I linked above (1, 2), I want to preserve the 0905 code for this old entry, while only showing the current codes for new entries. class RankInline(admin.TabularInline): model = Rank extra = 1 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "for": kwargs["queryset"] = ForCode.objects.filter(code__startswith="46") return super(RankInline, self).formfield_for_foreignkey(db_field, request, **kwargs) class CommentInLine(admin.TabularInline): model = Comment extra = 0 class ConferenceAdmin(admin.ModelAdmin): list_display = ("acronym", "title", "url") list_display_links = ("acronym", "title", "url") search_fields = ("acronym", "title", "url") inlines = (RankInline, CommentInLine) -
How to connect from mobile phone to the localhost
I am developing a website on Django, the local version is run by development server (python manage.py runserver) on localhost. I can test my site in a browser, the address is http://127.0.0.1:8000/. But now I need to see how my website is looking on the mobile phone. My laptop OS is Linux Mint, the phone OS is Android, both are connected to the WiFi router. I tried this recipe. I found out my WLAN IP (by the command ifconfig), which happens to be 192.168.0.104. By the recipe, I should enter the address together with port number, which is, apparently, 8000 (according to the development server port, see the paragraph 1), so I should see my local website by the address 192.168.0.104:8000, both from the laptop and the phone browser. However, in both devices I get a following error (translated to English): Can not connect. Firefox cannot establish a connection to the server at 192.168.0.104:8000. The site may be temporarily unavailable or too busy. Please try again in a few moments. If you cannot load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure Firefox has permission to access … -
How to using multi router in django?
Currently, I'm using the Django Framework and have a large data block, a router. In Django Framework, how can I split data into subdatabases and use multiple routers??? I want to split the block of data into several parts. Thanks. -
How can I access The request.data Inside My post_save signal after creating the Model Objects
I want to create Projects with Documents But It took time So i wanna add document after creating the projects But I am giving Documents related details inside my request body # Define the signal receiver function @receiver(post_save, sender=Project) def attach_documents_to_project(sender, instance, created, **kwargs): if created: attachments_data = instance.request.data.get('document') -
Advanced search in django rest framework
I have a database containing lots of posts with a number of fields(title, content, tags). I want to build a search system to look for posts. It seemed really easy first but it turns out it is not. For instance, when I type 'how to' I want my system show posts containing at least one of the word('how' or 'to' or 'how to' is the best scenario) but the problem is when I type 'how to' my system searches for only posts containing 'how to' not 'how' or 'to'. Please help me to build the system. class PostsSearch(APIView): def get(self, request, format=None): search = request.GET.get('search') query = SearchQuery(search) vector = SearchVector('title') + SearchVector('tags__name') posts = Post.objects.prefetch_related('tags').annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.0001).order_by('-rank') serializer = PostsSerializer(posts, many=True) return Response(serializer.data) I tried the code I provided above but it does not work at all -
django email activation feature failing
the view def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link") the url path('activate/<uidb64>/<token>/',views.activate,name='activate'), the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator() the confirmation email is indeed being sent but whenever i click on that link i get this error ! -
trying to call Post.objects.filter(category=cats) in my view
im trying to call this method in my view: def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats': cats, 'category-posts': category_posts}) and i have the category defined in my model, but for some reason the error is creating a field in my Model called objects -
Javascript: Input value on fields and show value on popup
I have a registration form. After filling up the forms, the reference number will display in popup. A reminder for the user to use for logging in the system. register.html <div>Reference No.<input type="text" name="refno" value="{{ refno }}" readonly></div> <div>Name<input type="text" name="name"></div> ... <button type="submit" id="getInputValue()" class="btn">Submit</button> this is my script function getInputValue() { let textElement = document.getElementById('refno').value; alert(textElement); views.py if request.method == 'GET': random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) refno = f"{random_chars}" return render(request, 'registration_form.html', {"refno": refno}) if request.method == 'POST': refno = request.POST.get('refno') name = request.POST.get('name') ... Applicant.objects.create(refno=refno, name=name, ...) return redirect(/user_login/) So after the button was clicked, the msg should display the reference number before it proceed to the login form. So I'm a bit confused on how to show the popup first before login. If I write return render(request, 'registration_form.html'), it will just return to the form. With this code I have, it doesn't even show a pop up. Thank you in advance. -
I am trying to set up django channels for a chat feature in my web app but i am getting DLL import error
File "C:\Users\user.virtualenvs\cinemahub-_4auLGIo\lib\site-packages\cryptography\exceptions.py", line 9, in from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions ImportError: DLL load failed while importing _rust: The specified procedure could not be found. I uninstalled channels 3.0.5 and run python manage.py, the error disappeared. but the Asgi server wasnt showing on terminal. I installed channels 4.0.0 and Daphne but daphne causes the same error however when i remove daphne, the error disappears. I want the asgi server to show on the terminal. I aslo installed and uninstalled cryptography numerous times yet error still appears -
AWSApprunner not able to send email from django
When I try to send and email from django running on AWSAppRunner instance, the screen stays loading for a while and then it turns all white. If I open my debugger, I see a 502 network error: Origin checking failed {My DOMAIN APPEARED HERE } does not match any trusted origins. I Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins and I added these credentials mentioned in that stack page (CSRF_TRUSTED_ORIGINS,CORS_ORIGIN_WHITELIST, CORS_ALLOWED_ORIGINS, SECURE_PROXY_SSL_HEADER) and then got this error. Origin checking failed - null does not match any trusted origins. I do have the CSFR token on my html {% csrf_token %}. I know its the email because I comment that send_email function and everything works as expected. I verified the identities (from email and to email) in AWS SES. I installed SES with pip and added : EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-east-2' AWS_SES_REGION_ENDPOINT = 'email.us-east-2.amazonaws.com' I also have my access key, I was able to send the email using my localhost (My own computer running python manage.py runserver). I allowed all trafic in and out on the security group. What else can I try ? def nuevaorden_view(request): … -
Django unable to connect to PostgreSQL Docker container using hostname (WSL)
I'm facing an issue where my Django application, running on Windows Subsystem for Linux (WSL), can't connect to a PostgreSQL database running in a Docker container. The error I'm getting in Django is: django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known I'm starting the PostgreSQL container using the following Docker command: docker run --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=postgres -d postgres And this is my environment varaible in django: DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres How can I fix this? -
Django can't connect to Redis Server using Docker
I'm getting started with Docker. Trying to dockerize django application I am facing the problem with the connection to redis-server i ran from docker Here is the error it throws: Error 111 connecting to 127.0.0.1:6379. Connection refused. Docker-compose.yml: version: '3.8' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - '8000:8000' depends_on: - db - redis-server db: restart: always image: postgres ports: - '5432:5432' environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: Legal # volumes: # - pgdata:/var/lib/postgresql/data redis-server: image: "redis:alpine" command: redis-server networks: - djangonetwork volumes: prometheus_data: {} grafana_data: {} django_data: {} settings.py: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-server:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } CACHE_TTL = 60 * 30 -
Django channels - Not Found: /ws/stock/track/
I'm following this video, but I don't get the same console output as in the video. My console output: [20/Feb/2024 19:09:12] "GET /stocktracker/?stockpicker=AAPL&stockpicker=AMGN HTTP/1.1" 200 6449 Not Found: /ws/stock/track/ [20/Feb/2024 19:09:12] "GET /ws/stock/track/?stockpicker=AAPL&stockpicker=AMGN HTTP/1.1" 404 2613 Console output on local site (using py manage.py runserver): stockpicker=AAPL&stockpicker=AMGN stocktracker/?stockpicker=AAPL&stockpicker=AMGN:176 WebSocket connection to 'ws://127.0.0.1:8000/ws/stock/track/?stockpicker=AAPL&stockpicker=AMGN' failed: (anonymous) @ stocktracker/?stockpicker=AAPL&stockpicker=AMGN:176 asgi.py: """ ASGI config for backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ """ import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from Tradingapp.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ) }) routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ # Celery data is sent to a "group" and this group has multiple users #to listen for the same thing via websockets re_path(r'ws/stock/(?P<room_name>\w+)/$', consumers.StockConsumer.as_asgi()), ] JS connection: const roomName = JSON.parse(document.getElementById('room-name').textContent) var queryString = window.location.search queryString = queryString.substring(1) … -
Web server with NGINX, Gunicorn (with workers > 1), and Djagno fails to save JWT in a cookie at server side
I have a WSGI Django application, with Gunicorn before it and Nginx as a web server. The Django Application is a Stateless DRF API. Django Related Configs REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'wird-jwt-auth', 'JWT_AUTH_REFRESH_COOKIE': 'wird-jwt-refresh', 'JWT_AUTH_RETURN_EXPIRATION': True, 'JWT_AUTH_HTTPONLY': False, "SESSION_LOGIN": False, "USER_DETAILS_SERIALIZER": "core.serializers.PersonSerializer", "PASSWORD_RESET_SERIALIZER": "core.util_classes.PasswordResetSerializer" } SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_HSTS_SECONDS = 2_592_000 SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" # Application definition SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' PERMISSIONS_POLICY = {"fullscreen": "*", } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', "django.contrib.postgres", 'member_panel.apps.StudentConfig', 'admin_panel.apps.AdminPanelConfig', 'core.apps.CoreConfig', 'rest_framework', "rest_framework.authtoken", 'django.contrib.sites', 'allauth', 'allauth.account', 'dj_rest_auth.registration', 'django_filters', 'corsheaders', 'polymorphic', 'drf_yasg', "cachalot", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django_permissions_policy.PermissionsPolicyMiddleware", 'django.middleware.locale.LocaleMiddleware', 'allauth.account.middleware.AccountMiddleware', ] Nginx Configs upstream app { server localhost:8200; } server { server_name .; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://app; 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_redirect off; } location /static/ { alias .; try_files $uri $uri/ =404; } location /media/ { alias .; try_files $uri $uri/ =404; } listen 443 ssl; # managed by Certbot # ssl files } When Gunicorn's workers are >1 the JWT Token I save at Client side disappear after the first refresh. When workers=1 … -
MacOS Django Less Issue
I used Django to use Less on my Windows computer without any issues, but when I switched to MacOS, the system reported an error enter image description here StaticCompilationError at /friendLink node:fs:1336 handleErrorFromBinding(ctx); ^ Error: ENOENT: no such file or directory, mkdir '/static/styles/less/global' at Object.mkdirSync (node:fs:1336:3) at module.exports.sync (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/node_modules/make-dir/index.js:97:6) at ensureDirectory (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:172:7) at writeOutput (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:230:7) at /Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:311:9 { errno: -2, syscall: 'mkdir', code: 'ENOENT', path: '/static/styles/less/global' } Step: pip install django-static-precompiler npm install less -g Django setting.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_PRECOMPILER_OUTPUT_DIR = '' Django templates: {% load compile_static %} {% load static %} ... <link rel="stylesheet" href="{% static "styles/less/global/components.less"|compile %}"/> I am certain that the Django project has this folder/static/styles/less/global enter image description here I thought it was a permission issue $ where lessc /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc sudo chmod +x /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc But it's useless I also tried PyCharm's File Watcher settings But it shouldn't be a problem. When I write a less file and save it, CSS will still appear Is it a problem with NVM, django static precompiler configuration, or macos? I'm not sure -
django if any of many to many has filed with value of False
Say I have a model of a library and I want to hide some books if either the book is marked as hidden or any of authors is marked as hidden or any of categories is marked as hidden. class Category(CustomModel): name = models.CharField(max_length=32, unique=True, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Person(CustomModel): first_name = models.CharField(max_length=64, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Book(CustomModel): title = models.CharField(max_length=128, null=False, blank=False) authors = models.ManyToManyField(Person, null=False, blank=False) translators = models.ManyToManyField(Person, null=True, blank=True) ... categories = models.ManyToManyField(Category, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) Now I tried these queries to exclude all books with either, is_hidden=True, authors__is_hidden=True, translators__is_hidden=True, or categories__is_hidden=True: as this: books = Book.objects.filter( is_hidden=False, authors__is_hidden=False, translators__is_hidden=False, categories__is_hidden=False).distinct() and this: books = Book.objects.filter( is_hidden=False, authors__is_hidden__in=[False], translators__is_hidden__in=[False], categories__is_hidden__in=[False]).distinct() but I cannot find a way to achieve it. I wish to achieve my goal without a loop since the number of entries can get as high as 80K. How to make the query? -
Problems with implementing logout functionallity
i am trying to implement logout but everytime it throw [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 if i try to logout trough drf view by clicking on admin -> logout it has the same error [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 questionTime/urls.py from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.auth.views import LogoutView from django.urls import include, path, re_path from django_registration.backends.one_step.views import RegistrationView from core.views import IndexTemplateView from users import views as ws from users.forms import CustomUserForm urlpatterns = [ path('admin/', admin.site.urls), path( "accounts/register/", RegistrationView.as_view(form_class=CustomUserForm, success_url="/",), name="django_registration_register",), path("api-auth/logout/", auth_views.LogoutView.as_view(), name="rest_logout"), path('logout/', LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path("api/v1/", include("questions.api.urls")), path("api-auth/logout/", LogoutView.as_view(), name="rest_logout"), re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"), ] settings.py LOGOUT_URL = '/logout/' LOGOUT_REDIRECT_URL = "/" it should log out user