Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optimizing Image Filtering and Color Selection in Django Product Display
I created three models In Models.py: class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL ,null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" So In my admin pannel Under Product Model it is creating two subparts one is General and other is Product Images--->Product model view and the product images will look like this--->Product Images In the General section I am uploading the main product image <div class="left-column"> {% for p in products %} {% for c in colors %} {% for x in p_image %} <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#1 <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#2 <img data-image="{{c.id}}" class="active" src="{{p.image.url}}" alt=""> #3 {% endfor %} {% endfor %} {% endfor %} </div> And displaying the main image in the frontend by #3 html code and I also want to display other images.My product detail page will … -
Sign up doesnt work when i include the firstname and last name in django
I created my signUp template at first with email, username, and password fields and a user was able to signUp successfully, But when i added the first_name, Last_Name and Phone fields I started getting a MultiValueDictKeyError evrytime a user tries to signup... I'm requesting for help on this😭😭😭😭 def signup(request): if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(username = username).exists(): messages.error(request,"Username already exists.") return render(request, 'registration\signup.html') elif User.objects.filter(email = email).exists(): messages.error(request,"email already exists.") return render(request, 'registration\signup.html') else: NewUser = User.objects.create_user(first_name, last_name,username, email, password,phone) NewUser.save() messages.success(request, "Your account has been successfully created you will be redirected to the login page") return redirect('home') else: messages.error(request,"Passwords do not match.") return render(request, 'registration\signup.html') return render(request, 'registration\signup.html') this is the form <div class="row "> <div class=" form_container col-5 my-1 " style=" height: 500px; border: 2px solid rgb(10, 43, 151); border-radius: 5px;margin-left: 30%;"> <form class="overlay" action="{% url 'signup' %}" method="post" style="background-color:trasparent;border-radius: 5px;margin-left: 0%;"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <label style="color: aliceblue;" for="fisrt_nam">First Name</label> <input type="text" id="fisrt_nam" class="form-control" name="fisrt_name" placeholder="fisrt name" required> </div> </div> <br> <div class="col-md-6"> <div class="form-group"> <label … -
Django 5 and Py 3.11.1 support for field encryption [closed]
A Customer want to have a field encryption for his Django Backend. Backend is running on Django 5 and Python 3.11.1. E2E Encryption from frontend side is currently not possible. I know that field encryption make his application not really more safe but I guess thats just requirements for marketing and the good feeling for the clients. Of cource we do everything possible to protect the System around from common attacks. My Problem is now that I can't find a Library that officially suports field encryption with Django 5 and Python 3.11.1. We run PSQL so a lib with pg_crypto support would be nice. I dont really like the idea to use an old library for such an important feature. I'm afraid to destroy my data when Security and Bug Fixes are not longer suported for the current version I'm working on. I searched several libraries and didn't found any hint for django 5 or python 3.11.1 support. Even the core library cryptography says nothing about 3.11.1 support. -
How to host my reactjs and django application on go daddy
I have a web application which uses reactjs for the frontend and django for the backend. I want to now host this on go daddy. I have a domain purchased as well as a hosting plan. I am just very confused on where to upload all my files. Any help would be appreciated -
How to use ManyToManyField for self class
I have one Model inside my models.py named Account In this case I wanna create a field in which I can choose my own Model Objects. for example if I had 3 Accounts {Jack, Harry, Helena} I want to choose the accounts I want between them. Actually I just want to create a Following System. Jack can follow Harry and Helena & also Helena can follow Jack or Harry How can I do that guys? Account class inside models.py class Account(models.Model): username = models.CharField(max_length=100) following = models.ManyToManyField(**Account**, blank=True) -
Private/offline LLM Chatbot on trained data
I have created a Django project with one model. And from admin portal, I will add the question and response which inserts data into postgres DB. Now, I'm trying to create an LLM chatbot for questioning and answering purpose on Postgres data and The user should be able to ask questions and chatbot must answer based on DB data. And, I am want to do with with any private/offline LLM model to secure it. I see, this can be achieved with Llama, Hugging face. But, not able to find any proper document/link to implement this. I am new to this. Can someone help to share links or any suggestions on this ? -
Django - Authentication using only a password
I need to implement authentication using only a password. I know that for security reasons this is not recommended, but I need this approach because it logs in using only RFID codes. I could treat this code as a regular field (not a password) and just retrieve the user with this code, but I want to hash this value so I iterate through all users using check_password. [models.py] class CustomUserManager(BaseUserManager): def create_user(self, password=None, **extra_fields): user = self.model(**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(**extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return self.username @property def full_name(self): return f'{self.first_name} {self.last_name}' [views.py] def login_view(request): if request.user.is_authenticated: return redirect(reverse('home')) if request.method == 'POST': password = request.POST.get('rfid_code') user = authenticate(request, password=password) if user is not None: login(request, user) return redirect(settings.LOGIN_REDIRECT_URL) return render(request, 'account/login.html') [backend.py] class CustomAuthenticationBackend(BaseBackend): def authenticate(self, request, password=None): try: User = get_user_model() for user in … -
How can i run the existing Django project in my mac
I am trying to run the Django project in my machine and i have cloned it. Now i directly run the the Project by python3 manage.py runserverand after that i got the error like this 192:vehiclerent vishal$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 1052, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 989, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1381, in _gcd_import File "<frozen importlib._bootstrap>", line 1354, in _find_and_load File "<frozen importlib._bootstrap>", line 1318, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mathfilters' Can anyone help how can i resolve this and explain what's happening. -
Issue with Registration: User Data Not Saving to Database (Django)
I've developed registration functionality for my web application using a combination of form elements, a view, a registration template, and JavaScript modals. However, despite completing the registration process, the user data is not being saved to the database as expected. Details: Form: I have implemented a form for user registration. View: A corresponding view function handles the registration process. Template: I've created a registration template for rendering the registration form. JavaScript Modals: Modal dialogs are used for user interaction during the registration process. Problem Statement: When I submit the registration form, the user data does not get stored in the database. I've verified that the form submission is successful, but somehow the data isn't persisting. Expectation: Upon successful submission of the registration form, the user data should be saved to the database for future reference and authentication purposes. Request for Assistance: I'm seeking guidance on what could be causing this issue and how to troubleshoot it effectively. Any insights, suggestions, or potential solutions would be greatly appreciated. Thank you! My code: Base code, containing JavaScript modals: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" … -
Custom system checks are getting ignored
Recently, I implemented a custom system check in our project. This check performs assertions based on our custom implementation of Django Rest Framework's model serializers. For debugging purposes on Visual Studio Code, I am using the debugpy package in conjunction with a Docker Compose setup. I followed this article to set it up. After configuring the debugger, I noticed that my custom system checks were not functioning properly. Upon further troubleshooting, I realized that it was due to a configuration I made in the manage.py file as mentioned in the article. In the article, they recommend adding the following code block to the manage.py file: # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 3000)) print('Attached!') # end new section However, when this code block is present, my custom system checks are completely ignored. If I comment out or remove this code and save the file, the system checks are triggered successfully. I'm unsure why this issue is occurring. Has anyone else encountered a similar problem where custom system checks were being ignored? Thank you in advance for your assistance. -
Optimizing Image Filtering and Color Selection in Django Product Display
I created three models In Models.py: class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL ,null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" So In my admin pannel Under Product Model it is creating two subparts one is General and other is Product Images--->Product model view and the product images will look like this--->Product Images In the General section I am uploading the main product image <div class="left-column"> {% for p in products %} {% for c in colors %} {% for x in p_image %} <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#1 <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#2 <img data-image="{{c.id}}" class="active" src="{{p.image.url}}" alt=""> #3 {% endfor %} {% endfor %} {% endfor %} </div> And displaying the main image in the frontend by #3 html code and I also want to display other images.My product detail page will … -
Django Rest Framework + Django Channels -> [Errno 111] Connect call failed ('127.0.0.1', 6379)
I am programming a project with Django (4.2.6), Django Rest Framework (3.14.0), Channels (4.0.0) and Channels-Redis(4.2.0), which acts as a backend for a mobile application. So far, I haven't had any problems with the Rest API connections and the endpoints I developed. I try to test the connection through websockets, but I get the following error: Exception inside application: Error connecting to localhost:6379. Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379). Traceback (most recent call last): File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/redis/asyncio/connection.py", line 274, in connect await self.retry.call_with_retry( File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/redis/asyncio/retry.py", line 59, in call_with_retry return await do() File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/redis/asyncio/connection.py", line 681, in _connect reader, writer = await asyncio.open_connection( File "/usr/lib/python3.10/asyncio/streams.py", line 48, in open_connection transport, _ = await loop.create_connection( File "/usr/lib/python3.10/asyncio/base_events.py", line 1084, in create_connection raise OSError('Multiple exceptions: {}'.format( OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) File "/home/tecnicus/Documentos/Repositorios/virtualenvs/virtualenv1/lib/python3.10/site-packages/channels/routing.py", line 116, in __call__ return await application( File … -
View XPS and PDF in browser
I need to set up document viewing in the browser. The documents could be either in PDF or XPS formats. I attempted to use an iframe. While PDF documents are being displayed, XPS ones are being immediately downloaded. My project is built on Django. Is there a way to display XPS files? My JS: function displayFile(element) { var objectId = element.id.substring('categories_'.length); var project_id = '{{ project.id }}'; var url = `/pilot_doc/get_file/${objectId}/${project_id}/`; var options = { method: 'GET', headers: { 'Accept': 'application/octet-stream' } }; fetch(url, options) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { if (data.status === 'success') { var byteCharacters = atob(data.file); var byteNumbers = new Array(byteCharacters.length); for (var i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); fileName = data.file_name; fileExtension = getFileExtension(fileName); console.log(fileExtension); var contentType; if (fileExtension === 'pdf') { contentType = 'application/pdf'; } else if (fileExtension === 'xps') { contentType = 'application/vnd.ms-xpsdocument'; } else { throw new Error('Unsupported file format'); } var blob = new Blob([byteArray], {type: contentType}); var url = URL.createObjectURL(blob); var iframe = document.createElement('iframe'); var docBox = document.querySelector('.box.doc'); var heightInPixels = docBox.offsetHeight; iframe.style.width = "100%"; … -
How can I pass context from one serializer to another in DRF [2024]?
I have seen many duplicate threads on this, most notably this context in nested serializers django rest framework, but none have worked for me. I have tried most solutions I see in every thread most notably CustomSerializers, using parents init(), and using parents to_representation(), but the context never passes from parent to child. Apparently it is supposed to pass automatically as of the newer django versions but it doesnt for me. (Django 5.0.2) In my example I serialize a post which's comments are serialized by calling the comment serializer. For every comment being serialized, I want to check if the user has voted on it yet by creating a field user_vote. When I print the request from the parent it prints normally, however from the child it request is empty. Serializers.py class CommentSerializer(ModelSerializer): child_comment = serializers.SerializerMethodField() user_vote = serializers.SerializerMethodField() class Meta: model = Comment fields = '__all__' def get_user_vote(self, obj): # Get the current user from the request print(self.context, file=sys.stderr) user = self.context['request'].user # Check if a vote exists for the current user and comment try: vote = Vote.objects.get(user=user, comment=obj) return vote.value except Vote.DoesNotExist: return 0 class PostSerializerSingle(ModelSerializer): images = SheetMusicImageSerializer(many=True) comments = CommentSerializer(many=True) class Meta: model = Post fields … -
How to connect react frontend to django backend
I am having trouble getting my react frontend and django backend to work together I have a client Registration form and here it is import React, { useState } from 'react'; import axios from 'axios'; import '../css/Clientregistration.css'; function ClientRegistration() { const [userData, setUserData] = useState({ entityName: '', organizationStatus: '', estYear: '', proprieterName : '', officeAddress : '', branchAddress : '', companyPerson : '', companyDesignation : '', compnayNumber : '', companyFax : '', companyEmail : '', industryNature : '', companyCIN : '', companyPAN : '', companyGST : '', bdpName : '', bdpmName : '', accountManager : '', billingCity : '', billingCountry : '', }); const handleInputChange = (event) => { const { name, value } = event.target; setUserData({ ...userData, [name]: value }); }; const statusOptions = [ 'Proprietorship', 'Private Limited', 'Public Limited', ]; const industryOptions = [ 'Communcations', 'Consulting', 'Education', 'Financial services', 'Healthcare', 'IT Services', 'Manufacturing', 'Pharma', 'Real estate', 'Technology', 'Data Center', 'Semiconductor', 'Insurance', ]; const backendBaseUrl = 'http://your-django-backend-url/api/'; const handleSubmit = async (event) => { event.preventDefault(); try { const response = await axios.post(`${backendBaseUrl}clientregistration/`, userData); console.log('Form submitted successfully:', response.data); // You can add any additional logic here after the form is successfully submitted } catch (error) { console.error('Error submitting form:', error); … -
i am unable to see the image. so please help me . and i am working with django templates
i am unable to get pictures. I have checked in settings.py file and also the html file . but everything is okay but it is not working . please help me to resolve this . the path of files and css files everything is okay. and also i inspect the code but everything is okay. the inspection told me that the file is not exist . but it exist -
Django - Modified Admin Form Returning an Object Instead of Text
I am trying to customize an Admin form on a Django site so that one of the fields is changed from a text field to a select widget pre-populated by grabbing all the serial numbers from a table of locations (each has a unique number). forms.py class SglnModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.sgln + ":" + obj.name class EndpointForm(forms.ModelForm): sgln = SglnModelChoiceField( queryset=Location.objects.all(), to_field_name="sgln", label="Endpoint SGLN", required=True, ) login = forms.CharField(label='Endpoint Login', max_length=32, required=True) password = forms.CharField(label='Endpoint Password', max_length=32, required=True) admin.py from django.contrib import admin from .forms import EndpointForm from .models import Endpoints class EndpointAdmin(admin.ModelAdmin): form = EndpointForm admin.site.register(Endpoints, EndpointAdmin) The form looks fine: Django Admin Form The HTML looks fine: [HTML picture] (https://i.stack.imgur.com/n4eqG.png) But the database is showing a "object(1)" as being inserted along with the rest of the fields. This should be a serial number pulled form the select tag. Database row Any hints as to why this is happening? -
How can I create a Django band website, that allows a user to login and logout
Im reuired to build a small website (for example, a simple site for a fictional band, or political candidate) using Django. ● Ensure your site has at least 3 pages and at least 1 database-driven component. ● Include user login and authentication. ● Try to make your submission as comprehensive as possible. I did manage to run the server but it takes me to a webpage that says I have succefully ran Django. And what I want is a webpage that allows the user to log in, log out. be able to navigate on the website. In the case a music website where the user can also be able to add albums and see the list of added websites. I did manage to run the server but it takes me to a webpage that says I have succefully ran Django. And what I want is a webpage that allows the user to log in, log out. be able to navigate on the website. In the case a music website where the user can also be able to add albums and see the list of added websites. -
502 Bad Gateway Error Deploying Django App to GCP App Engine with Gunicorn
I've successfully deployed my Django application to Google Cloud Platform's App Engine, but when trying to access it via the provided URL, I encounter a "502 Bad Gateway" error served by Nginx. Locally, my application runs fine using Waitress (for testing purposes), and I'm able to access it through a browser without any issues. Here's a brief overview of my setup: Environment: Python 3.11 Framework: Django 4.1 WSGI Server for Deployment: Gunicorn Deployment Platform: Google Cloud Platform App Engine Error Message: "502 Bad Gateway nginx" My app.yaml looks like this: runtime: python311 service: forecasting-django-app entrypoint: gunicorn -b :$PORT sales_forecasting.wsgi:application handlers: - url: /static/ static_dir: staticfiles/ - url: /.* script: auto And my project structure: sales_forecasting/ forecasting/ (Django app) sales_forecasting/ (Django project) staticfiles/ app.yaml main.py manage.py requirements.txt results.json Upon reviewing GCP logs, I noticed an error suggesting that a worker was killed, potentially due to running out of memory: [ERROR] Worker (pid:17) was sent SIGKILL! Perhaps out of memory? What I've tried so far: Ensuring gunicorn is properly installed and works locally. Checking that static files are correctly configured and collected. -
rabbitmq "PLAIN login refused: user 'myuser' - invalid credentials"
I am trying to set-up production Django app with Celery and Rabbit-MQ but have problem with authentication. I've added a user myuser: sudo rabbitmqctl add_user myuser mypassword sudo rabbitmqctl add_vhost myvhost sudo rabbitmqctl set_user_tags myuser mytag sudo rabbitmqctl set_permissions -p myvhost myuser ".*" ".*" ".*" If I run sudo rabbitmqctl authenticate_user myuser it authenticates correctly. But my Django app cannot authenticate: 2024-03-05 00:43:37.630 [info] <0.2106.0> accepting AMQP connection <0.2106.0> (127.0.0.1:42276 -> 127.0.0.1:5672) 2024-03-05 00:43:37.631 [error] <0.2106.0> Error on AMQP connection <0.2106.0> (127.0.0.1:42276 -> 127.0.0.1:5672, state: starting): PLAIN login refused: user 'myuser' - invalid credentials 2024-03-05 00:43:37.632 [info] <0.2106.0> closing AMQP connection <0.2106.0> (127.0.0.1:42276 -> 127.0.0.1:5672) My Celery broker url: CELERY_BROKER_URL = 'amqp://myuser:mypassword@localhost:5672/myvhost' Any idea what can cause it? -
How to add multiple categories to a model using a form in Django?
I have a model called BlogPost and one called Category, each BlogPost can have multiple categories. When creating posts from the admin panel I have no problems, but when trying to implement a form that creates a BlogPost so users can create posts I get an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use categories.set() instead. I tried reading the documentation but there's something that I'm not understanding because it's not working. My models are this; class BlogPost(models.Model): title = models.CharField(max_length=250) content = models.TextField() post_author = models.CharField(max_length=30) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='blog/files/blog_images') categories = models.ManyToManyField('Category', related_name='posts') #Relaciona el atributo con la clase Category y permite usar category.posts def __str__(self): return self.title class Meta: verbose_name = "blog post" verbose_name_plural = "blog posts" class Category(models.Model): cat_name = models.CharField(max_length=50) def __str__(self): return self.cat_name class Meta: verbose_name = "category" verbose_name_plural = "categories" This is the form: class newPostForm(forms.Form): CATEGORIES = ( (1, "Agua dulce"), (2, "Agua marina"), (3, "Primer acuario"), (4, "Alimentación") ) título = forms.CharField(max_length=250) contenido = forms.CharField( widget=forms.Textarea() ) imagen = forms.ImageField() autor = forms.CharField() categorias = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple ) And this is the view: def new_post(request): if request.method == "POST": … -
Django queryset - exclude True values
I am tryig to build a queryset where only the false values are added. Models Models reference = models.CharField(validators=[MinLengthValidator(15)], max_length=25, primary_key=True) h0730 = models.BooleanField(default=False) h0800 = models.BooleanField(default=False) h0830 = models.BooleanField(default=False) h0900 = models.BooleanField(default=False) h0930 = models.BooleanField(default=False) h1000 = models.BooleanField(default=False) h1030 = models.BooleanField(default=False) h1100 = models.BooleanField(default=False) h1130 = models.BooleanField(default=False) h1200 = models.BooleanField(default=False) h1230 = models.BooleanField(default=False) h1300 = models.BooleanField(default=False) h1330 = models.BooleanField(default=False) h1400 = models.BooleanField(default=False) h1430 = models.BooleanField(default=False) h1500 = models.BooleanField(default=False) h1530 = models.BooleanField(default=False) delivery_date = models.CharField(max_length=8) is_cancelled = models.BooleanField(default=False) Views taken_slots = Order.objects.filter(delivery_date__exact=delivery_date).filter(reference__icontains=code).filter(is_cancelled=False) slots_remaining = ['h0730', 'h0800', 'h0830', 'h0900', 'h0930', 'h1000', 'h1030', 'h1100', 'h1130', 'h1200', 'h1230', 'h1300', 'h1330', 'h1400', 'h1430', 'h1500', 'h1530'] for slot in taken_slots: if slot.h0730 and 'h0730' in slots_remaining: slots_remaining.remove('h0730') if slot.h0800 and 'h0800' in slots_remaining: slots_remaining.remove('h0800') ... ... The above for loop works as is expected but I am trying to optimize the process. For example if there are 100 references for the day, "taken_slots" will will be iterated 100 times. The expected output after the for loop completes is that the "slots_remaining" list will only have the False values remaining, e.g. ref1 = h0730 and h0930 is True and every other slot False ref2 = h0900 is True and every other slot False ref3 = h1030 … -
ViewSets not Showing on DjangoRestFramework Despite Being Added on urls.py
I am building a Django project and am trying to add an application's viewset to the project's urls.py. I have already done it for many of my applications, but for some reason, I cannot view this one in my urls.py or my Djangorestframework viewer. I am struggling to understand why this is occurring. class EmailViewSet(viewsets.ViewSet): """ A ViewSet for sending emails based on a template. """ serializer_class = EmailTemplateSerializer queryset = EmailTemplate.objects.all() def get_queryset(self): return EmailTemplate.objects.all() urls.py for project ... router.register(r'profiles', ProfileViewSet, 'profile') router.register(r'emails', EmailViewSet, 'email') I can see my model in the admin panel but not in the DRF view. I have tried to change the viewset and add it directly, but I cannot seem to understand or see how I can get it to show up. -
How to pass parameters to a custom OneToOne model?
I'm trying to create a simple model where validotors and upload_to path of fields can be configured on a per-model basis. My current model: class SimpleThreePageModel(models.Model): def __init__(self, *args, screen_size=(0, 0), image_path="", **kwargs): super().__init__(*args, **kwargs) self.screen_size = screen_size self.image_path = image_path slide_title_1 = models.CharField( max_length=25, verbose_name="Page Title 1/3 (25 char)", null=True, ) slide_body_1 = models.CharField( max_length=280, verbose_name="Page Body 1/3 (280 char)", null=True ) slide_image_1 = models.ImageField( null=True, verbose_name="Page Image 1/3 ({} x {}} px)".format( self.screen_size.x, self.screen_size.y ), blank=True, upload_to=self.image_path, validators=( [ validate_image_file_extension, MediaSizeValidator(self.screen_size.x, self.screen_size.y), ] ), ) slide_title_2 = models.CharField( max_length=25, verbose_name="Page Title 2/3 (25 char)", null=True, ) slide_body_2 = models.CharField( max_length=280, verbose_name="Page Body 2/3 (280 char)", null=True ) slide_image_2 = models.ImageField( null=True, verbose_name="Page Image 2/3 ({} x {}} px)".format( self.screen_size.x, self.screen_size.y ), blank=True, upload_to=self.image_path, validators=( [ validate_image_file_extension, MediaSizeValidator(self.screen_size.x, self.screen_size.y), ] ), ) slide_title_3 = models.CharField( max_length=25, verbose_name="Page Title 3/3 (25 char)", null=True, ) slide_body_3 = models.CharField( max_length=280, verbose_name="Page Body 3/3 (280 char)", null=True ) slide_image_3 = models.ImageField( null=True, verbose_name="Page Image 3/3 ({} x {}} px)".format( self.screen_size.x, self.screen_size.y ), blank=True, upload_to=self.image_path, validators=( [ validate_image_file_extension, MediaSizeValidator(self.screen_size.x, self.screen_size.y), ] ), ) Now what I'd really like to do is something like: class MyModel(models.Model): three_page_presentation = models.OneToOneField( SimpleThreePageModel((3840,2160), "my_path"), on_delete=models.CASCADE, null=True ) But … -
Error during django-allauth[mfa] . could not build wheels for django-allauth
when i want to install django-allauth[mfa] i got this error : Using cached typing_extensions-4.10.0-py3-none-any.whl (33 kB) Building wheels for collected packages: django-allauth Building wheel for django-allauth (pyproject.toml) ... done WARNING: Building wheel for django-allauth failed: [Errno 2] No such file or directory: 'd:\\wpsystem\\s-1-5-21-474952578-913561270-2101499973-1001\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\\localcache\\local\\pip\\cache\\wheels\\84\\10\\7b\\c9dbe47c3a955c9fa89b5cae6891d952195bac10d4a6b3650c\\django_allauth-0.61.1-py3-none-any.whl' Failed to build django-allauth ERROR: Could not build wheels for django-allauth, which is required to install pyproject.toml-based projects what is it about how can i fix it? a little details : i cloned github of cookiecutter-django and tried to install dependencies through pip , but i encountered this error. i commented the line for django-allauth in requirements.txt file out , then after installing other dependencies finished i tried to install django-allauth[mfa] alone but still the above error came up in the powershell.