Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django + Celery + Redis + Supervisor repeating, resending and duplicating tasks
I configures in my Ubuntu and Apache server a Django project in which I use celery to manage and handle backgound jobs/tasks. The problem that I see is that when there is a queue of tasks and is managing 3, if the 4th, 5th... do not start executing within an hour they duplicate. Here is what i have... Supervisor conf [program:project_app] command=/path/celery -A haus worker --loglevel=INFO -c 3 directory=/path/ user=www-data autostart=true autorestart=true stdout_logfile=/path/celeryd.log redirect_stderr=true celery.py from future import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) settings.py ... BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Mexico_City' ... The way i execute is: @shared_task() def do_some(args): # code do_some.delay(args) [2024-06-09 22:49:46,855: INFO/MainProcess] Task haus.celery_tasks.do_some[8bc9dc9e-493a-4b1d-b81a-f758c8ef49a3] received [2024-06-09 22:49:57,021: INFO/MainProcess] Task haus.celery_tasks.do_some[a58ba0cb-4881-430d-b652-a8d4edd704ea] received [2024-06-09 22:50:13,631: INFO/MainProcess] Task haus.celery_tasks.do_some[5cd7f9d3-c77f-4331-8459-9889e19f34af] received [2024-06-09 22:52:25,640: INFO/MainProcess] Task haus.celery_tasks.do_some[cd98b3e3-022d-4785-a89e-128a659c8e95] received [2024-06-09 22:52:51,268: INFO/MainProcess] Task haus.celery_tasks.do_some[54a35f23-426a-463f-9e72-e733cdd79ed2] received [2024-06-09 22:52:58,362: INFO/MainProcess] Task haus.celery_tasks.do_some[b6190664-179e-4316-8275-3b184e5b3cdc] received [2024-06-09 23:53:43,860: INFO/MainProcess] Task haus.celery_tasks.do_some[b6190664-179e-4316-8275-3b184e5b3cdc] received [2024-06-09 23:53:43,898: INFO/MainProcess] Task haus.celery_tasks.do_some[cd98b3e3-022d-4785-a89e-128a659c8e95] received [2024-06-09 23:53:43,909: INFO/MainProcess] Task haus.celery_tasks.do_some[54a35f23-426a-463f-9e72-e733cdd79ed2] received [2024-06-10 00:32:37,245: … -
django-storages[google] - Staticfiles storage key attribute error
I'm trying to configure Django (5.0.4) to use Google Cloud S3 as my file storage using django-stores. Here is what my settings.py configuration for object storage looks like: from google.oauth2.service_account import Credentials STORAGES = { "default": { "BACKEND": "storages.backends.gcloud.GoogleCloudStorage", "OPTIONS": { "GS_BUCKET_NAME": "BUCKET", "GS_PROJECT_ID": "PROJECT", "GS_CREDENTIALS": Credentials.from_service_account_file("service-account.json"), }, }, "staticfiles": "storages.backends.gcloud.GoogleCloudStorage" } After running python manage.py collectstatic I'm getting the following AttributeError Traceback (most recent call last): File "/home/victor/BmLabs/site/manage.py", line 22, in <module> main() File "/home/victor/BmLabs/site/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/victor/.pyenv/versions/bmlabs/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/victor/.pyenv/versions/bmlabs/lib/python3.12/site-packages/django/core/management/__init__.py", line 382, in execute settings.INSTALLED_APPS File "/home/victor/.pyenv/versions/bmlabs/lib/python3.12/site-packages/django/conf/__init__.py", line 89, in __getattr__ self._setup(name) File "/home/victor/.pyenv/versions/bmlabs/lib/python3.12/site-packages/django/conf/__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/victor/.pyenv/versions/bmlabs/lib/python3.12/site-packages/django/conf/__init__.py", line 262, in __init__ self.STORAGES.get(STATICFILES_STORAGE_ALIAS, {}).get("BACKEND"), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'get' As per the guide I've set the staticfiles key to storages.backends.gcloud.GoogleCloudStorage. -
search() got an unexpected keyword argument 'query'
`I want to implement the search function with the Django Web framework. I'm working on fetching public data (API) and fetching the data corresponding to the search results and showing it on the index.html page is it search view! def search(request): base_url = "http://apis.data.go.kr/5710000/benlService/nltyArtList" image_api_url = "http://apis.data.go.kr/5710000/benlService/artImgList" # 검색어 가져오기 search_query = request.GET.get('q', '') params = { "serviceKey":"gKat/nvnmi8i9zoiX+JsGzCTsAV75gkvU71APhj8FbnH3yX4kiZMuseZunM0ZpcvKZaMD0XsmeBHW8dVj8HQxg==", "pageNo": "1", "numOfRows": "5", "returnType": "json", "artNm": search_query } response = requests.get(base_url, params=params) if response.status_code == 200: data = response.json() art_list = data['response']['body']['items']['item'] # 작품 이미지 정보 for art in art_list: image_params = { "serviceKey":"gKat/nvnmi8i9zoiX+JsGzCTsAV75gkvU71APhj8FbnH3yX4kiZMuseZunM0ZpcvKZaMD0XsmeBHW8dVj8HQxg==", "pageNo": "1", "numOfRows": "5", "returnType": "json", "artNm": art["artNm"] # 'art_name' 대신 'art["artNm"]' 사용 } image_response = requests.get(image_api_url, params=image_params) if image_response.status_code == 200: image_data = image_response.json() if 'item' in image_data['response']['body']['items']: art["image_url"] = image_data["response"]["body"]["items"]["item"]["imgUrl"] else: art["image_url"] = None else: art["image_url"] = None else: # 에러 처리 print("API 요청 실패:", response.status_code) art_list = [] return render(request, 'index.html', {'art_list': art_list, 'search_query': search_query}) is it urls.py path setting urlpatterns = [# path('', views.index, name='index'), # 예를 들어, index view로 연결path('', views.openapi_view, name='index'),path('search/<str:query>/', views.search, name='search'),] -
Django StreamingHttpResponse streams locally but not in production
I am posting this question after a lot of research but didn't get any solution working for me. I don't know what am I doing wrong, as I am new to Django Following is my code base for stream.py import json from django.http import StreamingHttpResponse from decimal import Decimal class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) # or float(obj) return super(DecimalEncoder, self).default(obj) class StreamResponseMixin: def stream_response(self, queryset, serializer_class, gen_message_func=None): def generate_stream(): for item in queryset: serializer = serializer_class(item) yield self.gen_message(serializer.data, gen_message_func) response = StreamingHttpResponse(generate_stream(), content_type='text/event-stream') response['X-Accel-Buffering'] = 'no' # Disable buffering in nginx response['Cache-Control'] = 'no-cache' # Ensure clients don't cache the data response['Transfer-Encoding'] = 'chunked' return response def gen_message(self, data, gen_message_func=None): if gen_message_func: return gen_message_func(data) return '{}\n'.format(json.dumps(data, cls=DecimalEncoder)) # Default behavior if no custom message generator is provided Views.py class PackageViewSet(viewsets.ModelViewSet, StreamResponseMixin): queryset = Package.objects.all().order_by('-created_at') def get_serializer_class(self): if self.action in ['list', 'modified']: return PackageListSerializer return PackageDetailSerializer def get_queryset(self): user = self.request.user package_queryset = Package.objects.all().order_by('-created_at') package_queryset = package_queryset.select_related('customer', 'creator').prefetch_related( Prefetch('products', queryset=Product.objects.all()), ) try: customer = Customer.objects.get(user=user) package_queryset = package_queryset.filter(customer=customer) except ObjectDoesNotExist: pass return package_queryset @action(detail=False, methods=['GET'], url_path='stream-packages') def get_stream(self, *args, **kwargs): packages = self.get_queryset().iterator(chunk_size=50) return self.stream_response(queryset=packages, serializer_class=PackageListSerializer) nginx.conf server { listen 443 ssl; server_name abc.api.ai; ssl_certificate /etc/letsencrypt/live/abc.api.ai/fullchain.pem; …