Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django: how to "expand" a field which references an enum but not another table
I have a main table "PfPersona" with a field "stato_civile" that takes 1 char (the "key" of an enum). For this example let's say the enum has only one value. In DB the value would be "S". Is the definition of the enum correct? class StatoCivile(Enum): S = "value" And in my main model I would reference the enum like this: stato_civile = models.CharField(StatoCivile,max_length=1, blank=True, null=True, db_column='stato_civile') In the serializer of the main model I already have many expandable fields and they all work because they have an actual FK. I tried to put also "stato_civile" to make it expandable. expandable_fields = { "otherfield" : OtherFieldSerializer, . . "stato_civile":StatoCivileSerializer } I tried to define the StatoCivileSerializer class StatoCivileSerializer(serializers.ModelSerializer): class Meta: model = StatoCivile fields = ['name']#not sure what field I should define If I call the URL with "stato_civile" as an expandable field like this http://localhost:8000/pf/?expand=stato_civile I have this error in __getattr__ raise AttributeError(name) from None AttributeError: _meta Basically I didn't understand how to manage Enums because all the other expandable fields I have work thanks to the fact that they have an actual ForeignKey. -
How to resolve Third-Party Login Failure
I am having trouble using Github as third party for logging in to an app. I am getting this error (page): Third-Party Login Failure An error occurred while attempting to login via your third-party account. My alluth version: django-allauth==65.2.0 Project's settings.py: INSTALLED_APPS = [ ... # third-party apps "allauth_ui", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.github", "widget_tweaks", "slippers", ] SOCIALACCOUNT_PROVIDERS = { "github": { "VERIFIED_EMAIL": True } } All settings in django admin's social application's entry are properly setup (i.e. Client ID and Secret Key). All matching correctly what was setup when creating the Github Apps... -
Deployed Krakend Django microservice not receiving any input data given in json body
I have a Django application deployed with Krakend gateway. All endpoints are active. But the service is unable to access the request data. I'm giving the request as below curl --location 'https://backend-dev-url.com/api' \ --header 'Content-Type: application/json' \ --data '{ "a":"value", "b":"value" }' This is the response that i get { "a": [ "This field is required." ], "b": [ "This field is required." ] } I'm passing all the missing variables correctly. But somehow it is not reaching the service. It works perfectly on localhost. The issue is only with the deployed instance. Below is the krakend configuration part for this microservice { "endpoint": "api/v1", "method": "POST", "output_encoding": "no-op", "backend": [ { "url_pattern": "api/v1", "encoding": "no-op", "sd": "static", "method": "POST", "host": ["http://localhost:8000"], "disable_host_sanitize": false } ], "input_headers": ["Authorization","Content-Type"], "extra_config": { "qos/ratelimit/router": { "max_rate": 100, "client_max_rate": 60, "every": "1m", "strategy": "ip" } } } Thanks. -
Template Syntax Error when using Django allauth
I encountered this error when trying to improve the UI of login and signup pages.. TemplateSyntaxError at /accounts/logout/ 'slippers' is not a registered tag library. Must be one of: account admin_list admin_modify admin_urls allauth allauth_ui cache i18n l10n log socialaccount static tz widget_tweaks i had already installed the following packages: django-allauth==65.2.0 django-allauth-ui==1.5.1 django-widget-tweaks==1.5.0 contents of project's settings.py: INSTALLED_APPS = [ ... # third-party apps "allauth_ui", "allauth", "allauth.account", "allauth.socialaccount", "widget_tweaks", ] I just tried to reinstall the packages and it's still Template Error :( -
sort and search functionality not working together
i have the following search and sort functions in my javascript file and the following html file Javascript file document.addEventListener('DOMContentLoaded', function () { const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0]?.value; const resultsListFW = document.getElementById('list-results-fw'); const listFW = document.getElementById('list-fw'); const searchInputFW = document.getElementById('search-input-fw'); function renderFWData(data) { resultsListFW.innerHTML = ''; // Clear previous results let counter = 1; data.forEach(item => { const row = ` <tr> <td>${counter}</td> <td>${item.customer}</td> <td><a href="detail/${item.pk}" target="_blank">${item.name}</a></td> </tr> `; resultsListFW.insertAdjacentHTML('beforeend', row); counter++; }); listFW.classList.add('not-visible'); resultsListFW.classList.remove('not-visible'); } // FW: Perform search function performFWSearch(query) { fetch('/fw_search', { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrfToken }, body: new URLSearchParams({ fw: query }) }) .then(response => response.json()) .then(data => { renderFWData(data.data); }) .catch(error => { console.log('Error fetching FW data:', error); }); } }); document.addEventListener('DOMContentLoaded', () => { const table = document.getElementById('fw-table'); const headers = table.querySelectorAll('th[data-sort]'); const tbody = table.querySelector('tbody'); headers.forEach(header => { header.addEventListener('click', () => { const sortKey = header.getAttribute('data-sort'); const rows = Array.from(tbody.querySelectorAll('tr')); // Determine sorting order const order = header.dataset.order === 'asc' ? 'desc' : 'asc'; header.dataset.order = order; // Sort rows rows.sort((a, b) => { const aText = a.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim(); const bText = b.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim(); if (!isNaN(aText) && !isNaN(bText)) { // Numeric comparison return order === 'asc' … -
Django How to update the session cart icon after admin delete a product
I have two apps in my project one is call store and the other is call cart in store I have all the models and in cart I have all the cart functionality. The call is handle using session when admin delete a product the cart icon count is like if the product has not been deleted from the session however the summary html show up the rights products in the cart (it doesn't include the deleted one but the cart icon show up a quantity that is wrong). how can I update the icon with the right quantity once admin delete the product, the cart need to be refresh and I have used a post_delete signal for this but it seems not to be working. this is my code cart/signals.py from django.db.models.signals import post_delete from django.dispatch import receiver from store.models import Product from django.contrib.sessions.models import Session @receiver(post_delete, sender=Product) def update_cart_on_product_delete(sender, instance, **kwargs): # Get all sessions sessions = Session.objects.all() for session in sessions: cart = session.get_decoded().get('cart', {}) if cart: # Check if the deleted product is in the cart if str(instance.id) in cart: del cart[str(instance.id)] # Save the updated cart back to the session session.get_decoded()['cart'] = cart session.save() -
Error: connect ECONNREFUSED ::1:8000 in Nuxt 3
I’m working on a Nuxt 3 project and encountering the following error: [nitro] [unhandledRejection] connect ECONNREFUSED ::1:8000 This error occurs when I try to make API requests to my backend during development. I suspect it’s related to the frontend (Nuxt 3) server not running or being misconfigured, but I’m not sure how to resolve it. It happen when I try to get tokens from the backend when the app start. So I try to call the backend in middleware/auth.global.ts and in plugin/initail.ts like this to make sure that user token is set to the state (I am using Pinia for state management) import useAuthStore from "~/store/useAuthStore"; export default defineNuxtRouteMiddleware(async () => { const authStore = useAuthStore(); if (!authStore.isAuthenticated) { // Call the backend here await authStore.checkAuthState(); } }); import useAuthStore from "~/store/useAuthStore"; export default defineNuxtPlugin(async (nuxtApp) => { const authStore = useAuthStore(); authStore.checkAuthState(); }); My checkAuthState() is like this : try { // Attempt to refresh the token if access is empty const axiosApi = axios.create({ baseURL: "http://localhost:8000/api", headers: { "Content-Type": "application/json", 'Accept': 'application/json', }, withCredentials: true, withXSRFToken: true, timeout: 10000, }); await await axiosApi.post('/token/refresh/'); } catch (error) { console.error("Error refreshing token:", error); this.authenticated = false; return; } Here’s some … -
Cuncurrency, mutex, semaphores on django and a cron job
I want to create a critical section in django provide controlled section. One of this is in one of the django channels consumers handling the websocket connections and the other is in a cron process implemented with cron tab, not celery. I would like these both critical sections to have a lock. How would I implement this in django. I know there is python Value,Semaphores, Mutexs but I can not pass the Value to cron job. So Can I use some sort of a file lock. Maybe interprocess communication lock, if that exists. Anythoughs on how to archive this in Django -
Coverage: How to gracefully stop a Django development server that runs on a Github Action Instance
I am testing some API endpoints of my Django app by running Playwright separately on a Ubuntu machine on my Github Action instance. Since I also want to get the coverage of the tests, I am starting my server this way: - name: run backend server run: poetry run coverage run ./manage.py runserver --no-reload This results in a single process being started. Now, in order to collect the coverage data, I need to gracefully stop my django server, as force killing the process would also interrupt coverage and executing coverage combine would produce an error. I have tried the following commands, but they all fail to stop the server kill -SIGINT $DJANGO_PID kill -SIGTERM $DJANGO_PI pkill -f "./manage.py runserver" python -c "import os; import signal; print(os.kill($DJANGO_PID, signal.SIGTERM))" Is there a different approach I can use ? or maybe I am starting the server the wrong way?