Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't run Pycharm Debugger using WSL2
I have a project that has in PostgreSQL, Celery, Redis, RabbitMQ via docker containers. I'm facing an issue with PyCharm's debugger when running a DRF project in WSL2(Ubuntu). The project runs success in normal mode, but when I start the debugger, it hangs and eventually fails with "Handshake failed" errors in the logs. The full command executed is: /home/myuser/myproject/venv/bin/python3.11 /home/myuser/.pycharm_helpers/pydev/pydevd.py --multiprocess --qt-support=auto --port 29781 --file /home/myuser/myproject/manage.py runserver 8000 Here’s a snippet of the PyCharm logs: 025-03-06 12:48:04,336 [6128385] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,338 [6128387] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,454 [6128503] INFO - #c.i.e.wsl - WSL mount root for Ubuntu is /mnt/ (done in 114 ms) 2025-03-06 12:48:04,493 [6128542] WARN - #c.i.u.Alarm - Do not create alarm without coroutineScope: com.intellij.ui.GotItTooltip.(GotItTooltip.kt:94) 2025-03-06 12:48:04,508 [6128557] INFO - #c.i.u.WinFocusStealer - Foreground lock timeout set to 0 2025-03-06 12:48:06,295 [6130344] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [92734501] Handshake failed 2025-03-06 12:48:11,303 [6135352] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [1988656345] Handshake failed … -
Why is Django not using the specified cache backend?
As a simple test, I'm attempting to set the cache backend used by Django to something other than the default django.core.cache.backends.locmem.LocMemCache. I'm using a custom backend defined in the django-bmemcached package, which uses the python-binary-memcached module to access a Memcached instance with authentication. I've set the backend in the settings.py file, with the relevant snippet below: CACHES = { 'default': { 'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': { 'username': <username>, 'password': <password>, } }, } The settings.py file is being used by the application, but the default cache being used is not the specified cache backend: >>> from django.conf import settings >>> print(settings.CACHES) {'default': {'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': {'username': <username>, 'password': <password>}}} >>> from django.core.cache import caches >>> print(caches['default']) <django.core.cache.backends.locmem.LocMemCache object at 0x73bf66531720> This isn't caused by a third party package overriding the cache backend, and the Memcached instance can be accessed and operations performed successfully if a client for the backend is instantiated: bmemcached.Client(<ip>:<port>, <username>, <password>). Using a different binding, such as pymemcache, and setting the backend to a Django supported django.core.cache.backends.memcached.PyMemcacheCache still results in the above issues described where the default cache being used is not the specified cache backend. If at all possible, I'd like to be … -
How to Conditionally Render Mobile and Desktop Ads in Django to Prevent JavaScript Overlap?
I'm working on a Django project where I need to display different ads for mobile and desktop users. Currently, both mobile and desktop ad JavaScript is being loaded, which causes conflicts as the mobile ad scripts interfere with the desktop ads. Here's a simplified version of my template code: <div class="ads-mobile"> {% ad_simple_tag "mobile_ads" %} </div> <div class="ads-desktop"> {% ad_simple_tag "desktop_ads" %} </div> I'm using Cloudflare, which caches the pages, so I can't rely on server-side logic (like middleware) to determine which ads to display, as the result would be cached. I attempted to use JavaScript and/or css to detect the device type and hide/show or remove the ad blocks accordingly, but both ad scripts are still being loaded, causing issues. How can I ensure that only the relevant ad scripts are loaded based on the user's device type, considering that the page is cached by Cloudflare? Is there a client-side approach or best practice for handling this kind of situation in Django? -
How to apply Apache BasicAuth with IP-based access control for django project
I have a Django application and I am using Apache to manage access control. I want to restrict access to django project with this logic -> Allow access only from specific IP addresses. If the request comes from an IP address outside the allowed list, users should be prompted to authenticate using username and password defined in .htpasswd Apache .htpasswd username:encryptedpassword Apache virtual Host <VirtualHost *:80> LoadModule wsgi_module "/var/www/example.com/venv/lib/python3.10/site-packages/mod_wsgi/server/mod_wsgi-py310.cpython-310-x86_64-linux-gnu.so" DocumentRoot /var/www/example.com ServerName example.com WSGIDaemonProcess myapp python-home=/var/www/example.com/venv python-path=/var/www/example.com:/var/www/example.com/venv/lib/python3.10/site-packages WSGIScriptAlias / /var/www/example.com/example/wsgi.py process-group=myapp <Directory "/var/www/example.com/"> AllowOverride All Require all granted <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/example.com/static/ <Directory /var/www/example.com/static/> Require all granted </Directory> <Directory /var/www/example.com/> AllowOverride All Require all granted </Directory> <Location /> AuthType Basic AuthName "Restricted Access" AuthUserFile /var/www/example.com/.htpasswd Require valid-user <RequireAny> Require ip x.x.x.x Require ip x.x.x.x Require valid-user </RequireAny> </Location> </VirtualHost> Desired behaviour Users accessing any URL in the application from allowed IP addresses should have unrestricted access. Users from non-allowed IP addresses should be prompted for authentication via apache(.htpasswd) Problem is If I am inputing username and password prompted by apache, django gives { "detail": "Invalid username/password." } I dont want to remove headers at apache level because some of my url requires authentication implemented … -
Django images not loading after setting `DEBUG = False` on PythonAnywhere
I have deployed my Django project on PythonAnywhere, and everything was working fine when DEBUG = True. However, after setting DEBUG = False, none of my images (media files) are loading. What I Tried: I have set up MEDIA_URL and MEDIA_ROOT correctly in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I also ran python manage.py collectstatic --noinput and my static files are loading correctly. The images are uploaded and exist in the /home/myusername/django_ecom_web/ecomprj/media/ directory. I checked the file paths in the browser and they return a 404 Not Found error. How I Fixed It: After some research, I found that Django does not serve media files in production when DEBUG = False. To fix this in PythonAnywhere, I had to: Go to Dashboard → Web → Static Files section. Add the following mapping: /media/ → /home/myusername/django_ecom_web/ecomprj/media/ Reload my web app. After doing this, my images started loading correctly. My Question: Why does Django not serve media files in production when DEBUG = False? Is setting up a manual media mapping the only way to serve media files on PythonAnywhere, or is there a better approach? -
Django returns old form data in HTMX response
I changed UpdateView do that it can handle create requests as well if pk=0: class ObjectView(UpdateView): hx_url = "" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) self.hx_url = f"{self.model._meta.app_label}:{self.model._meta.model_name}" context["hx_url"] = reverse( self.hx_url, args=[self.object.id if self.object else 0] ) return context def get_object(self, queryset=None): if self.kwargs.get(self.pk_url_kwarg) == 0: return None return super().get_object(queryset) def form_invalid(self, form): messages.add_message( self.request, messages.ERROR, "Invalid input.", ) return self.render_to_response(self.get_context_data(form=form)) def form_valid(self, form): messages.add_message( self.request, messages.SUCCESS, "Data saved.", ) if self.request.htmx: return self.render_to_response(self.get_context_data(form=form)) return redirect(self.object.get_absolute_url()) In my View I am checking if price field was updated and if yes update the price_date field as well: class PartView(ObjectView): model = Part form_class = PartForm def form_valid(self, form): if self.object: old = Part.objects.get(id=self.object.id) old_price = old.price self.object = form.save(commit=False) if self.object.price != old_price: self.object.price_date = date.today() self.object.save() form.save_m2m() else: self.object = form.save() return super().form_valid(form) I make an htmx call to it from my template: <div id="modalContent" hx-target="this"> <form method="post" hx-post="{{ hx_url }}" hx-on:htmx:validation:failed="this.reportValidity()" hx-trigger="click from:#btn-save"> {% csrf_token %} <div> {% include "form_field.html" with form_field=form.price %} {% include "form_field.html" with form_field=form.price_date %} </div> </div> </form> {% include "btn_save.html" %} {% include "messages.html" %} </div> The problem is even though it successfully updates the price_date in the DB it still … -
Django ModuleNotFoundError: No module named 'ecomprj' on PythonAnywhere Deployment
Body: I am deploying my Django project on PythonAnywhere, but I keep getting this error in my logs: ModuleNotFoundError: No module named 'ecomprj' Project Structure: My Django project is located at: /home/Sagarmoy007/django_ecom_web/ecomprj/ Running ls -l /home/Sagarmoy007/django_ecom_web/ecomprj gives: __pycache__ core customercare db.sqlite3 deladmin ecomprj errorriders locustfile.py manage.py media migrate.bat notification_app others requirements.txt returnadmin staffdata static staticfiles templates useradmin userauths vendorpannel videoshareing whoosh_index Inside /home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj/, I have: __init__.py settings.py urls.py wsgi.py asgi.py My WSGI File (/var/www/sagarmoy007_pythonanywhere_com_wsgi.py): import os import sys # Add the correct project paths sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj') # The main directory sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj') # The Django project folder # Set Django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecomprj.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() What I Have Tried: Verified that manage.py exists inside /home/Sagarmoy007/django_ecom_web/ecomprj. Checked that the Django settings module is correctly set (ecomprj.settings). Restarted the web app from the PythonAnywhere dashboard. Ran python manage.py shell inside /home/Sagarmoy007/django_ecom_web/ecomprj, but it fails with the same ModuleNotFoundError. Questions: Is my WSGI configuration correct? Do I need to modify my PythonAnywhere environment? How can I properly set up Django on PythonAnywhere to recognize my project? -
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed class MyCustomSignupForm(SignupForm): def save(self, request): token = request.POST['g-recaptcha-response'] action = "signup" r_result = recaptcha(request, token, action) if r_result: user = super(MyCustomSignupForm, self).save(request) else: messages.warning(request, '...robot...') user = ??? return user -
Cannot resolve keyword 'mem_ev' into field in Django
I have a small Django project that consists of 2 models (Event, mem_ev) plus auth User and Profile such that Users --< mem_ev >-- Events (ie a classic many to many relationship between Users & Events). I want to be able to list all events for a member and all members for an event both of which entail a join between the main dataset and mem_ev. I have the list of events attended by a member working fine (list_member_events) but cannot get a list of members attending an event (list_event_members) working. My models.py is: from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Delete profile when user is deleted event_count = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' #show how we want it to be displayed class Event(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default="", null=False) description = models.TextField() cost = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) event_date = models.DateTimeField(null=True,blank=True) attendees = models.IntegerField(default=0) class Meta: ordering = ['event_date'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Event, self).save(*args, **kwargs) class Meta: ordering = ['event_date'] def __str__(self): return self.title class mem_ev(models.Model): member_id = models.ForeignKey("Profile",on_delete=models.CASCADE) event_id = models.ForeignKey("Event",on_delete=models.CASCADE) amt_paid = models.DecimalField(max_digits = … -
Cannot determine region size; use 4-item box
I'm trying to make a QR code and I'm using pillow=11.1.0. Here's the code to generate and save the QR code: def save(self, *args, **kwargs): ## TODO:Generate QR Code # qr_code_url = f"{os.environ['HOST_URL']}/inventory/{self.part_type_id}" qrcode_img = qrcode.make(self.part_number) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(im=qrcode_img, box=(0,0)) buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code_data.save(f'{self.part_name}.png', File(buffer), save=False) canvas.close() super().save(*args, **kwargs) However when I do save it I'm faced with the following error: cannot determine region size; use 4-item box The line in question is: canvas.paste(im=qrcode_img, box=(0,0)) -
Hey There ! , I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base
, I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base Cloud Messaging i am having trouble to implement it on my Django Project . Well i want to implement these features: TO send Notification from student to Teacher And Vice Versa . QN. = > How do i do it ? well i need help or some best YouTube Channels to help guide me as of my recent Searches in YT {YouTube} i have not Found the best Video that matches my Querry . -
Django generates complex SQL instead of simple OR condition
I'm encountering an issue where Django's ORM is generating an unexpectedly complex SQL query from a simple function. The function checks if there are any recent or upcoming matches by applying filters for team participation and public season checks on alive matches. Instead of a straightforward OR condition, the generated SQL includes a nested subquery: SELECT COUNT(*) FROM "scheduler_season" WHERE "scheduler_season"."id" IN ( SELECT U0."id" FROM "scheduler_season" U0 WHERE (U0."enddate" >= ?::date AND U0."schedule_is_public" = ?) ) OR "scheduler_season"."id" IN (?, ?, ..., ?) Expected query: SELECT COUNT(*) FROM "scheduler_season" WHERE ("enddate" >= ? AND "schedule_is_public" = ?) OR "id" IN (?, ?, ..., ?) Why does Django create this complex subquery, and how can I modify the Django query to generate the simpler expected SQL? -
Flatpicker on django template not working on mobile device
i have interesting problem. Have this template: {# date picker #} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"/> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/bg.js"></script> <link rel="stylesheet" type="text/css" href="{% static "custom/date_picker.css" %}"/> <script> document.addEventListener("DOMContentLoaded", function () { // Ensure Flatpickr's localization is loaded before modifying if (flatpickr.l10ns && flatpickr.l10ns.bg) { flatpickr.l10ns.bg.rangeSeparator = " до "; } else { console.warn("Bulgarian locale not found, continuing without modifying rangeSeparator."); } const dateTimePickers = ["#fromInput", "#toInput"]; dateTimePickers.forEach(selector => { flatpickr(selector, { enableTime: true, time_24hr: true, locale: "bg", dateFormat: "H:i ч. на d M Y г.", enableSeconds: false, // Ensure seconds are not required disableMobile: true // Forces Flatpickr UI on mobile }); }); </script> then i have this two inputs <div style="margin-top: 15px" id="fromDiv"> <label for="fromTime">От</label> <input type="text" id="fromInput" name="fromTime" placeholder="Избери дата и час" style="margin: auto"> </div> <div style="margin-top: 15px" id="toDiv"> <label for="dateTimeInput">До</label> <input type="text" id="toInput" name="toTime" placeholder="Избери дата и час" style="margin: auto"> </div> everything works perfectly on desktop browser, but when is used on mobile device, inputs change, want seconds, but in choice pop up its not possible to be selected seconds. Examples on desktop browser: how looks input and choice pop-up on desktop browser Examples on mobile: pop-up choice on mobile browser and date-time input on mobile browser.. how … -
Forbidden Error (403) in Django Test Cases on GitHub Actions
I have a Django REST framework API application hosted on AWS ECS, using RDS. I am working on implementing CI/CD using GitHub Actions, where we need to include a test suite. The corresponding CI/CD implementation is as follows: unit-tests: runs-on: ubuntu-latest environment: ${{ inputs.build_env }} env: ENVIRON: ${{ secrets.ENVIRON }} PG_DB_NAME: ${{ secrets.POSTGRES_DB }} PG_DB_USER: ${{ secrets.POSTGRES_USER }} PG_DB_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} PG_DB_HOST: ${{ secrets.POSTGRES_HOST }} PG_DB_PORT: ${{ secrets.POSTGRES_PORT }} SECRET_KEY: ${{ secrets.SECRET_KEY }} steps: - name: Checkout repo uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v2 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install dependencies run: | python3 -m pip install --upgrade -r requirements.txt - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ secrets.AWS_REGION }} - name: Run tests run: | cd ./dbasebe python3 manage.py test cd .. And the unit test case is class TestFirstEndpoint(SimpleTestCase): def setUp(self): self.client = APIClient(enforce_csrf_checks=False) def test_endpoint_no_valid_user(self): url = reverse('myapp:firstendpoint') response = self.client.post(url, {'userid':'testuser'}, format='json') `self.assertEqual(response.status_code, 404) the corresponding endpoint view is @api_view(["POST"]) @authentication_classes( ([utils_security.CsrfExemptSessionAuthentication, BasicAuthentication]) def first_endpoint_view(request): userid = request.data.get("userid", 'USER1') user = Mymodel.objects.filter(userid=userid) if user.exists(): # do my job return Response({"message": "Work is done"}, status=status.HTTP_200_OK) else: return Response({"message": "User not found"}, status=status.HTTP_404_NOT_FOUND) … -
'<' not supported between instances of 'NoneType' and 'int' django views.py
templates/html {% if guess == rand_num %} <h1>{{message1}}</h1> {% elif guess > rand_num %} <h1>{{message3_a}}</h1> <h1>{{message3_b}}</h1> {% elif guess < rand_num %} <h1>{{message2_a}}</h1> <h1>{{message2_b}}</h1> {% endif %} views.py def easy(request, ): rand_num = random.choice(lst) print(rand_num) attempts = 11 for _ in range(0, 10): # print(f"You have {attempts} remaining to guess the number.") # guess = int(input("Make a guess: ")) guess = request.GET.get('guessed_number') if guess == rand_num: return render(request, 'easy.html', {'attempts': attempts, "message1": f"You got it! The anshwer was {rand_num}"}) break elif guess < rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message2_a": "Too Low", "message2_b": "Guess again"}) elif guess > rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message3_a": "Too High", "message2_b": "Guess again"}) attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, 'guess': guess, 'rand_num': rand_num}) return render(request, 'easy.html') i Am triying to Run this Django code. but it is not running.. -
In Django 5.1 difference between Model and AbstractUser
I am looking at the Django Documentation and am a bit confused as the differences between: from django.contrib.auth.models import AbstractUser from django.db.models import Model I tried doing the following in a class and got an error that has to do with the following topic: Python multiple inheritance and MRO The error emerged because I had done the following: class Employee(Model, AbstractUser): pass When I went to make migrations in Django, an error message said it violated MRO. When I searched what that meant on Google, I found a Stack Overflow post that mentions that it happens when it can't decide between the two classes, a specific value, or a method. In my research, there might be a conflict amongst similar methods in class. I am expecting to have an Employee that has a custom authentication, and is an entity in the database. How would I go about achieving this, do I have to pick AbstractUser over Model? -
Unable to connect via saml sso login to Azure AD
I am using django as backend and I am trying to do saml sso login for Azure AD. I am getting below error for xmlsec. I am using djangosaml2, pysaml2 in django backend for saml auth error=Error: xmlSecCryptoAppKeyLoadEx failed: file=C:\Users\ADMINI~1\AppData\Local\Temp\2\tmpeq1v1od1.pemError: failed to load public key from "C:\Users\ADMINI~1\AppData\Local\Temp\2\tmpeq1v1od1.pem".Error: keys manager creation failed tmpeq1v1od1.pem file is created in Temp\2\ folder but when i try to run xmlsec signature verify command manually I am getting same error. -
django rest framework, how to override a field so that "null is zero"
Hello I have a Model with a field that is not null on the database -the field "amount". However on the api-level this field can be skipped, which should then be stored as the default value. I have tried several ways, however I keep coming back to the fact that to_internal_value() isn't executed for fields when the value is None? Even though the field has allow_null to be True? class NullIsZeroDecimalField(serializers.DecimalField): def __init__(self, **kwargs): super().__init__(allow_null=True, default=0, **kwargs) def to_internal_value(self, data: Primitive) -> Decimal: """Convert None or empty strings to 0 before validation. :param Primitive data: the input data return Decimal: decimal value """ print('internal value') if data is None or data == "": return Decimal(0) return super().to_internal_value(data) class ModelWithAmountSerializer(serializers.ModelSerializer): amount = NullIsZeroDecimalField(max_digits=20, decimal_places=10) class Meta: model = AmountModel fields = ("amount",) def test_serializer(self): serializer = ReceiptLineSerializer(data={"amount": None}) is_valid = serializer.is_valid() self.assertEqual(serializer.validated_data["amount"], Decimal(0)) However here the assertion fails. And upon research it turns out that the "to_internal_value" is never called for "none" fields. it is just short-circuited. How to overcome this? And if possible, could I instead of defaulting to "0" default to the "default-of-the-model-definition"? IE as if the value is omitted when creating the model? -
Django Admin CSS Not Loading in Production Even Though Static Files Are Served (200 OK)
I'm experiencing an issue where my Django admin panel appears unstyled on my production server, even though all static files are being served correctly. The admin HTML includes proper <link> tags, and I can confirm that the CSS files are accessible via direct URL. Environment Details: Production: Azure VM Django: latest Application Server: Gunicorn Web Server: nginx on Ubuntu Middleware: Removed WhiteNoise (to avoid conflicts) Static Files: Collected using python manage.py collectstatic --noinput Note: I am using same azure VM for my django backend and react frontend What I’ve Done/Verified: 1. Django Settings: Set STATIC_URL and configured STATIC_ROOT STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 2. Nginx Configuration: server { listen 80 default_server; server_name _; client_max_body_size 200M; # Favicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/example/staticfiles/; autoindex on; } # Serve media files location /media/ { root /home/ubuntu/example; autoindex on; } # Proxy API requests to Django backend location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } # Proxy Django admin requests to the Django backend location /admin/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } # Serve the React frontend from its build output location / { root /home/ubuntu/frontend/dist; # Adjust path if needed try_files … -
django add success message erro
Whenever i am using messages I keep getting the same type error saying string is no callable. However this same code used to work, I am not sure what happened but it just stopped working and started giving me this error for all messages in all pages, even when i add something on admin panel. Not sure what is causing this error. Please help. Request Method: POST Request URL: http://127.0.0.1:8000/compras/fornecedores/ Django Version: 5.1.3 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: /Users/macbook-fcorrea/Documents/Coding/cabiunas/compras/views/views.py, line 122, in fornecedores Raised during: compras.views.views.fornecedores Python Executable: /Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/bin/python3 Python Version: 3.13.1 Python Path: ['/Users/macbook-fcorrea/Documents/Coding/cabiunas', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python313.zip', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/lib-dynload', '/Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/lib/python3.13/site-packages', '/Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/lib/python3.13/site-packages/setuptools/_vendor'] This is my views.py def fornecedores(request): form_empty = NewFornecedor() # FILTER fornecedor_filter = FornecedorFilter( request.GET, queryset=Fornecedor.objects.all().order_by('name')) all_forn = fornecedor_filter.qs if request.method == 'GET': context = { 'all_forn': all_forn, 'fornecedorform': form_empty, 'filter': fornecedor_filter.form } if request.htmx: return render(request, "compras/partials/fornecedor-lista.html", context) return render(request, "compras/fornecedores.html", context) elif request.method == 'POST': form = NewFornecedor(request.POST) if form.is_valid(): form.save() messages.success(request, 'Fornecedor adicionado com sucesso.') return redirect("compras:fornecedores") else: print(form.errors) return render(request, "compras/fornecedores.html", {'form': form, 'all_forn': all_forn, 'filter': fornecedor_filter.form}) This is my template: fornecedores.html {% extends "compras/layout.html" %} {% load crispy_forms_tags %} {% load static %} {% block body %} <div … -
Gmail API Not Sending Email Attachments with PDF in Django
I'm using the Gmail API to send emails with PDF attachments from my Django backend, but the attachment is not appearing in the email — only the email body is received. Here are the logs showing the PDF is generated and attached correctly: [DEBUG] Generated PDF size: 16988 bytes[DEBUG] Attaching PDF: invoice_EJ70FEX.pdf (size: 16988 bytes) [INFO] Email sent successfully. Message ID: 19561950e1b649a0 However, when I receive the email, no attachment is visible. Here's the email-sending code I'm using: from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.conf import settings from email.utils import formataddr import base64 logger = logging.getLogger(__name__) def send_damage_invoice(driver_data, pdf_content): """Send damage invoice email with PDF attachment.""" try: logger.debug("Preparing damage invoice email for %s (%s)", driver_data['name'], driver_data['vrm']) subject = f'Damage Charges Invoice - {driver_data["vrm"]}' from_email = formataddr(('H&S Autocare', settings.DEFAULT_FROM_EMAIL)) to_email = driver_data['email'] # Create context for email template context = { 'driver_name': driver_data['name'], 'vrm': driver_data['vrm'] } # Render email content html_content = render_to_string('emails/damage_invoice.html', context) text_content = strip_tags(html_content) # Create email message email = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=[to_email] ) email.attach_alternative(html_content, "text/html") # Attach PDF filename = f'invoice_{driver_data["vrm"]}.pdf' logger.debug("Attaching PDF: %s (size: %d bytes)", filename, len(pdf_content)) email.attach(filename, pdf_content, 'application/pdf') email.send(fail_silently=False) logger.info("Email sent successfully to %s", … -
Django Webhook Unauthorized Issue on Azure Despite Successful Local Testing
I have a Django + React project hosted on Azure. I'm using Azure Postgres as my database, and my webhook handler is set up to receive events from an external API (Seal Subscriptions). The webhook subscriptions/create event sends a POST request to my Django backend at: https://vitaverde-backend.greensky-92f80007.eastus.azurecontainerapps.io/shopify/webhook/subscription/ However, I keep getting the following error in my Azure backend log stream: ws 11 128676314590080 Received webhook request 2025-03-04T00:39:38.1700588Z stderr F ERROR 2025-03-04 00:39:38,169 views 11 128676314590080 Unauthenticated user request 2025-03-04T00:39:38.1701766Z stderr F WARNING 2025-03-04 00:39:38,170 log 11 128676314590080 Unauthorized: /shopify/webhook/subscription/ Debugging Steps Taken Tested Webhook Locally: I wrote a test_webhook.sh script, which successfully sends a POST request with the correct headers and HMAC signature. The webhook persists data correctly to my Azure Postgres DB. Test Script: #!/bin/bash PAYLOAD='{"test": true, "customer": {"first_name": "Test", "last_name": "User", "email": "test@example.com"}}' SEAL_SECRET="seal_secret_****************************" SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SEAL_SECRET" | cut -d' ' -f2) curl -X POST \ "https://vitaverde-backend.greensky-92f80007.eastus.azurecontainerapps.io/shopify/webhook/customer-creation/" \ -H "Content-Type: application/json" \ -H "X-Seal-Token: seal_token_*************************" \ -H "X-Seal-Hmac-Sha256: $SIGNATURE" \ -d "$PAYLOAD" \ -v echo -e "\n\nPayload: $PAYLOAD" echo "Signature: $SIGNATURE" Ensured CSRF Exemption for Webhook: In settings.py, I added the webhook endpoint to CSRF_EXEMPT_URLS: CSRF_EXEMPT_URLS = [ 'shopify/webhook/subscription/', 'shopify/webhook/customer-creation/', 'api/customer/webhook/seal-delivery/', ] … -
What is the proper way to handle saving a large amount of huge graphs
I currently use Django 4.2.5 and django-rest-framework 3.14.0. I need a way to handle saving a large amount of huge graphs ~1_000_000 of ~5_000 node's graph. My current database is mariadb, MySQL. I found a lot of different solutions: A graph oriented database such as Neo4j Using SQL relations, by having and intermediate database for parents / children relations Using JSON data and re-construct graph when need it in graph form But none of these solutions are fully advantaging. What solution would you recommend and why ? -
Is it a good idea to let Django server React? What are the pros and cons?
I am thinking to combine Django and React, meaning to deploy them together on a single server. May I know if it is a great idea to do so? Are there any pros and cons of that approach? Let me know your comments. Thanks in advance! I just wanted know whether if it is a great idea or not. -
Django How to deal with database locking
I have two functions, periodic_signals(), and update_choice(), and use postgres. update_choice() is called once users make a new choice, and update the database. periodic_signals() is called every 0.1s using Threading.timer, and reads users' choices from the database, and do some stuffs, then send signals back to users, and plot them in real time. When periodic_signals() is called every 1s, I don't have any problems. When periodic_signals() is called every 0.1, everything I call update_choice(), there is a pause in my plot, and I can see the execution time of update_choice() increases 10x. Is it because I read and write to the same row almost at the same time, causing database locking? How can I solve it, except to improve the performance of these two functions (at the moment both function take about 0.005-0.02s depending on the number of users)?