Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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; … -
How to add css and bootstrap in python django
When I try to load css file along with bootstrap, my css file doesn't work but bootstrap works fine. I don't know what went wrong and it annoys me the fact that something that supposed to take minutes to work takes me days to make it work for me enter image description here <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="https://unpkg.com/bootstrap@5.3.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://unpkg.com/bs-brain@2.0.4/tutorials/buttons/button-1/assets/css/button-1.css"> <link rel = "stylesheet" href = "css/style.css"> </head> <body> {% block content %} {% endblock %} </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html> -
Django CORS and CRSF Issues
The Issue I am at my wits end with CORS and CSFR issues. When I fix something I feelk like I am playing wack-a-mole when I fix something another element i not rendering. I am using django-cors-headers library. I have reviewed other Django CORS Questions, and tried to modify the suggestions but still getting inconsistent loading. I tried to make the most permissive configruations possible Source Code and Output The element that is not renderig is from docuseal, console output is Access to image at 'https://docuseal.s3.amazonaws.com/se9pbobli54k4y03zqliyh91ssyj?response-content-disposition=inline%3B%20filename%3D%220.jpg%22%3B%20filename%2A%3DUTF-8%27%270.jpg&response-content-type=image%2Fjpeg&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQXOPSUYTZ5CT2YNP%2F20240611%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240611T121805Z&X-Amz-Expires=14400&X-Amz-SignedHeaders=host&X-Amz-Signature=faded6e47a7668b5832bca56fe88b62454133cbe89f644cf1f06fcf0798c076a' from origin 'http://127.0.0.1:9555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here are my CORS & CSFR related settings: REFERRER_POLICY = "strict-origin-when-cross-origin" CSRF_COOKIE_NAME = "nhhc-csrf" CSRF_FAILURE_VIEW = "nhhc.urls.permission_denied_handler" SESSION_COOKIE_NAME = "nhhc-session" CSRF_HEADER_NAME = "X_CSRFToken" # CORS_ALLOWED_ORIGIN_REGEXES = [ # r"^null$", # r"^http://localhost:[0-9]+$", # r"^http://127\\.0\\.0\\.1:[0-9]+$", # r"^https://localhost:[0-9]+$", # r"^https://127\\.0\\.0\\.1:[0-9]+$", # r"^https://docuseal.s3.amazonaws.com/*" # ] CSRF_COOKIE_SECURE = False CORS_ALLOW_PRIVATE_NETWORK = True CSRF_COOKIE_DOMAIN = None SESSION_COOKIE_SECURE = False CORS_ORIGIN_ALLOW_ALL = True SESSION_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ["http://localhost"] The Ask Can someone offer input or resources on what I need to do to get this docseal element to render. If i have coinflicting settings. -
Django PasswordResetForm Not Sending Emails with Custom Domain
I'm encountering an issue with Django's PasswordResetForm where emails are not being sent when a custom domain is specified. Below is the save method within my custom form: class PasswordResetForm(auth_forms.PasswordResetForm): """ This form takes the same structure as its parent from :py:mod:`django.contrib.auth` """ def save(self, *args, domain_override=None, request=None, **kwargs): """ Generates a one-use only link for resetting password and sends to the user. """ site = get_current_site(request) if domain_override is not None: site.domain = site.name = domain_override for user in self.get_users(self.cleaned_data["email"]): self.send_password_reset_email(site, user, request) def send_password_reset_email(self, site, user, request=None): extra_context = { "user": user, "site": site, "reset_url": get_password_reset_url(user), "request": request, } CustomerDispatcher().send_password_reset_email_for_user(user, extra_context) I tried to retrieve the domain from the request using domain = request.get_host() but still facing the issue. Additional Context: When the domain_override parameter is provided with a custom domain, emails are not being sent to users. The get_current_site function is being used to fetch the current site based on the request. The custom domain is correctly retrieved and assigned to the site variable, but emails are still not being sent. The send_password_reset_email method is responsible for sending the password reset email to the user with the correct reset link. Question: How can I ensure that emails … -
How to change the root directory of a Python project?
I have a simple Django project (namely the one from this tutorial). The main part of the tree looks like this: . ├── env ├── proj │ ├── proj │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── api │ │ ├── __init__.py │ │ ├── serializers.py │ │ ├── urls.py │ │ └── views.py │ ├── base │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py | ├── __init__.py │ └── manage.py └── README.md In the tutorial the outer proj folder is the root. In api/views.py is the following import: from base.models import Item When I print sys.path in settings.py, it contains /path/to/wrapper/proj. But I would like my root folder to be one level higher. This is what I did: go to Settings > Project structure and change content root to /path/to/wrapper append another .parent to BASE_DIR in settings.py(now BASE_DIR = Path(__file__).resolve().parent.parent.parent) prepend proj. to imports(now from proj.base.models import Item) But that does not work: ModuleNotFoundError: No module named 'proj.base' When I print sys.path in settings.py, it still contains /path/to/wrapper/proj. Where does that actually come … -
Django channels function group_send causing problems
Context: I'm making a messaging application on the web, in which I'm implementing Django for the backend. For concurrency I am using websockets (channels). Well, for the user group management (channel layer) I'm using the following logic. There will be two types of groups, ‘chats’ and ‘notifications’. The notifications groups are groups of 1 user and 1 channel_name, they are used to track the user's connection, they have the following form: {user_id} : [‘{channel_name}’] Example: ‘30’: [‘specific.363469477d6745289c5bc679b7947790!d813479fc71448d49592711a7f823e06’] On the other hand, chat groups will be used to track the presence of users in chats, and report events such as ‘writing’, ‘connecting or disconnecting’, ‘updating’, ‘new messages’, etc ... At group level they have the following form: {id_minor}-{id_major} : [‘{channel_of_id_1}, {channel_of_id_2}’] Example: ‘1-30’: [‘specific.363469477d6745289c5bc679b7947790!d813479fc71448d49592711a7f823e06’] Note : in group chats there can be a maximum of 2 members, i.e. if user 1 joins the chat with 2, the structure would be like this... 1-2‘ : [’{channel_name_of_1}"]. If 2 enters the chat with 1, the structure would be like this ... ‘1-2’ : [‘{channel_name_of_2}’] And if both are in the chat ... ‘1-2’ : [‘{channel_name_of_2}, {channel_name_of_1}’] Problem: in the django application I have the following function ... logger = logging.getLogger('django.channels') async def broadcast_connection_inform(user_id, … -
Model manager queryset doubles the sum for sets of amounts
I want to return the sums of items and payments for an invoice using a model manager. It works correctly if there is only one record in the payment and item models, if I add more I can no longer chain the results. In the shell I tried the following >>> Invoixe.objects.with_aggregates().last().tot Decimal('60') >>> Invoixe.objects.with_totals().last().tot Decimal('30') with_aggregates returns the wrong total(tot) value (The correct total is 30) The SQL looks like this SELECT "task_invoixe"."id", "task_invoixe"."name", (CAST(SUM("task_ixem"."amount") AS NUMERIC)) AS "tot", (CAST(SUM("task_paxment"."amount") AS NUMERIC)) AS "pay", (CAST(((CAST(SUM("task_ixem"."amount") AS NUMERIC)) - (CAST(SUM("task_paxment"."amount") AS NUMERIC))) AS NUMERIC)) AS "bal" FROM "task_invoixe" LEFT OUTER JOIN "task_ixem" ON ("task_invoixe"."id" = "task_ixem"."invoixe_id") LEFT OUTER JOIN "task_paxment" ON ("task_invoixe"."id" = "task_paxment"."invoixe_id") GROUP BY "task_invoixe"."id", "task_invoixe"."name" ORDER BY "task_invoixe"."id" ASC LIMIT 1 Here is the code ChatGPT believes this code should work I can create the same error by chaining managers like so >>> Invoixe.objects.with_totals().with_payments().last().tot Decimal('60') >>> Invoixe.objects.with_totals().last().tot Decimal('30') Which also give the wrong amount from django.db import models from django.db.models import Sum, F class InvoixeQueryset(models.QuerySet): def with_totals(self): return self.annotate(tot=Sum(F('ixem__amount'))) def with_payments(self): return self.annotate(pay=Sum(F('paxment__amount'))) def with_aggregates(self): return self.annotate( tot=Sum('ixem__amount'), pay=Sum('paxment__amount'), ).annotate(bal=F('tot') - F('pay')) class InvoixeManager(models.Manager): def get_queryset(self): return InvoixeQueryset(self.model, using=self._db) def with_aggregates(self): return self.get_queryset().with_aggregates() def with_totals(self): return self.get_queryset().with_totals() … -
Django javascript hide functionality not working
What I basically want is for there only to be the "This product has variations" checkbox, then if the user checks that box, then the Size and Colour checkboxes will show up. If the user clicks size, the size variation value box will show up. Same with colour. Right now although I am trying with my script to achieve this functionality, I can't. What am I doing wrong here? Thanks in advance! My models.py: class Product(models.Model): name = models.CharField(max_length=100) product_slug = models.SlugField(unique=True, blank=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') image2 = models.ImageField(upload_to='products/', null=True, blank=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='products') in_stock = models.BooleanField(default=True) is_popular = models.BooleanField(default=False) is_best_seller = models.BooleanField(default=False) min_delivery_time = models.PositiveIntegerField(null=True, help_text="Minimum estimated delivery time in business days") max_delivery_time = models.PositiveIntegerField(null=True, help_text="Maximum estimated delivery time in business days") has_variations = models.BooleanField(default=False) def __str__(self): return f'{self.business.business_name}, {self.name}' def get_json_data(self): data = { 'id': self.id, 'name': self.name, 'price': float(self.price), 'description': self.description, 'images': [self.image.url, self.image2.url] if self.image and self.image2 else [], 'min_delivery_time': self.min_delivery_time, 'max_delivery_time': self.max_delivery_time, } return json.dumps(data) def save(self, *args, **kwargs): if not self.product_slug: self.product_slug = slugify(self.name) super().save(*args, **kwargs) @property def overall_review(self): avg_rating = self.reviews.aggregate(Avg('rating'))['rating__avg'] return round(avg_rating, 1) if avg_rating else 0 def star_rating_percentage(self, star): total_reviews = self.reviews.count() … -
How to change font in Django form?
I'm writing a website in django, using a built-in form, but the font is not at all like in the example. I can't make the text smaller my site looks like this forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): phone_number = forms.CharField(max_length=15, required=True, help_text='Номер телефона в формате +7 9XX XXX XX XX') password1 = forms.CharField( label='Password', strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),) class Meta: model = User fields = ('username', 'phone_number', 'email', 'password1', 'password2', ) views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import SignUpForm from .models import Profile def registration(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() Profile.objects.create(user=user, phone_number=form.cleaned_data.get('phone_number')) raw_password = form.cleaned_data.get('password') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'users/signup.html', {'form': form}) main.html (template) {% load static %} {{ '<' }}{{ '!DOCTYPE html>' }} <html lang="ru"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link href="{% static 'main/css/main.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <div id="header"> <span class="logo">Greenhouse</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> signup.html (login page) {% extends … -
python django floadformat doesn't work with arabic langauge
I am working on an ecomerece site, In django template i want to render value with float value 2 like that {{product.tax_price|floatformat:2}} it return correct value when language in english as soon as i change into arabic it render value like 120,00 instead of 120.00. can you please specify the issue i am having thanks in advance I have try syntax describe in django formating documentation {{ product.tax_price|floatformat:"3u" }} -
Syncing offline app with lots of data with server
Hi fellow stackoverflowers, We have an electron app, with a JSON DB for persisting the app's state while offline. When the app syncs (to submit new actions & fetch new data), a new JSON is created from the server(Django), which replaces the one previously being used from the electron app. All good up to now, the app has had lots of usage, until one of the features started exploding the size of the JSON response. For additional context, serialising the response object to a JSON object on the server can take up to ~30sec, which will grow even more given that data adds up. At the moment we were thinking that our best bet is to introduce websockets, move the JSON generation in the background, and send a message to the app once its completed. Since i'm not very experienced with offline apps i wonder, is this a legit solution? Are we on the right path or at there alternatives? Isn't there a standard pattern of handling this type of issues? We've also thought about a diff sync, which would only include a small portion of the JSON DB every time in the response (e.g by updated_at) but then what … -
Django PasswordResetForm Not Sending Emails to Users with Unusable Passwords
enter image description here In my Django application, I am using the PasswordResetForm to allow users to reset their passwords. However, I noticed that users with unusable passwords do not receive password reset emails. The get_users method in PasswordResetForm filters out these users. The Django documentation states: The get_users method in the PasswordResetForm also filters out users with an unusable password, so those users don’t get emails either. You’ll have to either assign some type of password to those users or override that method in the form to not filter out by that condition. Additionally, I receive a "200 OK" response and see the log entry GET /password-reset/done/ HTTP/1.1" 200 6626, but the emails are not being sent. How can I resolve this issue? Specifically, how can I either: Assign a usable password to users who have an unusable password. Override the get_users method in PasswordResetForm to include users with unusable passwords. -
Razor Pay Not Calling CallBack URL Python Django
So basically, razorpay popup is opening, payment being success but the callback url isn't getting called: var options = { "key": data.razorpay_key, "amount": data.amount, "currency": data.currency, "name": "BusinessCard4U", "image": "{{websitelogo.image.url}}", "description": "Payment for digital card subscription", "order_id": data.razorpay_order_id, "callback_url": "{% url 'PaymentSuccess' %}", "handler": function (response){ // Handle Razorpay success callback }, "theme": { "color": "#5EB9F0" }, }; This is data i am passing... it has callback url as you can see... but neither anything is getting printed, nor it's being called. I tried using redirect: true variable to see if that works but that made the payment failed. Thank You! -
Regex Pattern to allow alphanumeric and square brackets with text insde it
i am using regex to allow alphanumeric, underscore, hyphen and square brackets in a text box. regex i am using to validate input is r'^[a-zA-Z0-9_\-\[\] ]*$. i need to modify the regex such that if empty brackets are given it should return false. Sample cases "Your message here" - Valid "Your [text] message here" - Valid "your_text_message [text]" - valid "Your [] message here" - Invalid "[] message" - Invalid