Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to connect my backend to my frontend
EditTransaction.js import React, { useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; export default function EditTransaction() { const params = useParams() const [initialData, setInitialData] = useState() const [validationErrors, setValidationErrors] = useState({}) const navigate = useNavigate() function getTransaction() { fetch("http://127.0.0.1:8000/transactions/" + params.id) .then(response => { if (response.ok) { return response.json() } throw new Error() }) .then(data => { setInitialData(data) }) .catch(error => { alert('Unable to read the Transaction details') }) } useEffect(getTransaction, [params.id]) async function handleSubmit(event) { event.preventDefault() const formData = new FormData(event.target) const Transaction = Object.fromEntries(formData.entries()) if (!Transaction.name) { alert("Please fill the Name field") return } try { const token = '852de93b4848505296fb5fe56e41a6d1501adfca'; const response = await fetch("http://127.0.0.1:8000/transactions/" + params.id, { method: 'PATCH', body: formData, headers: { 'Authorization': `Token ${token}` }, }); const data = await response.json() if(response.ok){ //Transaction Created Correctly! navigate('/admin/transaction') } else if (response.status === 400){ setValidationErrors(data) } else( alert('Unable to Update Transaction') ) } catch(error) { alert('Unable to connect to the server') } } return( <div className="container my-4"> <div className="row"> <div className='col-md-8 mx-auto rounded border p-4'> <h2 className= "text-center mb-5">Edit Transaction</h2> <div className="row mb-3"> <label className='col-sm-4 col-form-label'>ID</label> <div className= 'col-sm-8'> <input readOnly className='form-control-plaintext' defaultValue={params.id}/> </div> </div> { initialData && <form onSubmit={handleSubmit}> <div className="row … -
Images do not appear on a page even though they are already in a DB (Django)
I try to learn how to deploy my django project. I have a form in which user can upload his image. The image is a content for ImageField of a Recipe model. Uploading process is working as expected but when I try to display these pictures on the page they just dont appear. Here's my code: settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py (project one): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('user_auth.urls')), path('main/', include('main_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class Recipe(models.Model): author = models.ForeignKey(UserExtended, on_delete=models.CASCADE, related_name='recipies') title = models.CharField(max_length=150, null=False) category = models.ForeignKey(RecipeCategory, related_name='recipies', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to="images/", null=False) short_description = models.CharField(max_length=250, null=False) tutorial = models.TextField(null=False, default='') uploaded_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(UserExtended, related_name='liked_recipies') likes_count = models.SmallIntegerField(default=0) def __str__(self): return f'{self.author} {self.title}' example of my template: <img class="full-recipe-image" src="{{ recipe.image.url }}" alt="Фото блюда"> Any help would be a blessing to me since I'm pretty desperate. I tried to alter my urls.py and was struggling with MEDIA_ROOT / MEDIA_URL problem -
404: NOT_FOUND error on Vercel - Django deployment
I deployed a Django project on Vercel and it shows the deployment is successful. However, when I try to open the website, it shows the error: 404: NOT_FOUND Code: NOT_FOUND ID: lhr1:lhr1::6n29s-1732227821846-0cc9eddbb440 My Django project can be found in the following link: https://github.com/RailgunGLM/railgunglm-com I tried solving the problem by, as some solutions on stackoverflow suggested, inserting a vercel.json file and a build.sh file, adding the line app = application at the very end of wsgi.py, including .vercel.app in my ALLOWED_HOSTS in setting.py, and lastly, installed whitenoise. However, none of them seems to work. The application works normally in my local machine, but I'm not sure whether I made a mistake in one of these files. I would be really appreciated if there is a solution to fix this problem. -
Changing the session key to a different user model field
I have my own user model. Django derives the session key from the primary key in this model. However, I wish to use a different field as the primary key / session key. The problem with changing the primary key is that it will break existing logged in sessions since the Django session middleware code tries to convert the session key to the type of the primary key defined in the model. I wish to change from username to a uuid. I thought I could work around this by having different auth backends since the session stores the backend but this type conversion occurs before Django calls the get_user method in my custom backends. Is there a way to uses a new field as the primary key? -
Constraint to forbid NaN in postgres numeric columns using Django ORM
Postgresql allows NaN values in numeric columns according to its documentation here. When defining Postgres tables using Django ORM, a DecimalField is translated to numeric column in Postgres. Even if you define the column as bellow: from django.db import models # You can insert NaN to this column without any issue numeric_field = models.DecimalField(max_digits=32, decimal_places=8, blank=False, null=False) Is there a way to use Python/Django syntax to forbid NaN values in this scenario? The Postgres native solution is to probably use some kind of constraint. But is that possible using Django syntax? -
DRF serializer missing fields after validation
I have a simple DRF serializer: class CustomerFeatureSerializer(serializers.Serializer): """ Serializer for a customer feature. """ feature_id = serializers.CharField() feature_value = serializers.SerializerMethodField() feature_type = serializers.CharField() name = serializers.CharField() def get_feature_value(self, obj): """ Return the feature_value of the feature. """ return obj.get("feature_value", None) the feature_value field is a method field since it can be either a boolean, an integer, or a string value (so for now I just kept it as a method field to fetch the value). I am using this to serialize some objects that I am hand-generating (they do not correspond 1:1 with a model) but for some reason after validation the name and feature_value fields are just completely disappearing. for feature in toggleable_features: display = { "feature_id": feature.internal_name, "name": feature.name, "feature_value": profile.feature_value(feature) if profile.has_feature(feature.internal_name, use_cache=False) else False, "feature_type": feature.type, } features.append(display) print(display) print(features) serializer = CustomerFeatureSerializer(data=features, many=True) print(serializer.initial_data) serializer.is_valid(raise_exception=True) print(serializer.validated_data) return Response(serializer.validated_data) and the print statements output: {'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'} [{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}] [{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}] [OrderedDict([('feature_id', 'feat-id'), ('feature_type', 'boolean'), ('name', 'feat name')])] the value is just gone. Any idea why this could be happening? Is the object I am … -
Django SSL Redirect causing local development connection issues in Chrome
After setting SECURE_SSL_REDIRECT=True in my settings.py but False in my environment variables for local development and restarting the server and browser I cannot connect to my website via local host and get the You're accessing the development server over HTTPS, but it only supports HTTP. [21/Nov/2024 11:28:50] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03èª\x19óÆð?ë-\x99âÆH\x13V\x08{zm') error. It works when I open it incognito and in other browsers but not in the current browser(Chrome). Here is my settings.py: SECRET_KEY = env.str("SECRET_KEY") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) SECURE_HSTS_SECONDS = env.int("DJANGO_SECURE_HSTS_SECONDS", default=2592000) SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) SESSION_COOKIE_SECURE = env.bool("DJANGO_SESSION_COOKIE_SECURE", default=True) CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=True) Environment variables: DEBUG=True SECRET_KEY=bTU5cQLjBGapg3d......mrVglq1CEhbk DJANGO_SECURE_SSL_REDIRECT=False DJANGO_SECURE_HSTS_SECONDS=0 DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False DJANGO_SECURE_HSTS_PRELOAD=False DJANGO_SESSION_COOKIE_SECURE=False DJANGO_CSRF_COOKIE_SECURE=False I've deleted cookies for both localhost and 127.0.0.1, restarter Chrome and still had the same error in the end. -
How to run django-ckeditor-5 with docker container
I have a django app and I installed the module django-ckeditor. I can run the app with the command: python manage.py runserver without any problems. But after I build the docker container with the command: docker-compose -f docker-compose-deploy.yml up I get this errors: import_module("%s.%s" % (app_config.name, module_to_search)) web-1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web-1 | return _bootstrap._gcd_import(name[level:], package, level) web-1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import web-1 | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load web-1 | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked web-1 | File "<frozen importlib._bootstrap>", line 680, in _load_unlocked web-1 | File "<frozen importlib._bootstrap_external>", line 850, in exec_module web-1 | File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed web-1 | File "/usr/src/app/DierenWelzijnAdmin/admin.py", line 17, in <module> web-1 | from ckeditor.widgets import CKEditorWidget web-1 | ModuleNotFoundError: No module named 'ckeditor' web-1 | [2024-11-21 15:50:43 +0000] [7] [INFO] Worker exiting (pid: 7) web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Worker (pid:7) exited with code 3 web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Shutting down: Master web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Reason: Worker failed to boot. I added ckeditor in settings.py file: INSTALLED_APPS = [ 'django_ckeditor_5' I added ckeditor in requirements.txt file: django-ckeditor-5==0.2.15 I … -
Is there any way to get the windows user id in Django API
I am writing a Django API which will be hosted on IIS server and will be called from Angular Front end. I am trying to get the Windows User name who is calling my API. I am no finding any way for doing this. I tried multiple options like request.user, REMOTE_USER etc. None of them are working. They are giving Anonymous User always. Please help me with step by step process. I tried request.user object. This always gives AnonymousUser. I tried Remote_USER option as well but no luck. I am expecting to get user name of windows login. -
Django Test Environment Runs Twice and Fails When Using if not IS_PRODUCTION and INJECT_FAKE_DATA
Description: I'm encountering a strange issue in my Django test environment. When running my test suite, the environment appears to initialize twice, causing a specific test to pass the first time and fail on the second run. The problem seems to be related to the following conditional statement in my settings.py file: if not IS_PRODUCTION and INJECT_FAKE_DATA: # Code for injecting fake data Environment Details: Django version: 5.1.1 Python version: 3.12.1 Test Framework: pytest with pytest-django Database: MongoDB for test What Happens: When I run my tests, the environment is reloaded twice (as evidenced by logs). On the first initialization, everything works as expected, and the test passes. On the second run, the same test fails due to the environment not behaving as intended. INFO:C:\path\to\settings.py changed, reloading. INFO:INJECT_FAKE_DATA is True. INFO:Fake data mode activated. INFO:Watching for file changes with StatReloader ... Performing system checks... System check identified no issues (0 silenced). ... First run: test passes. Second run: test fails with inconsistent state. and PS C:\Users\Chevr\OneDrive\Bureau\eOnsight\eOnsightApi\eonsight-api> pytest app_auth ============================================================= test session starts ============================================================== platform win32 -- Python 3.12.1, pytest-8.3.3, pluggy-1.5.0 django: version: 5.1.1, settings: eOnsight_api.settings (from ini) rootdir: C:\Users\Chevr\OneDrive\Bureau\eOnsight\eOnsightApi\eonsight-api configfile: pytest.ini plugins: Faker-30.0.0, django-4.9.0, factoryboy-2.7.0, mongo-3.1.0 collected 2 items app_auth/tests/test_auth_viewset.py::test_login … -
Django devserver load once
I am trying to develop a django application it use paddelocr take sometime to initiate. so when ever I am trying to change something and test it I have to wait 5 sec for the paddleocr to initiate again. Is there a way to load the model only once when i start the dev server and not everytime I make some changes. I have tried adding the model initalization in the setting.py assuming that it will only run only that didn't work. I have also tried one of gpts suggestion of using thread but no luck so far -
ModuleNotFoundError: No module named 'pageflows.website'
I am making a project in Django, and trying to optimise my code and trying to implement Don't repeat techniques. Here I have three class with same functions in it, which I am calling. I put these functions into utils.py file ad just used there names in context after importing them in my views. In those functions I am using the models to get the data, I have imported them in utils but after all this it raises an error **ModuleNotFoundError: No module named 'pageflows.website' ** I don't get it why this error occured? Kindly help me out in this. I don't get it why this error occured? Kindly help me out in this. -
Celery picks up new tasks, but all old are stuck in PENDING
In a nutshell: I'm able to run new celery tasks but the old ones are stuck with PENDING states. Celery run command: celery -A config.celery_app worker --pool=solo --loglevel=info Environment: Celery 5.4.0 redis-server 7.4.1 on WSL (Windows Linux) The celery and Django app runs on windows and the redis-server in WSL. I ran celery a couple of times and everything was good, but now I constantly see some old tasks as "PENDING" state when I read their state in Django with AsyncState(task_id). Purging the queue with celery -A config.celery_app purge didn't make anything either. I visited a couple of threads on this, but none seem to be dealing with my precise problem. (I'm still able to execute new tasks) I wonder if it's not a problem with running on WSL or something like this, because I'm also unable to see the task queues from the app or CLI: celery inspect active_queues gives kombu.exceptions.OperationalError: [WinError 10061] No connection could be made because the target machine actively refused it and doing: i = app.control.inspect() scheduled = i.scheduled() shows no tasks Project is built with django-cookiecutter and Celery task was basically defined as: @app.task def my_task(**kwargs): return my_function(**kwargs) -
django asgi raised django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I want to build a Django app with django-channels. But when I run the following command: daphne -b 0.0.0.0 -p 8010 paya.asgi:application It gives me this error: Apps aren't loaded yet. This error occurs when I add the following line to the consumer.py: from Auth.models import Store consumers.py: import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from Auth.models import Store class ChatConsumer(WebsocketConsumer): def connect(self): self.user = self.scope['url_route']['kwargs']['sender'] self.store = self.scope['url_route']['kwargs']['receiver'] self.user_store_group = f'store_{self.user}_{self.store}' async_to_sync(self.channel_layer.group_add)( self.user_store_group, self.channel_name ) self.accept() #self.sotreUser = Store.objects.get(id=self.store) #data = [json.dumps({'name': 1, 'productId': 2, 'receiver': self.sotreUser.user.username})] #self.send(text_data=data) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) print(text_data) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'add_order', 'message': text_data_json } ) def add_order(self, event): message = event['message'] self.send(text_data=json.dumps({ 'message': message })) asgi.py: import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from django.urls import path from chat.consumers import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( [path('ws/chat/<str:sender>/<str:receiver>/', ChatConsumer.as_asgi()),] ) ), }) setting.py: INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', ] ASGI_APPLICATION = 'paya.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, },} DATABASES = { 'default': { 'ENGINE': … -
Use existing page for error 404/505 in Wagail
I am using the most recent version of Wagtail, 6.3.1 at this time. I want to use a specific page for an error 404 and error 500 so I can have it in line of the rest of website. I created two views: class Error404View(View): def get(self, request, *args, **kwargs): site_settings = SiteSettings.for_request(request) if site_settings.error_404_page: serve = site_settings.error_404_page.serve(request, *args, **kwargs) return serve else: return HttpResponseNotFound("NOT FOUND") class Error500View(View): def get(self, request, *args, **kwargs): site_settings = SiteSettings.for_request(request) if site_settings.error_500_page: return site_settings.error_500_page.serve(request, *args, **kwargs) else: return HttpResponseServerError("INTERNAL SERVER ERROR") (I know I will also to override the HTTP return code in the serving). And in urls.py configured these: handler404 = Error404View.as_view() handler500 = Error500View.as_view() if settings.DEBUG: # Error test pages urlpatterns += [path("404/", Error404View.as_view())] urlpatterns += [path("500/", Error500View.as_view())] But the output of those pages is simply: <!DOCTYPE HTML> <html lang="nl" dir="ltr"> <head> <title>Office365</title> </head> <body> <h1>Office365</h1> </body> </html> (I selected the content page titled Office365 for the sake of testing). I found this related question on SO but it is from many versions ago so perhaps it does not apply anymore: Wagtail: render a page programmatically in a Class Based View So; how can I get the content of that specified page … -
Django: Objects that live throughout server lifetime
I have some data in csv format that I need to load into the application once and then reuse it throughout the lifetime of the application, which is across multiple requests. How can I do that? An obvious method for me is to have a module that will load the data and then expose it. However, I don't like modules doing a lot of work, because then imports lead to unexpected side effects. I would like to do that one-time work in a predictable, deterministic fashion, not because someone imported a module. Does Django provide some hooks for globals? Some kind of Application/Service class where I could do that work and then access the data in the requests? -
Unable to save user model with new data
Django 4.2.5, python 3.11, saving to mysql db. I am trying to update the "chat_user_status" field for my "Teacher" model, which extends the abstract User model. Model.py code for Teacher: class TeacherProfile(models.Model): teacher = models.OneToOneField( UserProfile, related_name='teacher', primary_key=True, parent_link=True, on_delete=models.CASCADE) chat_user_status = models.BooleanField(default=False, verbose_name='Chat Status') def save(self, *args, **kwargs): identity = self.teacher.email friendlyName = self.teacher.first_name + \ ' ' + self.teacher.last_name super(TeacherProfile, self).save(*args, **kwargs) Views.py (Teacher model) login code that is trying to update the chat_user_status field, and nothing is updating, and no error: def login_user(request): logout(request) email = password = '' if request.POST: email = request.POST['email'] password = request.POST['password'] user = authenticate(username=email, password=password) if user is not None: if user.is_active: login(request, user) if is_teacher(user): user.chat_user_status=True user.save() Views.py relevant code from my chat app that is trying to save the data def update_chatuser_status(uid): user_profile = UserProfile.objects.get(id=uid) teacher_profile = None try: teacher_profile = TeacherProfile.objects.get(teacher_id=user_profile.id) except: pass if teacher_profile != None: teacher_profile['chat_user_status']=False teacher_profile.save() There is no change to the field 'chat_user_status' after calling save(). There is no error message. I have searched other answers, either they don't work, or are irrelevant. -
Django 2 DB columns as FK to the same related table
I have a table 'Athletes' and another table 'Parents'. Table fields are: ATHLETES reg_number first_name last_name gender age_group (as FK to AgeGroup) parent_1 (as FK to Parents using related_name='parent_1') parent_2 (as FK to Parents using related_name='parent_2') PARENTS first_name last_name email phone I have this working in the admin console where I can add parents to athletes. I have a form that will display the related parents for each athlete. Issue is trying to update the parent for a given athlete. POST has correct IDs for parent_1 and parent_2 but I get the following error within browser ValueError at /save_athlete Cannot assign "'1'": "Athletes.parent_1" must be a "Parents" instance. POST has the following data showing in the payload id: 1 reg_number: 12345 group: 2 first_name: amy last_name: small gender: Female parent_1: 1 parent_2: 2 I don't understand the error so not sure what code would be useful to post here. I had expected that the parent_1 and parent_2 values (ids) would be accepted when the form validates but it throws an error in views.py -
Difference between Apple Sign-In Token Request: /auth/token vs /auth/keys
I am working on a Flutter + Django REST Framework application and implementing Apple Sign-In functionality. When Iam tried to manually obtain the user's access_token, I followed the flow where needed to generate a client_secret on the backend (it was a JWT built using values like KEY_ID, TEAM_ID, CLIENT_ID, and CLIENT_SECRET from APPLE DEVELOPER account). I would then send the authorization_code (received from flutter), client_secret(genereted by developer on backend), and other details to https://appleid.apple.com/auth/token to get the access_token. However, when integrating the same Apple Sign-In functionality using the drf-social-oauth2 library for Django, I noticed that I no longer need to use all those keys and secrets (like KEY_ID, TEAM_ID, CLIENT_SECRET etc.). Instead, it only requires the CLIENT_ID and identity_token that I receive from the Flutter app, and it sends a request to https://appleid.apple.com/auth/keys, which returns the access_token without needing the authorization_code from Flutter. So, what is the difference between these approaches? In both cases, I get an access_token (although access_tokens have different expiration times), but the only thing is that in one case, I don't need all those keys, and in the other, I do. -
Count distinct on an aggregated dimension
I have the following model: class Historique(models.Model): type_of_object_choices = ( (1, 'Cadeau') , (2, 'Offre') , (3, 'Commentaire') ) event_type_choices = ( (1, 'modification') , (2, 'creation') , (4, 'suppression') ) wishlist = models.ForeignKey(Wishlist, on_delete=models.CASCADE) type_of_object = models.IntegerField(choices=type_of_object_choices, null=True) event_type = models.IntegerField(choices=event_type_choices) object_pk = models.IntegerField() How do I express in a "Django" type of way the following SQL query? SELECT type_object , CASE WHEN sum_event_type in (1) THEN 'modification' WHEN sum_event_type in (2, 3) THEN 'creation' WHEN sum_event_type in (4, 6) THEN 'supression' END as type_of_action , COUNT(DISTINCT object_pk) as nb_objects FROM ( SELECT type_object , object_pk , sum(event_type) as sum_event_type FROM wishlist_historique GROUP BY type_object, object_pk ) as temp GROUP BY type_object , CASE WHEN sum_event_type in (1) THEN 'modification' WHEN sum_event_type in (2, 3) THEN 'creation' WHEN sum_event_type in (4, 6) THEN 'supression' END I have been trying different solutions based on annotate and aggregate but all faied. -
Gunicorn on Apache Server not serving static files in Django project: "Not Found" error for /static/
I’m running a Django project using Gunicorn and Apache with mod_wsgi, but Gunicorn is not serving the static files correctly. When I try to load my page, I get errors like: Not Found: /static/css/style.css Not Found: /static/js/app.js In browser console I get Refused to apply style from 'http://localhost/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Additionally, when I try to access the static files directly (e.g., http://localhost:9090/static/css/style.css), I get a 404 error. The static files are correctly configured in the Django settings, but Gunicorn is not able to locate them. Environment: Django version: 5.1 Gunicorn version: 20.x.x Apache version: 2.4.x mod_wsgi version: 4.9.0 Operating System: Ubuntu 20.04 Python version: 3.10 Running inside a virtual environment Django Static Configuration (settings.py): STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'app/static')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'userentry', //my django app ] Current Setup: Apache is proxying requests to Gunicorn. Static files are collected in the STATIC_ROOT directory using python manage.py collectstatic. I have confirmed that the static files are located at /app/static/ on the server. My apache virtualhost: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName localhost ProxyPass / … -
Django - Failed Login Redirecting To Different Page
I am new to Django and I am trying to use the authentication system. I have managed to get it working using the default Auth URLS. (/accounts/login) etc. I want to get a login form on my homepage so it is always available to unauthenticated users. I have managed to display the form, and when a user enters correct details, the login is successful. Unfortunately when the user enters wrong information it is currently redirecting me to the login url (accounts/login) I have been trying to rectify this, but I either break the auth or it redirects, I cannot seem to find a solution. Views.py: def index(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = AuthenticationForm() return render(request, 'home.html', { 'form': form }) HTML template: <form class="p-4 p-md-5 border rounded-3 bg-body-tertiary" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-floating mb-3"> <input class="form-control" id="{{ form.username.id_for_label }}" name="username" type="text" /> <label for="{{ form.username.id_for_label }}">{{ form.username.label }}</label> </div> <div class="form-floating mb-3"> <input class="form-control" id="{{ form.password.id_for_label }}" name="password" type="password" /> <label for="{{ form.password.id_for_label }}">{{ form.password.label }}</label> </div> {% if form.errors %} <div class="justify-content-center d-flex w-75 mt-1 mb-1 alert alert-danger border-0"> <small class="text-center mx-4">Your Username and … -
Django QuerySet performance
I'm debugging sitemap generation, and finally have the following snippet: items=Event.objects.all() for limit in (1000, 10000, 20000): events=items[:limit] print(f'{limit=}') start=time() for obj in events.values('id', 'slug', 'date_updated'): s='/events/{0[slug]}_{0[id]}_{0[date_updated]}/'.format(obj) print(f' Time spent: {time()-start:.2f}') start=time() for obj in events.only('slug', 'date_updated'): s=f'/events/{obj.slug}_{obj.pk}_{obj.date_updated}/' print(f' Time spent: {time()-start:.2f}') And I have the following output: limit=1000 Time spent: 0.26 Time spent: 9.80 limit=10000 Time spent: 0.66 Time spent: 85.09 limit=20000 Time spent: 1.18 Time spent: 177.20 I see in the doc that QuerySet.values() is recommended for few fields and when you don't need the complete Model behaviour, which is indeed the case here. But is the overhead of creating Model instances (and whatever more there is under the hood) indeed SO huge? Or it's something about my setup and (mis)configuration. When it's doing models, I see both python and mysql processes consume CPU. And it's inexplicable, because same query when I run it in mysql client takes half a second. -
Get currenty logged in user in Django/Angular
I am creating a Django / Angular project but I am having an issue. In normal django applications without frontend framework we can just do request.user and we can get the iformation needed. I already created the api endpoints to my User model but is there a way to directly find the user Id to make a call like this: getUserById(userId: number): Observable<User> { const url = `${this.baseUrl}users/${userId}/`; return this.http.get<User>(url); } Or do I need to set up a different serializer like this for example: class CurrentUserView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = request.user # Get the current logged-in user serializer = UserSerializer(user) return Response(serializer.data) make a call to this endpoint and then with the data from here access the rest of the endpoints? Also right now I havent set up an Authentication mechanism. Maybe in the future if I do I wont be needing an endpoint like this? Thanks in advance -
Django HTTPS with nginx as reverse proxy. Issues with CSRF tokens
I developed a Django application which runs inside a docker container. Outside the container, a natively runnign nginx does the reverse proxy-ing of the requests that django application. Django runs via WSGI with gunicorn. General setup: I use a HTTP sever on port 80 which only serves a redirect to HTTPS on Port 443. No data is actually served on that port. Port 443 is setup for HTTP/2 with SSL encryption Path /static is served by nginx to supply static django data. Path / is configured as proxy to the django instance: location / { proxy_set_header Host $http_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://127.0.0.1:8000; # This is the port the docker container with my django listens to } Django is configured with the following options: # Production only settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = False I set the SECURE_SSL_REDIRECT to false, as I have a server internal healthcheck that accesses the django application on http://localhost:8000 and checks its status. As there is not HTTPS on that route, a forced SSL redirect would break that check. I rely on the strict configuration of nginx that an outside access can never occur via HTTP …