Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing clients card Django
I need to store customer loyalty cards. It should be flexible. I have several variants of cards with different discount systems. For example, the card by amount of purchases - > $100 - 5%, > $1000 - 10%, etc. Or by amount of visits - > 10 - 3%, 100 - 10%, etc. Furthermore, it should store the different image for different types of cards and sales amount, for example 5% - silver colour, 10% - gold, etc. I came up with the idea of storing in in database as JSON. Visits for example: schema = {1: {'discount': 5%, image: '....', 'style': {'background': ..., 'foreground': ...}, 2: {'discount': 10%, image: '....', 'style': {'background': ..., 'foreground': ...}, 3: {'discount': 15%, image: '....', 'style': {'background': ..., 'foreground': ...}, } class ABSCard(models.Model): title = field work_place = field .... class Discount(models.Model): type = .... schema = JSONField abscard_id = ABSCard But I'm not sure that storing JSON in PostgreSQL is the best way. -
Prevent async task from being executed before the rest of the code on Django
Please help me here. This is my django admin class: My problem is, the check_sync_available validation is not working properly because the async task sync_development (redis/celery) is being executed BEFORE the requests.get according to the logs, how can I prevent that? I've tried to use transactions.oncommit and lots of other things and nothing works. class CourseAdmin(nested_admin.NestedModelAdmin): class Meta: model = Course fields = '__all__' actions = ["sync_course_development"] def sync_course_development(self, modeladmin, request, queryset): api_url = f'https://lalala.lalala.la/check_sync_available/' response = requests.get(api_url, headers={'Content-Type': 'application/json'}) if response.status_code != 200: modeladmin.message_user(request, f'A sync is already in progress, try again later.', messages.ERROR) return None else: print(f"Sync available: {response.status_code}") for course in queryset: sync_development.apply_async([course.id]) modeladmin.message_user(request, f'Courses syncing in background. Please reload the page in a while.', messages.SUCCESS) This is the log so you can see what I'm talking about. Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,694: WARNING/ForkPoolWorker-7] Point 765/3802 - Percentage: 19.89245930284848 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,696: WARNING/ForkPoolWorker-7] Point 766/3802 - Percentage: 19.91905538924079 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,698: WARNING/ForkPoolWorker-7] Point 767/3802 - Percentage: 19.945522992123962 Jun 12 18:31:59 ip-xxx-xx-xx-xx web: [2024-06-12 18:31:59 +0000] [5952] [INFO] Booting worker with pid: 5952 Jun 12 18:32:01 ip-xxx-xx-xx-xx web: [2024-06-12 18:32:01 +0000] [5906] [INFO] Autorestarting worker after current request. … -
Centrifugo Django. disconnect after handling command reason="bad request"
I am trying to follow this tutorial: But after following all of the steps I do not see any messages and have this in my centrifugo logs: 2024-06-12 20:42:18 [INF] disconnect after handling command client=5bf22df5-8051-463b-9c41-4a6e9d92865a command=id:6 reason="bad request" user= It seems that it occurs when centrifuge.connect() is executed (in chat.templates.chat.rooms.html file). Here are logs from NGINX container: 192.168.65.1 - - [12/Jun/2024:17:44:26 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:30 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:42 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:44 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:58 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:45:01 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 … -
window.addEventListener('scroll', function() {
I'm working on the front end through Django WebFramework and PyCham, but infinite scrolls are not properly applied It is a page that fetches and displays public data APIs. Even if the scroll is stuck to the floor, more content does not come out. my html templates {% extends 'base.html' %} {% load static %} {% block content %} <section> <div class="mainpage_content_container"> <div class="section_wrap"> <div class="slick_container"> <div><img src="{% static 'img/gucciSeoul.jpeg' %}" alt=""></div> <div><img src="{% static 'img/korean_mood1.jpeg' %}" alt=""></div> <div><img src="{% static 'img/white_cow.jpeg' %}" alt=""></div> <div><img src="{% static 'img/colorful.jpeg' %}" alt=""></div> <div><img src="{% static 'img/6.25.jpeg' %}" alt=""></div> <div><img src="{% static 'img/seoulcity.jpeg' %}" alt=""></div> </div> </div> <div class="content_container"> <div class="content_wrap"> <ul> {% for image_info in image_info_list %} <li> <div class="img_wrap"> <img src="{{ image_info.file_url }}" alt="{{ image_info.art_name }}" style="max-width: 300px; min-height: 350px"> <div class="img_info"> <p><strong>작품명 :</strong>{{ image_info.art_name }}</p> <p><strong>일련번호 :</strong>{{ image_info.artCd }}</p> <p><strong>작품가격 :</strong>{{ image_info.price }}</p> </div> </div> </li> {% endfor %} </ul> {% if art_list %} <h2>검색 결과</h2> <ul> {% for art in art_list %} <li> <p>작품 번호: {{ image_info.artCd }}</p> <p>작품명: {{ image_info.art_name }}</p> <p>이미지: {% if art.image_url %} <img src="{{ art.image_url }}" alt="작품 이미지"> {% else %} 이미지 없음 {% endif %} </p> </li> {% endfor %} </ul> {% else … -
Django docker error with Postgres django.core.exceptions.ImproperlyConfigured
Good day. I'm having problems comunicating django app (local) and postgres db (docker ) The db work fine with adminer. But when I try the credentials that I use in adminer... Boom! ...env\Lib\site-packages\django\db\backends\postgresql\base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module SETTINGS DATABASES = { 'default': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") }, 'kettle': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME_KETTLE"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") } } ENV DB_ENGINE='django.db.backends.postgresql' DB_NAME='database' DB_USER='postgres' DB_PASSWORD='1234' DB_HOST='db' DB_PORT='5432' DB_NAME_KETTLE='kettle' ADMINER_PORT=8080 VIRTUAL ENV asgiref==3.8.1 certifi==2024.6.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.8 Django==4.2.3 django-cors-headers==4.2.0 djangorestframework==3.14.0 idna==3.7 psycopg==3.1.19 psycopg2==2.9.6 psycopg2-binary==2.9.6 pycparser==2.22 PyJWT==2.3.0 python-dateutil==2.9.0.post0 python-dotenv==1.0.0 pytz==2024.1 requests==2.31.0 six==1.16.0 sqlparse==0.5.0 typing_extensions==4.12.2 tzdata==2024.1 urllib3==2.2.1 and in my docker , postgres is in the port 5432:5432 -
Objects are displayed below the form field drowdown
I have created a form which is creating a new object of a model in which there is one field which is dropdown as it is a foreign key in model but the objects are also displayed below the field along with the dropdown. Model: class Vehicle(models.Model): type = models.ForeignKey(VehicleType, on_delete=models.CASCADE) number = models.CharField(max_length=10) View: def request_cabbie_upgrade(request): if request.method == 'POST': vehicle_form = VehicleForm(request.POST) if vehicle_form.is_valid(): vehicle = vehicle_form.save(commit=False) vehicle.save() cabbie_request = CabbieRequest(user=request.user, vehicle=vehicle) cabbie_request.save() return redirect('PassengerDashboard') else: vehicle_form = VehicleForm() return render(request, 'users/cabbie_request.html', {'vehicle_form': vehicle_form, 'user': request.user}) Form: class VehicleForm(forms.ModelForm): type = forms.ModelChoiceField(queryset=VehicleType.objects.all(), empty_label="Vehicle Type") class Meta: model = Vehicle fields = ['type', 'number'] Template: {% extends "base.html" %} {% block title %} <title>Cabbie Dashboard</title> {% endblock title %} {% block body %} <div class="container mt-5 pt-5 cabbie-dashboard-container"> <div class="row"> <div class="col-md-12"> <h2>Cabbie Information</h2> <div class="card"> <div class="card-body"> <p><strong>Username:</strong> {{ cabbie.username }}</p> <p><strong>First Name:</strong> {{ cabbie.first_name }}</p> <p><strong>Last Name:</strong> {{ cabbie.last_name }}</p> <p><strong>Email:</strong> {{ cabbie.email }}</p> <p><strong>Phone:</strong> {{ cabbie.phone }}</p> </div> </div> </div> <div class="col-md-12 mt-4"> <h2>Request Cabbie Upgrade</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="id_type">Vehicle Type:</label> {{ vehicle_form.type }} </div> <div class="form-group"> <label for="id_number">Vehicle Number:</label> {{ vehicle_form.number }} </div> <button type="submit" class="btn btn-primary">Submit Request</button> </form> </div> … -
How to Make Django Model Choice Field Accept Multiple Criteria
With a model defined as such class Product(models.Model): code = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=100) # intended to be left as NOT unique I would like to pick a product by either its code or its name. For example, if Product 1's code is SUS304 and name Stainless Steel 304, type SUS304 or Stainless Steel 304 in the form should both select this product. I try to use a union queryset as source queryset, but Django complains that .filter after .union is not supported. class OrderForm(forms.ModelForm): codes = Product.objects.annotate(full=F('code')) names = Product.objects.annotate(full=F('name')) product = forms.ModelChoiceField(codes.union(names), to_field_name='full') class Meta: # Order is another model that have a ForeignKey to Product model = Order fields = ['product'] How can I achieve this (especially in Django's way)? PS1. It is possible that multiple products share the same name, or one product's name is another's code. In such case, I would expect a ValidationError. PS2. Despite the length limit, there is no effective way to determine if a given string is a code or a name. SUS304 could also be a product's name. -
Does wagtail support dynamical definition of Search and Social Previews or Slug?
Is there any system in wagtail where you can dynamically define Search and Social Previews or Slug. so for example that it goes details/1/ where one would represent certain ID. so it would be details/{id} I wonder is this possible. If this is not possible is it possible somehow to define query in route? Thanks in advance guys. Currently I am solving this problem with keeping in session my id and using it later in my blocks.py but I would like for the Id to be vissible in the route. Example: https://www.my-website.com/orders/2/ Where 2 would be dynamically forwarded. -
Should I subclass my django model or not?
I'm creating a simple forum app in order to learn django. The idea is to create as much a full featured forum as I can over time, but for now this is what I have: class Post(models.Model): post_body = models.TextField(max_length=2000) publish_date = models.DateTimeField("date posted") author = models.TextField(max_length=200) # link to User model later class Meta: abstract = True # Post that starts a thread class ThreadPost(Post): post_title = models.Charfield(200) is_solved = models.BooleanField("is_issue_solved", default=False) class ReplyPost(Post): is_solution = models.BooleanField("is_this_the_solution", default=False) thread_post = models.ForeignKey(ThreadPost, on_delete=models.CASCADE) I'm unsure if this this is overdoing it a bit. ThreadPost and ReplyPost are so similar. Should I instead just create two separate classes which are unrelated through inheritance? Should I just have one Post class and just make the post_title optional when it's a reply? I guess the singular Post class would have to have a recursive relation too in that case (0 to N). Also, in future I want to add other features like reactions (e.g. thumbs up/down, laugh etc.), ability to report a post etc. Which I think could be a seperate model that links Post and User and would have its own fields. I wonder what approach would be best to keep the … -
Invalid model reference ‘my.guru.Comment_ref_comments’. String model references must be of the form ‘app_label.ModelName’
Ive got this problem here. I will paste in my code too. After looking through the internet, I found this error, but only for custom User models. In my example I have a simple Comment model: class Comment(models.Model): author = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT) published = models.DateField(auto_now_add=True) hidden = models.BooleanField(default=False) content = models.TextField() ref_comments = models.ManyToManyField('self', blank=True, related_name="comment_relation", default=None) parent = models.ForeignKey('self', default=None, null=True, on_delete=models.SET_DEFAULT) level = models.SmallIntegerField(default=1) no_of_reactions = models.IntegerField(default=0) def delete_tread(self): self.delete() orphans = Comment.objects.filter(parent=None) for com in orphans: if not com.get_blog() and not com.get_vlog() and not com.get_popPost() and not com.get_article(): com.delete() def get_article(self): if self.article_relation.all(): return self.article_relation.all()[0] else: return None def get_blog(self): if self.blog_relation.all(): return self.blog_relation.all()[0] else: return None def get_vlog(self): if self.vlog_relation.all(): return self.vlog_relation.all()[0] else: return None def get_popPost(self): if self.pop_relation.all(): return self.pop_relation.all()[0] else: return None def __str__(self): return self.content Error message: File “/workspaces/coachGu-live/guru/models.py”, line 100, in class Comment(models.Model): File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/base.py”, line 160, in new new_class.add_to_class(obj_name, obj) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/base.py”, line 325, in add_to_class value.contribute_to_class(cls, name) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 1585, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 1052, in create_many_to_many_intermediary_model lazy_related_operation(set_managed, klass, to_model, name) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 80, in lazy_related_operation return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 78, in model_keys = (make_model_tuple(m) for m in models) … -
Django many to many nested serializer
Hi i have a class widgets which can have multiple cameras and multiple analysis related to it. i want to return the cameras and widgets related as an object because if we delete the cameras the i want to get [{camera: null}] class CameraWidgetSerializer(serializers.ModelSerializer): class Meta: model = CameraWidget fields = ('camera',) class AnalysisWidgetSerializer(serializers.ModelSerializer): class Meta: model = AnalysisWidget fields = ('analysis',) class WidgetSerializer(ModelSerializerWithValidation): cameras = CameraWidgetSerializer(many=True) analyses = AnalysisWidgetSerializer(many=True) these are the simplified modals class CameraWidget(models.Model): """ Association class used to link between cameras and widget """ camera = models.ForeignKey( Camera, models.SET_NULL, help_text='The camera related to the widget', related_name='cameras_widgets', blank=False, null=True ) widget = models.ForeignKey( Widget, models.CASCADE, help_text='The widget containing the camera', related_name='cameras_widgets', blank=True, null=True ) class Widget(models.Model): analyses = models.ManyToManyField(Analysis, through='AnalysisWidget') cameras = models.ManyToManyField(Camera, through="CameraWidget") i managed to do this by seperating input and output this way cameras_ids = serializers.PrimaryKeyRelatedField(queryset=Camera.objects.all(), many=True, write_only=True) cameras = serializers.PrimaryKeyRelatedField(queryset=Camera.objects.all(), many=True, write_only=True) but i want the get and post to have the same structure, meaning "cameras" in both requests body while keeping DRF validation for these fields -
Django cache requests and only allow refresh daily
So I have this Admin dashboard for an e-commerce website where there are all kinds of statistics about sales and customers. Now this data is hosted in AWS RDS and the dashboard is made with django templates. So logically whenever the admin goes to this page it gets refreshed and it queries the AWS RDS. Now this data does not change in real-time the dashboard data gets updated daily in the database (this is done with dbt so this has nothing to do with django) so it doesnt make sense to run these queries multiple times a day because the data will not change on the dashboard. So what I need is something to cache the data once the admin goes to this dashboard and then invalidate the cache at say midnight. Anyone has done something like this or has any advice on how to create something like this? Thanks in advance for all replies! -
vscode run django test with database running in docker container on host
My settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.testing.unittestArgs": [ "-v", "-s", ".", "-p", "test_*.py" ], "python.testing.pytestEnabled": false, "python.testing.unittestEnabled": true, "[python]": { "editor.defaultFormatter": "ms-python.autopep8", "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": "explicit", "source.fixAll": "explicit" }, "editor.rulers": [ 80, ] }, "black-formatter.args": [ "--line-length", "80" ], "python.analysis.autoImportCompletions": true, "python.analysis.typeCheckingMode": "off", "python.envFile": "${workspaceFolder}/.vscode/.env", // "isort.args":["--profile", "black"] } I see all tests in Test explorer. I have test postgres database running in a docker container outside of vscode in network host mode on ubuntu. I have .vscode/.env file with all env variables needed to run a test case. When I run a test from test_explorer I get error django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_category_name_key" DETAIL: Key (name)=(Admin) already exists. If I try running the same test case through Run and debug using following launch.json file - it works successfully { "version": "0.2.0", "configurations": [ { "name": "Django test", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "test", "app1.tests.test1.test_abc", "--keepdb" ], "django": true, "envFile": "${workspaceFolder}/.vscode/.env", "console": "integratedTerminal" } ] -
Django - NoReverseMatch at /carro/
I'm learning how to make a basic e-commerce site, but I have this problem that appears when I add a product in the cart. I tried everything (I think) but still can't make this cart to work. It seems that the argument for "id_producto" is not reaching to nowhere. URLS.PY from django.conf import settings from django.urls import path from .import views app_name = "carro" urlpatterns = [ path('', views.detalle_carro, name='detalle_carro'), path('add/<str:id_producto>/', views.carro_mas, name='carro_mas'), path('remove/<str:id_producto>/', views.carro_menos, name='remover_carro'), ] VIEWS.PY from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.views.decorators.http import require_POST from gestionPedidos.models import Producto from .carro import Carro from .forms import anadirProductoForm #aqui va el form cupon @require_POST def carro_mas(request, id_producto): carro = Carro(request) producto = get_object_or_404(Producto, id_producto=id_producto) form = anadirProductoForm(request.POST) if form.is_valid(): cd = form.cleaned_data carro.anadir(producto = producto, cantidad=cd['cantidad'], update_cantidad=cd['update']) messages.success(request, "vamooo") return redirect('carro:detalle_carro') def carro_menos(request, id_producto): carro = Carro(request) producto = get_object_or_404(Producto, id=id_producto) carro.remover(producto) return redirect('carro:detalle_carro') def detalle_carro(request): carro = Carro(request) for item in carro: item['update_cantidad_form'] = anadirProductoForm(initial = { 'cantidad' : item['cantidad'], 'update' : True }) return render(request, 'detalle_carro.html', {'carro' : carro}) my template {% extends 'base.html' %} {% load static %} {% block title %}Mi carrito de compras!{% endblock %} {% block first_content %} … -
How to know user is online/offline with django channels?
With Django Channels, can you track which users are online or offline throughout your website? Should every page have a websocket connection? And when a user is online/offline, how can I show the user online/offline in real time. I have no idea. I only do group chats online users but cant do user online/offline in full website -
systemctl and uwsgi issue for remote django app
when I run uwsgi manually with uwsgi --ini uwsgi.ini command, it runs properly, but when I run sudo systemctl start uwsgi it will run properly (i.e., journalctl -b -u uwsgi or sudo systemctl status uwsgi won't show any errors) but I will get 500 error for all API calls. The errors do not happen when I run the server manually. And the uwsgi.service file worked fine until this morning so I don't know what is happening all of a sudden. help me please? The remote server is an ubuntu machine. I tried relaxing the permissions of related files/directories etc, doesn't work. When I check the uwsgi log it says that django app was not found, but I'm pretty sure the env files/variables are correctly configured. It works fine when I run uwsgi manually too. Set PythonHome to /home/ubuntu/venv3.9 *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x557b93f7ebf0 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 145840 bytes (142 KB) for 1 cores *** Operational MODE: single process *** Traceback (most recent call last): File "/home/ubuntu/[app]/wsgi.py", line 14, … -
Google Assistant being extremely intrusive in my Django website
I have a homepage where the text - when clicked triggers Google Assistant to translate it, and this is very bad experience for the user. I have tried to set the website language so GoogleAssistant don't just translate/define english words. and have tried the following snippets but in vain. no-translate <html lang="en"> What else possibly I can do this avoid this sh*t. [ sorry I'm really tired of this so called 'Assistant' ]Website homepage with Django I expected to work "normally" but anytime a word or text is clicked Google Assistant gets into play. -
Django object.values with alias / translation?
Is it possible to use something like an alias name for a django model attribute and a translation too? For example, one has a model like this: class TestModel(models.Model): field1 = models.CharField( args="Source (U)ID", max_length=150, help_text="Some helptext", ) field2.... field3.... Now you access the model in a view like this: transactions = ( Transaction.objects.all() ) transactions.values( Id=F("field1"), Json=F("field2"), BookingDate=F("field3"), ) Here we use an alias, but I have to specifically pick the values by hand and set them every time. Is there a better way to do that? A translation would be very useful too, since the data will be passed to a template and a table will be rendered with the data. So there is no good way to do it in the templates since the template doesn't know what fields it gets. It just renders what it gets. So the translation has to happen in the view/model somehow. Thanks! -
WebSocket connection to 'wss://example.com/wss/' failed in Django Channels
I'm trying to set up a WebSocket connection using Django Channels in my Django project. However, I keep encountering an error when trying to connect from the frontend JavaScript. The error message in the browser console is: WebSocket connection to 'wss://example.com/wss/' failed Here is my project structure: project/ ├── myproject/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ ├── asgi.py ├── myapp/ │ ├── __init__.py │ ├── views.py │ ├── urls.py │ ├── consumers.py │ ├── routing.py │ ├── templates/ │ ├── index.html ├── manage.py ├── passenger_wsgi.py ├── requirements.txt My settings.py includes: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ] ASGI_APPLICATION = 'myproject.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } The asgi.py file is configured as follows: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import myapp.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( myapp.routing.websocket_urlpatterns ) ), }) My routing.py: from django.urls import path from . import consumers websocket_urlpatterns = [ path('wss/', consumers.LoadConsumer.as_asgi()), ] The consumer class in consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer class LoadConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): pass … -
Invalid client in django-oauth-toolkit v2 that was valid in v1
I'm running seasonal upgrades on a project and noticed django-oauth-toolkit stayed a 1.7.1 last time. The upgrade to 2.x turns two tests from 200 to 401, invalid_client. One of these tests looks like this; @pytest.fixture def oauth_data(db): test_region = Region.objects.create( name="MyRegion", iso_code_short="MYR", iso_code_long="MYREG" ) app_owner = USER_MODEL( username="app-owner", email="owner@somewhere.com", gender="M", date_of_birth="1970-1-1", region=test_region, first_name="John", last_name="Doe", ) app_owner.set_password("password") app_owner.save() app_redirects = "http://site1.com/return\r\nhttp://site2.com/back" app = Application.objects.create( name="My Test Client", client_id="test-app", client_secret="password", client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, user=app_owner, skip_authorization=True, redirect_uris=app_redirects, ) return {"app": app, "app_owner": app_owner} # some test class here... def ( self, oauth_data, client, settings ): mixin = AccessTokenGeneratorMixin() tokens = mixin.get_access_token(oauth_data["app"], oauth_data["user"]) url = reverse("oauth2_provider:token") response = client.post( url, data={ "client_id": oauth_data["app"].client_id, "client_secret": oauth_data["app"].client_secret, "grant_type": "refresh_token", "refresh_token": tokens["refresh_token"], }, ) assert 200 == response.status_code Is there something in v2 (that I've missed in the release notes) that invalidates this fixture to create an invalid client!? -
Django unable to destroy test DB
I made a REST framework project in Django using Docker. All of the tests passed without issue. Then I had to move the project "out" of Docker. Not sure if this is an important detail, but just in case. I created a PostgreSQL on Aiven and connected my project to it. It all works, except one test fails and also, after running them, I get this message: File "/Users/john/programation/python3/recipe-app-api-out/recipe_env/lib/python3.12/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError: cannot drop the currently open database Do you know why this is happening now? I'm also not sure if the test failing and the dropping issue have to do. The test failing creates and uploads an image, and then tries to delete it with the TearDown method. Let me know if there is some specific part of the code I should share to add useful context to the question. -
Getting error for django and react native code Forbidden (CSRF token missing.):
I am working on a Django backend to handle some data manipulation, specifically appending and deleting data. My code works perfectly when tested with Postman, but I encounter a 403 Forbidden error when trying to access the /bookings/remove/ endpoint from my React Native frontend. Here's the error message I receive: Forbidden (CSRF token missing.): /bookings/remove/ "POST /bookings/remove/?booking_id=148/ HTTP/1.1" 403 Interestingly, all other endpoints are working fine without any CSRF-related issues. It's only this specific endpoint that is causing problems. Django Backend i have my settings for cors as follows: INSTALLED_APPS = [ 'corsheaders', "all other apps" ] SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_AGE = 1209600 CORS_ALLOW_ALL_ORIGINS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } and my endpoint for which i am getting error is @api_view(["POST"]) @permission_classes([IsAuthenticated]) @csrf_exempt def cancel_the_booking(request, booking_id): try: if not booking_id: return Response({"error": "Booking ID is required"}, status=status.HTTP_400_BAD_REQUEST) booking = Booking.objects.get(booking_id=booking_id) if booking.host_id != request.user.id: return Response({"error": "You are not authorized to cancel this booking", "host": request.user.id}, status=status.HTTP_403_FORBIDDEN) for date_price in booking.dates_price.all(): AdSpaceDates.objects.create( ad_space=booking.space_id, available_from=date_price.available_from, available_to=date_price.available_to, price=date_price.price ) booking.delete() return Response({"success": "Booking cancelled and dates are now … -
How to add multiple forms to Django view if one is ChatGPT input?
I like to add two separate forms into one view what is not a big deal but I can't find where is the stuff what makes an error and both of the forms works not. This is the first time I'm integrating ChatGPT and I'm not so familiar with fetch api. After posting I get no error message from the http request form just not saving the data. ChatGPT form say: An error occurred. Please try again. (I changed the names and id's so if it ot consistent here, in my server it causes no problems) views.py def add_new_stuff(request, company_uuid, position_id): form = AddStuffFrom(request.POST) if request.method == "POST" : if 'chatGptSubmitBtn' in request.POST: try: data = json.loads(request.body) user_input = data.get('user_input', '') if user_input: chatgpt_response = get_chatgpt_response(user_input) return JsonResponse({'response': chatgpt_response}) return JsonResponse({'error': 'No user input provided'}, status=400) except json.JSONDecodeError: return JsonResponse({'error': 'Invalid JSON'}, status=400) if 'stuffSubmitBtn' in request.POST: if form.is_valid(): form.save() context = { 'form': form, 'company_uuid': company_uuid, 'uuid': company_uuid, 'position_id': position_id, } return render(request, 'stuff/add_new_stuff.html', context) html <form id="openai_form" method="post"> {% csrf_token %} <label for="user_input" class="h5 text-primary"><i class="bi bi-robot"></i> AI</label> <input type="text" class="form-control" id="user_input" name="user_input" required> <button type="submit" id="chatGptSubmitBtn" class="btn btn-primary btn-sm my-3" id="aidaSubmitBtn"><i class="bi bi-play-circle-fill"></i> Mehet</button> <div class="my-3 px-2" … -
Django TestCase slef.client.patch gives a 404 error
I want to test the update function of a view set from rest_framework.viewsets import ModelViewSet @extend_schema(tags=['Customers']) class CustomerViewSet(ModelViewSet): """ This view can be used to see all the customers""" serializer_class = CustomerSerializer ..... def update(self, request, *args, **kwargs): return self._update_customer(request, *args, **kwargs) The route is mapped here (like the other view sets): router.register(r'customers', CustomerViewSet, basename='customer') Like for my other view sets where it works, i test the update method by resolving it in my test case from django.test import TestCase from rest_framework.reverse import reverse ...... class CustomerUpdateViewTest(TestCase): ..... def test_customer_missing(self): url = reverse('customer-detail', [2]) token = create_access_token(self.my_user) data = { 'customer': 'new name customer' } response = self.client.patch(url, data, content_type="application/json", HTTP_AUTHORIZATION=f'Bearer {token}') I have created before in a setup method many customers But the self.client.patch instruction give always a 404 error In my running application, the path is /api/customers/x (like in my test where x = a customer identifier) and is an HTTP PATCH verb For my similar views, i test in a very similar way and it works. Do you have already encountered such a problem ? If yes, what can i do to solve this problem ? Thank you very much in advance, Thomas -
VS Code not jumping to the top stack frame
I'm trying to debug some Django library code with the default VS Code Python and Django debugging settings (and "justMyCode" = True). I've set a breakpoint in one of the library functions: I call this from some user code, eg. formset.save(). When I debug and hit the breakpoint, VS Code jumps to this user code instead of the library code as I'd have expected: Pressing "Step Into" seems to progress the library code, but keeps jumping back to the user code which is calling it. The call stack seems to know about the library code, although it is greyed out: If I click on save then the currently executing statement is highlighted: I can go through the tedious process of stepping through, clicking the top stack frame, and then doing usual things like inspecting locals. The issue just seems to be about where VS Code is jumping to every time the debugger breaks (or maybe where pdb is telling VS Code to jump -- I'm not sure). I want the library code which is currently being executed to be jumped to, and that's what I would have expected to happen.