Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't retrieve images from filesystem with Next.js and Django
English is not my native language. I'm trying to deploy three Next.js apps and one Django API app(using Django ninja). the problem is I get "400 bad request" in my browser's console. https://MY_SERVER_DOMAIN/users/_next/image?url=https://MY_SERVER_DOMAIN/media/magazine/thumbnail/Methods-of-using-radish-in-diet.webp&w=1920&q=75 in local I can see the image but on production I get 400. my Nginx config: location /media/ { alias /home/USER/backend/media/; } location /api/v1 { include proxy_params; proxy_pass http://localhost:8000; } location /admin { include proxy_params; proxy_pass http://127.0.0.1:8000; } location / { include proxy_params; proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /doctors { include proxy_params; proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /users { include proxy_params; proxy_pass http://localhost:3002; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } I saw many errors like this this in /var/log/nginx/error.log: 2025/04/06 13:44:21 [error] 41446#41446: *1 directory index of "/home/USER/users-front/.next/static/media//" is forbidden, client: 5.125.0.145, server: 176.97.218.11, request: "GET /users/_next/image/?url=%2Fusers%2F_next%2Fstatic%2Fmedia%2Fdoctor.07a8ef12.jpg&w=96&q=75 HTTP/1.1", host: "MY_SERVER_DOMAIN", referrer: "https://MY_SERVER_DOMAIN/users" but it should retrieve the image from Django media directory("backend/media") not Next.js! -
CORS headers not being added in django
Preface, I am aware of django-cors-headers not work I am getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301. Here are the important parts of my settings.py. INSTALLED_APPS = [ ... corsheaders ... ] corsheaders is the last entry in INSTALLED_APPS MIDDLEWARE is: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware", ] So CorsMiddleware is at the top. And for CORS settings: CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_ALL_ORIGINS = True And ALLOWED_HOSTS is: ALLOWED_HOSTS = ['*'] Online, this seems to be all that's needed to get CORS headers, but I am not getting them in the response. How do I fix this? -
Django jalali leap year is wrong for 1403
In my django app. Im using django-jalali-date package with version 1.0.1 but 1403 leap year is wrong and it detect 1404 as a leap year. -
Htmx preload extension not working, default behaviour not firing network request on mouseover (with Django)
Hi anybody here used preload extension with htmx, I am using it with django. But htmx does not fire any request after setting preloading to mouseover (I am using the preload cdn for loading and it seems to be working.) ps. I am using django enter image description here -
Wagtail default template field in_preview_panel is fine in dev but fails in production
In the default template from Wagtail even mentioned online here, there is a part: {# Force all links in the live preview panel to be opened in a new tab #} {% if request.in_preview_panel %} <base target="_blank"> {% endif %} I extend this base template in my other templates. This is fine in dev, but when running the website in production, I face with this error: Exception while resolving variable 'in_preview_panel' in template 'home/home_page.html'. Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 880, in _resolve_lookup current = current[bit] ~~~~~~~^^^^^ TypeError: 'WSGIRequest' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 890, in _resolve_lookup current = getattr(current, bit) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'WSGIRequest' object has no attribute 'in_preview_panel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ^^^^^^^^ ValueError: invalid literal for int() with base 10: 'in_preview_panel' During handling of the above exception, another exception occurred: ... I have no clue on what in_preview_panel is and why it behaves different in dev and prod. If I remove it, this case of error will be resolved. I have … -
How to display an image as the current value to an ImageField in a DJango app
I have this form in a Django template: <form action="{% url 'MCARS:Service-Record' %}" method="POST"> {% csrf_token %} <div class="box-body"> {% for field in form %} {% if not forloop.counter|divisibleby:2 %} <div class="row"> {% endif %} <div class="col-md-6"> <div class="mb-3 form-element form-control"> {{ field.label_tag }} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.ClearableFileInput %} <div> <p>Current Image:</p> <img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; height: auto;"> </div> {% endif %} {{ field|add_class:'form-control' }} </div> </div> {% if forloop.counter|divisibleby:2 %} </div> {% endif %} {% endfor %} </div> <div class="text-end"> <button type="submit" class="btn btn-primary mt-2"><i class="mdi mdi-content-save"></i> Save</button> </div> </form> using this Model, lass Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) and this form class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ('user','memberId','invited', 'registered') There is one field in there called avatar. I get to this one part in the template: {% if field.ClearableFileInput %} <div> <p>Current Image:</p> <img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; … -
POST 405 (Method Not Allowed) Django REST
The problem is when sending a post request from the client to the django server. Both the client and the server are deployed locally. I've double-checked where the problem might be many times, so I'm attaching the code from the views and settings file. javascript code fetch('http://127.0.0.1:8000/products/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }) .then(response => response.json()) .then(data => console.log(data.basket)) .catch(error => console.error('Basket get error', error)); python code views: @csrf_exempt def get_all_products(request): if request.method == 'POST': try: data = json.loads(request.body) print(data) except Exception as e: return JsonResponse({'error': str(e)}, status=400) return JsonResponse({'error': 'Invalid request method'}, status=405) settings: ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mini_app', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'DELETE' ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:5500', 'http://localhost:5500' ] output in the python django console: Method Not Allowed: /products/ [05/Apr/2025 13:05:54] "POST /products/ HTTP/1.1" 405 35 output in the browser console POST http://127.0.0.1:8000/products/ 405 (Method Not Allowed) -
Reportlab cannot open resource when using Minio (S3) pre-signed link
I am using reportlab in a containerized Django project with django-minio-backend for storing user-uploaded images. I want to create a PDF that uses the uploaded image as the background. This is the code used to render the PDF from django_minio_backend import MinioBackendStatic from reportlab.lib.utils import ImageReader def render_pdf(data: dict, image_url: str) -> io.BytesIO: RGB_VAL = 50 # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Register the Open Sans Font font_file = MinioBackendStatic().open("/fonts/OpenSans-Regular.ttf") pdfmetrics.registerFont(TTFont("OpenSans", font_file)) # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer, pagesize=landscape(A4)) image = ImageReader(image_url) # <--------------- Problem Line! p.drawImage(image, 0, 0, width=A4[1], height=A4[0]) # Other Draw operations ... # Close the PDF object cleanly, and we're done. p.showPage() p.save() return buffer The Minio storage backend is running in a different container and returns a URL for the resource something like this. http://localhost:9000/media-root-storage/images/<My-Image-Name>.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=20250405T085308Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature> This is the error that I get Traceback (most recent call last): File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 643, in __init__ fp = open_for_read(fileName,'b') File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 534, in open_for_read return open_for_read(name,mode) File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 532, in open_for_read raise IOError('Cannot open resource "%s"' % name) OSError: Cannot open resource "http://localhost:9000/media-root-storage/images/<My-Image-Name>.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=20250405T085308Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>" I even tried to replace the hostname from … -
Safe keyword usage with Django-summernote inhibits word wrapping even with explicit word wrapping
I am trying to use summernote with django and am encountering this issue where if I paste 200 words of inline lorem ipsum text as a test in the texfield, it correctly shows the text, but in a single line that is too big and goes off screen to the right. Where as if i just paste the lorem ipsum as hard coded in the template, the word wrap works perfectly fine. I use tailwind here: <div class="prose max-w-full break-words"> {{ post.content | safe }} </div> The content field is a is a text field: content = models.TextField() I tried adding the linebreaks keyword and setting the word-wrap to break word but it did nothing: <div class="prose max-w-full break-words" style="word-wrap: break-word;"> {{ post.content | safe }} </div> -
Django ModelForm ensuring FK integrity without using it in the form
I have a User Profile model with a Model Form: class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) state = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) facebook = models.URLField(null=True, blank=True) Twitter = models.URLField(null=True, blank=True) LinkedIn = models.URLField(null=True, blank=True) Instagram = models.URLField(null=True, blank=True) Snapchat = models.URLField(null=True, blank=True) website = models.URLField(null=True, blank=True) class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ('user','memberId','invited', 'registered') I don't want user in the form, but remember who the user is, when saving back to the model. How do I ensure that? Without it, the compiler throws a FK integrity error. This is what I have the view: @login_required() def Profile(request, memberid=None): if memberid: user = User.objects.select_related('profile').get(id=memberid) else: user = User.objects.select_related('profile').get(id=request.user.id) errors = None if request.method == 'POST': print('found me') data = request.POST form = UserProfileForm(data) form.user = user if form.is_valid(): form.save() else: print('form is invalid') errors … -
How can I test my Django & React app with massive users efficiently?
I'm working on a Django backend and a React frontend, and I need to test my app with a large number of users. I have used Cypress for UI testing, but it takes too much time to complete the tests I need. My goal is to test two different scenarios: First scenario (8,840 users) Register a user Modify user details Create a contribution Second scenario (~300,000 users) Perform the same process as the first scenario but on a much larger scale I'm looking for a faster and more efficient way to execute these tests. -
Initiate paypal payment post request returning 404 error, but the url mapping in django backend is correct, no syntax errors in React frontend
My React and Django website is deployed on render, when i run the backend service from render the initiate paypal payment url is mapped there, i also checked Django urls its there, but when i send the post request from the frontend, i get a 404 error and iyour text checked properly i have no syntax errors, am sending the correct data to the backend, forward slash is there. Am using Sandbox mode, i removed the client id and secret id from settings.py and i placed them in render's environment variable, so this is how i access them: PAYPAL_CLIENT_ID = os.getenv('PAYPAL_CLIENT_ID') PAYPAL_SECRET_CLIENT = os.getenv('PAYPAL_SECRET_CLIENT') i feel like whenever i click on the 'pay with Paypal button' so as to send the request, something blocks it hence the 404 error. website link, please you can use fake filter extension to login and help me checkout the problem Also : No CORS-POLICY issues the frontend Url is correctly placed in the allowed origins the REACT_BASE_URL is also correctly placed in my settings.py and views.py i just don't no what the problem is, i have so far tried everything, any one who can help me, i appreciate thank you backend code @api_view(['POST']) def … -
Django shell: Can't find constructor of a model
I have a Django Modell Kunde from django.db import models class Kunde(models.Model): Kundennummer = models.IntegerField(), Vorname = models.CharField(max_length=200), Nachname = models.CharField(max_length=200) I open the Django shell with the command python manage.py shell I do from kundenliste.models import Kunde; and then Kunde.objects.all() This gives me <QuerySet []> Now I would like to insert a new customer But k1 = Kunde(Kundennummer=1,Vorname="Florian",Nachname="Ingerl"); gives me the error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\imelf\Documents\NachhilfeInfoUni\MaxPython\env_site\Lib\site-packages\django\db\models\base.py", line 569, in __init__ raise TypeError( TypeError: Kunde() got unexpected keyword arguments: 'Kundennummer', 'Vorname' What do I do wrong? -
Python: Can't find command virtualenv
I have the python installed from here: Python download link The command python --version gives me Python 3.12.2 I want to create a virtual environment in order to use it for a Django project. pip install virtualenv works fine. But afterwards , the command virtualenv env_site gives me the error virtualenv : Die Benennung "virtualenv" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang. In Zeile:1 Zeichen:1 + virtualenv env_site + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException In my path variable, I have the following entries C:\Software\Python\Python312\Scripts\ C:\Software\Python\Python312\ C:\Users\imelf\AppData\Local\Programs\Python\Launcher\ What is wrong? Why doesn't he recognize the command virtualenv ? -
Cant find command virtualenv env_site
I have the python installed from here. www.python.org/downloads the command python --version gives me Python 3.12.2 I want to create a virtual environment in order to use it for a Django project. pip install virtualenv work fine, but afterwarnds, the command virtualenv env_site gives me the error: virtualenv : Die Benennung "virtualenv" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang. In Zeile:1 Zeichen:1 virtualenv env_site + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException In my path variable, I have the following entries. C:\Program Files\Python313\Scripts\ C:\Program Files\Python313\ C:\Users\Max\AppData\Local\Programs\Python\Launcher\ If someone can help me, that would be nice. -
Custom text in Django admin is not translating
I have a Django project where I need to localize the admin panel into two languages. It seems like I'm following the instructions, but for some reason, my custom translation isn't working. Below, I’ve attached the configuration files. #settings.py USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [BASE_DIR / "locale"] LANGUAGE_CODE = "ru" LANGUAGES = [ ("ru", _("Русский")), ("en", _("Английский")), ] #urls.py urlpatterns = [ path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns(path("admin/", admin.site.urls)) And specifically the usage #models.py from django.utils.translation import gettext_lazy as _ class Bot(models.Model): session_name = models.CharField(_("Имя сессии")) .po file #locale/en/LC_MESSAGES/django.po ... #: src/backend/bots/models.py:8 msgid "Имя сессии" msgstr "Session name" .po file compiled with the command python manage.py compilemessages In the admin panel, when changing the language, everything is translated except my custom translations. I also tried running the check through the shell. #Django shell from django.utils.translation import gettext as _, activate, get_language activate("en") print(_("Имя сессии")) # Имя сессии It feels like Django is ignoring my .po file And files tree . ├── locale │ └── en │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── manage.py ├── src │ ├── backend │ │ ├── core │ │ │ ├── __init__.py │ │ │ ├── … -
¿Cual es mejor en realizar consultas de bases de datos?
Estoy desarrollando una aplicación web con Django y necesito optimizar las consultas a la base de datos. ¿Cuál es la mejor práctica para mejorar el rendimiento en consultas SQL en Django ORM? -
Django app with Azure storage account - images are not saved to blob storage container
I have a Django app, and I am trying to store images in an Azure Storage account. I have a database with table category and property name images, where the URL of the uploaded image is saved when a user uploads an image. For example: media/photos/categories/Koesimanse.png However, the image is not being saved in the Azure storage container. When I try to access the URL: https://dier.blob.core.windows.net/media/media/photos/categories/Liza_GUAzhRg.jpeg Then I get this error: BlobNotFound The specified blob does not exist. RequestId:2bf5ff31-201e-0066-459e-a4a58e000000 Time:2025-04-03T13:45:48.5890398Z Additionally, when I check the blob container, the image is not there. However, if I manually upload an image to the Azure blob container and store its URL in the database, the image is successfully retrieved from Azure Storage blob container. So for the models I have this: class Category(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name="Naam") description = CKEditor5Field( max_length=11000, blank=True, null=True, verbose_name="Beschrijving", config_name="extends") images = models.ImageField( upload_to="media/photos/categories", blank=False, null=False, verbose_name="Foto") # Define the cropping field cropping = ImageRatioField('images', '300x300') category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='subcategories', blank=True, null=True, verbose_name="Categorie") date_create = models.DateTimeField( auto_now_add=True, verbose_name="Datum aangemaakt") date_update = models.DateTimeField( auto_now=True, verbose_name="Datum geupdate") def img_preview(self): if self.images and self.images.name: try: if self.images.storage.exists(self.images.name): print("IMAGES SAVED") print(self.images) return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') else: … -
Django superuser privileges
I am following Vincent's book, Django for Beginners, and I am on chapter 14. I have followed all the tutorial code to create a superuser and have granted it all of the permissions in the admin panel. However, when logged in as the superuser I am not able to delete or edit the posts of other users. Should the superuser be able to do this? Thank you for any insight. -
django.core.exceptions.ImproperlyConfigured:
I get this error all the time since two days now and i am stacked at this level? I am a beginner with django and i read the django documentation following all the instructions but always the same problem. Hello, I get this error all the time since two days now and i am stacked at this level? I am a beginner with django and i read the django documentation following all the instructions but always the same problem. django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pages.urls' from 'C:\Users\adech\mon_site\monsite\pages\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
django Pannel error Could not reach the URL. Please check the link
Here when i update my model i am getting this error why ? This is my models.py class ProductImage(models.Model): user = models.ForeignKey(Seller,on_delete=models.CASCADE, related_name='Product_Image_User') Video = models.FileField(upload_to="Product/video", blank=True, null=True) images = models.JSONField(default=list) # Stores multiple image URLs Date = models.DateTimeField(default=timezone.now) Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images", blank=False, null=False) secret_key = models.TextField(blank=True,null=True) def __str__(self): return f"{self.user}-{self.Product}-{self.id}" -
Django project - Redis connection "kombu.exceptions.OperationalError: invalid username-password pair or user is disabled."
Hello I'm trying to deploy my django app on railway. This app is using Celery on Redis. When I deploy the project the logs indicate: [enter image description here][1] As we see the initital connection is to redis is successful. However I as soons as I trigger the task (from my tasks.py file): the connection is lost: [enter image description here][2] The error indicates a "invalid username-password pair or user is disabled.". Nevertheless, I don't understand because my REDIS_URL is the same used for the initial connection when the project is deployed. In my logs I get extra info: [enter image description here][3] [1]: https://i.sstatic.net/3yAjMwlD.png [2]: https://i.sstatic.net/Cb0cY3Lr.png [3]: https://i.sstatic.net/XWwOvWdc.png tasks.py # mobile_subscriptions/tasks.py from celery import shared_task import time import logging logger = logging.getLogger(__name__) @shared_task def debug_task(): try: logger.info('Demo task started!') time.sleep(10) logger.info('Demo task completed!') return 'Demo task completed!' except Exception as e: logger.error(f"Unexpected error in debug task: {e}") raise celery.py: # comparaplan/celery.py import os from celery import Celery from dotenv import load_dotenv load_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'comparaplan.settings') celery_app = Celery('comparaplan') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() celery_app.conf.task_routes = { 'mobile_subscriptions.tasks.debug_task': {'queue': 'cloud_queue'}, } celery_app.conf.update( result_expires=60, ) settings.py """ Django settings for comparaplan project. """ import os import sys import time from pathlib import Path from … -
Django Select2 Autocomplete: How to Pass Extra Parameter (argId) to the View?
I'm using Django with django-autocomplete-light and Select2 to create an autocomplete field. The Select2 field is dynamically added to the page when another field is selected. It fetches data from a Django autocomplete view, and everything works fine. Now, I need to filter the queryset in my autocomplete view based on an extra parameter (argId). However, I'm not sure how to pass this parameter correctly. JavaScript (Select2 Initialization) function getElement(argId) { let elementSelect = $("<select></select>"); let elementDiv = $(`<div id='element_id' style='text-align: center'></div>`); elementDiv.append(elementSelect); $(elementSelect).select2({ ajax: { url: "/myautocomplete/class", data: function (params) { return { q: params.term, // Search term arg_id: argId // Pass extra parameter }; }, processResults: function (data) { return { results: data.results // Ensure correct format }; } }, placeholder: "Element...", minimumInputLength: 3 }); return elementDiv; } Django Autocomplete View class ElementAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView): def get_queryset(self): qs = MyModel.objects.filter(...) I want to pass argId from JavaScript to the Django view so that the queryset is filtered accordingly. However, I am not sure if my approach is correct or how to achieve this. Appreciate any suggestions or improvements. Thanks! -
I do not understand why in Django Rest Framework, my serializer do not serialize the file I gave it
I do not understand why in Django Rest Framework, my serializer do not serialize the file I gave it I do a request like this in my Vue.js file: const formData = new FormData(); formData.append("file", file.value); formData.append("amount_pages", "" + 12); try { const response = await fetch(BACKEND_URL, { method: "POST", body: formData, }); } catch (e: any) { console.error(e); } On a view like that in my Django/DRF app: from rest_framework import generics, serializers class MySerializer(serializers.Serializer): file = serializers.FileField(required=True) amount_pages = serializers.IntegerField() class Meta: fields = [ "file", "amount_pages", ] class MyView(generics.CreateAPIView): def post(self, request, *args, **kwargs): serializer = MySerializer(data=request.data) print(request.data) # <QueryDict: {'file': [<TemporaryUploadedFile: part1.pdf (application/pdf)>], 'amount_pages': ['12']}> print(serializer.data) # {'file': None, 'amount_pages': 12} I have already took a look at other issues but have not found any answers. -
Security on Webapp against hacking attempts
I hava a under-construction django webapp on Heroku. While checking the latest features on the logs, I read a great deal (several hundreds) of rapid succesion GET request, asking for passwords, keys, and other sensible credentials. This is new, we are only 2 people working daily on the website, and it makes no sense as the WebApp doesnt ask and doesnt have these credential, so they are hacking attempts. I know nothing about web security. Sorry if I am asking or saying obvious or wrong things My questions are: what to do now ? How do I prenvent these specific attacks from happening and been sucesfull ? How do I prevent other common attacks from happening and been sucesfull ? How can assets the webapp vulnerabilities ? I wrote the fwd="latest_ip" on https://www.iplocation.net/ip-lookup trying to know from where the attacks came from, but it shows widely different results. I imagine that I need a Firewall. But I dont know which rule I should apply, or if there is an option to protect from django (instead of the firewall), or other option. Reading https://devcenter.heroku.com/articles/expeditedwaf it seems that : CAPTCHA protection rule for the entire site (enter / as the URL) Country …