Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgresql + Django Development Server Won't Open in Browser (connection refused)
My attempt to create/integrate Postgresql database and run Django development server continues to fail and I've followed every step in this tutorial (search page for 'Setting Up PostgreSQL with Django'): (website 1) https://www.hostinger.com/tutorials/django-tutorial When I run the development server and type in the browser http://127.0.0.1:8000 to connect, I get a page cannot be reached. ERR_CONNECTION_REFUSED Thinking it is a firewall issue I then followed the instructions on this page to open both (8000 port & 5432 port to any ip address (I copied example 1 on the page) --> 5432 is the default PostgreSQL port so I included that as well with 8000 just incase, and it still does not work: (website 2) https://linuxconfig.org/how-to-open-allow-incoming-firewall-port-on-ubuntu-22-04-jammy-jellyfish I double checked and know that I entered in my settings.py file the correct Database engine, name, user, password, host, and port because I followed the steps in (website 1). And I tried opening both the 5432 and 8000 port to any ip address incase the page was not opening because of a firewall issue from the example 1 in (website 2). I don't know what else to do. Please help, I am so frustrated! -
Handling data for both JSON and FormData in Angular
So im kinda new to angular and django, but im trying to create a web app kinda similar to Amazon, where the user is able to log in and browse different listings from other user, create his own listings and do basic CRUD operations on his own listings. When creating a listing the user needs to add a title, description, price, location choose a category and subcategory, add values to the attributes, and he can attach images as files. In the database both categories and subcategories have their own "attributes" whose values also need to be inputed by the user. For an example a category is lets say "Pet", that will have a attribute lets say "Age", and for a subcategory "Dog" there will be an attribute "Breed". I found a tutorial online for adding images, and basically im sending them as files, and saving them in a folder on backend. When I try to add a listing, everything works fine except that the attributes are never added to the database. I added some console logs on front to see if im getting them and sending as json and I do, so I think that the problem is on backend … -
Looking for suggestion for "simplest possible" Django email-notification system
In my original website, I brought in "all of Pinax" just to do one(!) thing: to let me queue-up email message requests that would then be sent out, every fifteen minutes, by an externally executed "manage.py" command (every fifteen minutes). I have now realized the error of my ways. And so, kindly suggest to me the SIMPLEST current-Django package which would most easily do this one thing: it lets me queue an email-only message, and it implements a "manage.py" subcommand to send them. Who has already done: "this, just this?" (Trivial request, I know. But by now, I know it's far better to "ask the community" first ...) -
string_if_invalid django or ninja template: custom renderer in selected html string
i'm looking for a solution to selectively not replace missing variables/replace by whatever in django: I have a text, defined by a user, where he can insert variables {{model.myvar}}. In the backend, i render the text and the context to return a text which can be then modified if necessary. So far so good... For UX reasons, the variables can be entered at different times, and the text be generated at any time...So if all the var are not entered, there will be empty strings... What i'm looking for is a way to get the free text with variables, and "generate" it as often as wanted ! So the text is sent to the backend, if the corresponding var is in the context => var is replaced ! but if there is not: return {{myvar}}. Then the txt can be re-generated later with appropriate information ! I deeply searched for a solution with django template and jinja. Indeed i explored "string_if_invalid" for django: but apply in all the app and can create problems. I'm looking for a custom solution which i can apply selectively in selected parts of my codes... -Is it possible ? -How...?! Thanks for your help ! -
Create Post and Upload Multiple Files in Django
I have a table of animals. For each animal I have multiple images. I would like the user to be able to register a new animal and add multiple images to it in one form. As of now no records are created and I do not understand why. I've been struggelig this for hours. I know I could get there by using formsets but would prefer something like this. I suspect the view is causing this, but do not understand why. This is my not-working sollution: upl/models.py from django.db import models from django.core.exceptions import ValidationError def validate_img_extension(value): if not value.name.endswith(".jpg", ".jpeg", ".png"): raise ValidationError("Only .jpg, .jpeg og .png allowed.") class Animal(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) class AnimalImage(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) image = models.FileField(upload_to="products/", validators=[validate_img_extension]) upl/views.py from django.shortcuts import redirect, render from .forms import AnimalImageForm, AnimalForm from .models import Animal, AnimalImage def createAnimal(request): animalform = AnimalForm() imageform = AnimalImageForm() if request.method == "POST": animalform = AnimalForm(request.POST) imageform = AnimalImageForm(request.POST or None, request.FILES or None) images = request.FILES.getlist("image") if animalform.is_valid() and imageform.is_valid(): title = animalform.cleaned_data["title"] describ = animalform.cleaned_data["description"] animal_instance = Animal.objects.create(title=title, description=describ) animal_instance.save() for i in images: AnimalImage.objects.create(animal=animal_instance, image=i) return redirect("uplhome") context = {"animalform": animalform, "imageform": imageform} return … -
django allauth - ACCOUNT_UNIQUE_EMAIL doesn't prevent duplicate emails on signup
I'm making a basic website where users sign up with an email, a username, and a psssword. I'm using dj_rest_auth, which wraps allauth to provide a REST API interface. Here's an example registration call: POST: http://127.0.0.1:8000/api/auth/registration/ Body: { "username": "new_user3", "password1": "testtest@123", "password2": "testtest@123", "email": "h@h.com" } These are the flags I've set in settings.py: ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True Yet, when I send the registration request twice, and only change the username (not email), it goes through just fine: What's the easiest way to have this fail if the email is a duplicate? Ideally I'm looking for something the library itself provides, and not a custom class. -
Receiving Empty request.data When Invoking a Python Service Using Dapr: Bad Request Syntax (400)
I am encountering an issue while invoking a Python service using Dapr. The invocation consistently results in the following error: code 400, message Bad request syntax ('4') After investigating, I found that the error might be related to incomplete or missing order information. However, despite implementing the sample code provided in the Dapr documentation and making several adjustments, the issue persists. Observed Issue When invoking the service, request.data on the receiving end is always empty. As a temporary workaround, I routed the request through a gateway, which worked. However, this is not a sustainable solution for the long term. Environment Details Dapr SDK version: 1.12.1 (Python) Dapr runtime version: 1.12.5 Deployment platform: Azure containers Invocation method: Service-to-service using Dapr HTTP API Attempts to Solve Verified headers and content type (application/json) in the request. Tried different payload formats (stringified JSON and Python dictionaries). Referenced the official Dapr documentation and sample code. Question What could be causing request.data to be empty on the receiving side? Is there a specific configuration or step I might be missing for service-to-service invocation using Dapr in this environment? Additional Information I tried many solutions: Changing the code. Using direct information instead of the Dapr library. Modifying … -
Django crashes when I load a template with a 300,000+ character URI in it
I've put a data:image URI into my django template file (Jinja 2), and when I try to load the page that has this template, django crashes with no error messages. The URI is more than 300,000 characters long. How can I put this image in the page without the site crashing? -
Django keeps telling me that my superuser email violates unique constraint
I'm building a Django/DRF backend and keep getting this error when I try to create a superuser in cli: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint `"users_useraccount_email_key"` This is strange because I know that I'm using unique emails EVERY time I create a superuser. After inspecting the error message further, I noticed that it said the above exception was a direct cause of the following exception: ... lots of venv related files and then in my /users/managers.py, line 61 Which is just: user.save(using=self._db) At the bottom of the error is: django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_useraccount_email_key" DETAIL: Key (email)=(email@email.com) already exists. I'm using Postgres and using Postgres to generate the UUID, NOT python. class MyRandomUUID(Func): class RandomUUID(Func): template = 'GEN_RANDOM_UUID()' # template = 'UUID_GENERATE_V4()' output_field = 'UUIDField()' I am on Ubuntu and my virtual env is using Python v3.8, Django v4.17 and DRF v3.15. I know these versions are aging but its what the commands installed w/o giving specific versions. And I can no longer login to /admin either. It gives me this error(EVERY TIME): Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. BEFORE this, I was able … -
Django cannot connect to database in container
I have created docker-compose file version: "3" services: web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 depends_on: - postgresql volumes: - .:/app postgresql: image: postgres:latest environment: POSTGRES_DB: pgdb POSTGRES_USER: postgres POSTGRES_PASSWORD: admin ports: - "5432:5432" and when I run compose up, my db runs successfully, but eventually container with django cannot connect to my postgresql setting of project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'diary', # 'USER': 'postgres', # 'PASSWORD': 'admin', # 'HOST': 'localhost', # 'PORT': '5432' 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") } } dockers logs : 2025-01-13 21:35:18 web-1 | django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory 2025-01-13 21:35:18 web-1 | Is the server running locally and accepting connections on that socket? what can cause such error? Even tho in previous work with same properties all worked correctly -
Django Website throws error after spamming refresh
I have a Django 1.8.4 app that uses python 3.6.9. The problem occurs when i refresh the page like ~10-20 times. I get the following error: One refresh after the error and the website works again. It seems like the cache returns an error message instead of a file. The caching settings are as follows: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'OPTIONS': { 'MAX_ENTRIES': 10000, 'TIMEOUT': 604800, } } I checked memcached logs and I got these messages: Jan 13 16:38:21 ******* systemd[1]: Stopping memcached daemon... Jan 13 16:38:21 ******* systemd[1]: Stopped memcached daemon. Jan 13 16:38:21 ******* systemd[1]: Started memcached daemon. Which doesn't help much. I tried increasing the allocated memory, but the error occured when used up memory was ~160MB / 512MB so it seems like that's not the issue. Setting "Limit the number of simultaneous incoming connections" to 1024 also doesn't help. Does someone have an idead what might be happening? -
Django custom `get_or_create` on model with M2M through model
As title says I'm trying to implement get_or_create method which able to get or create instance with respect to through model. Models: class Component(models.Model): name = CharField() class ConfigComponent(models.Model): config = models.ForeignKey(Config) component = models.ForeignKey(Component) quantity = models.PositiveIntegerField() class Config(models.Model): components = models.ManyToManyField(Component, through="ConfigComponent") So basically I want to check if Config matching input data exists and use it if so. Otherwise - create a new one. But how to consider the quantity of each Component? It is not a big deal to find Config with exact num of components but it may appears that components match but their quantity is different. -
How to create list of object from 2 models with sorting in Django?
I have this model in Django: Class SmallNews(models.Model): date_news = modeles.DateField ... Class BigNews(models.Model): date_news = modeles.DateField ... I want to create list of object(SmallNews + BigNews) and sorting all this objects by DateField. What the best way to do this? -
REACT AND DJANGO
I am running django on port 8000 and react on port 3000 i want to run both on a single port and how should i do it when i deployed project i used all the methods and suggest me something different for this question in detailed format -
Django PIL image not resizing
I am trying to resize the profile picture for my profile model. And I am not seeing what I am doing wrong. Below is the code: def save(self, *args, **kwargs): super().save() img = Image.open(self.profile_picture.path) img.show() img_resized = img.resize((100, 100), Image.Resampling.LANCZOS) img_resized.save() I would like the code to be resized at the dimensions mentioned in the code. I am receiving no errors in the terminal during runserver. -
Issue - TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I tried everything to fix this issue, it is so frustrating!! After the registration (with React) I receive the verification email including the link. After I clicking the link the issue with the "TemplateResponseMixin" appears, no matter what I try... Here is my code, you can also find the complete on my GitHub repository: https://github.com/ChrisCross1983/pp5-paw_buddy: enter image description here views.py from allauth.account.views import ConfirmEmailView from allauth.account.models import EmailConfirmation, EmailAddress from django.views.generic.base import TemplateResponseMixin from django.http import JsonResponse, HttpResponse from django.template.response import TemplateResponse from django.views.generic import TemplateView from django.shortcuts import render from django.contrib.sites.models import Site import logging logger = logging.getLogger(__name__) class CustomConfirmEmailView(ConfirmEmailView): template_name = 'account/email_confirmed.html' def get(self, request, *args, **kwargs): print("DEBUG: CustomConfirmEmailView gestartet mit Key:", kwargs.get("key")) try: confirmation = self.get_object() print("DEBUG: Confirmation gefunden:", confirmation) confirmation.confirm(request) print("DEBUG: Benutzer erfolgreich bestätigt") user = confirmation.email_address.user user.is_active = True user.save() return JsonResponse({"message": "Email erfolgreich bestätigt"}) except Exception as e: print(f"DEBUG: Fehler in CustomConfirmEmailView: {e}") return JsonResponse({"error": str(e)}, status=400) def test_template_view(request): return render(request, 'account/email_confirmed.html', {"message": "Test erfolgreich"}) def account_inactive_view(request): logger.debug("Account Inactive View aufgerufen") return JsonResponse({"error": "Your account is inactive. Please confirm your email to activate it."}, status=403) def index(request): return render(request, 'index.html') urls.py: from django.contrib import admin from django.urls import path, include from project.views import CustomConfirmEmailView, … -
AttributeError: 'str' object has no attribute 'is_registered' in Django Custom Add Product Page
Title: AttributeError: 'str' object has no attribute 'is_registered' in Django Custom Add Product Page Problem Statement: I am creating a custom page in Django to allow users (staff members) to add a product. The product is defined in the Product model, which includes a ManyToManyField for Color. While the product creation works fine in the admin panel (with the ability to add new colors using the "plus" icon in the color field), this functionality does not work in my custom page. When attempting to wrap the widget for the color field using RelatedFieldWidgetWrapper, I encounter the following error: AttributeError at /useradmin/add_product/ 'str' object has no attribute 'is_registered' Below are the relevant code snippets and configurations. I’d appreciate any help identifying the issue and achieving the desired functionality. Models Product Model from django.db import models from taggit.managers import TaggableManager from shortuuidfield import ShortUUIDField from ckeditor_uploader.fields import RichTextUploadingField from django.utils.safestring import mark_safe 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) viewers = models.ManyToManyField('CustomUser', related_name="viewed_products", blank=True) cagtegory = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, related_name="category") subcategory = models.ForeignKey('SubCategory', on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategory") vendor = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True, related_name="product") main_product_color = models.ManyToManyField('Color_main', blank=True) color = models.ManyToManyField('Color', blank=True) size = models.ManyToManyField('Size', blank=True) title … -
How to resolve CORS issues with Django backend on Heroku for Flutter frontend?
I am working on a Django backend hosted on Heroku and a Flutter frontend hosted on https://anirni.web.app. My API requests are getting blocked due to CORS policy, and I'm struggling to configure Django to handle this properly **My current setup: ** Backend: Django hosted on Heroku. Frontend: Flutter app hosted on https://anirni.web.app and also tested locally (http://localhost:52360). CORS library: I'm using django-cors-headers. **Relevant parts of my settings.py: ** ` """ Django settings for anirni_server project. Generated by 'django-admin startproject' using Django 5.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ import os from pathlib import Path import dj_database_url from corsheaders.defaults import default_headers EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'mail.anirni-dz.com' # Remplacez par le serveur SMTP de Bluehost EMAIL_PORT = 465 # Port SMTP (généralement 587 pour TLS) EMAIL_USE_TLS = False EMAIL_USE_SSL = True # Activer SSL EMAIL_HOST_USER = '###' # Adresse email EMAIL_HOST_PASSWORD = '###' # Mot de passe DEFAULT_FROM_EMAIL = '###' # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent from corsheaders.defaults import default_methods # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Not able to start a dead letter queue (RabbitMQ / Celery)
I have defined task_queues = ( Queue('celeryDrawingRegister', Exchange('celeryDrawingRegisterExchange', type='direct'), routing_key='register.#', queue_arguments={ 'x-dead-letter-exchange': 'dlx_exchange' }), Queue('celeryDrawingRegisterDLQ', Exchange('dlx_exchange'), routing_key='dlq.#'), # Dead Letter Queue ) in my settings.py file, I then run my workers using elery multi start devCeleryDatasheetMaitainance devCeleryDocument devCeleryDrawingRegister -A imageTranslateApp -l info -P eventlet --loglevel=DEBUG -c:devCeleryDatasheetMaitainance 3 -c:devCeleryDocument 3 -c:devCeleryDrawingRegister 3 -Q:devCeleryDatasheetMaitainance celeryDatasheetMaintainance -Q:devCeleryDocument celeryDocument -Q:devCeleryDrawingRegister celeryDrawingRegister Now my normal workers and task works fine , but I can't use celeryDrawingRegister as Dead Letter queues to acknowledge task and then send it to celeryDrawingRegisterDLQ. What am i missing here?? P.S This is my Celery configuration import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'imageTranslateApp.settings') app = Celery() app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
I am getting a error: everse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\\Z']
am trying to run a Django site but have a error when i click on this url: 'book:genres' this is the error: Reverse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\Z'] something is wrong with this url: <a href="{% url 'book:genre' genre.id %}"> my models page: from django.db import models # Create your models here. class Genre(models.Model): """A Genre of a book""" text = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now=True) def __str__(self): """return a string representation of the model""" return self.text class Title(models.Model): """A Title of a book""" genre = models.ForeignKey(Genre, on_delete=models.CASCADE) text = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'titles' def __str__(self): """"Return a string rep of model""" return f"{self.text[:50]}" my veiws: from django.shortcuts import render # Create your views here. from .models import Genre def index(request): """Home page""" return render(request, 'book/index.html') def genres(request): genres = Genre.objects.order_by('date_added') context = {'genres': genres} return render(request, 'book/genres.html', context) def genre(request, genre_id): genre = Genre.objects.get(id=genre_id) titles = genre.entry_set.order_by('-date_added') context = {'genre': genre, 'titles':titles} return render(request, 'book/genre.html', context) my urls: """Defines url patterns for book app""" from django.urls import path from . import views app_name = 'book' urlpatterns = [ # Home page path('', views.index, name = 'index'), path('genres/', views.genres, name="genres"), … -
Django is adding slash into dynamic URL segment
I have a dynamic url configured like so: path('segment/', func1, name='func1'), path('segment/<str:string>/', string, name='string'), However, when I go to https://example.com/segment/watch?v=nTeq0U_V15U (watch?v=nTeq0U_V15U being the string), a slash is automatically added in middle, making it https://example.com/segment/watch/?v=nTeq0U_V15U/. Interestingly enough that does not throw a 404 error even though I have no URL pattern with 3 segments in urls.py. However, my question is why is the slash being added in, and how can I avoid it? -
Where to deploy real estate web app (django + django rest framework + reactjs + postgresql) with many images (kind of zillow.com)?
I developed a real estate web application with following design: database: postgresql backend: django, django rest framework frontend: reactjs. This app is a real estate application something like www.zillow.com. The idea is following: User registers on the platform, logs in to her/his account and publishes her/his properties. There can be uploaded up to 20 images and 1 obligatory video mp4 for every property. The images and video are stored in backend media/images and media/videos and their urls are stored in postgresql. As there are many platforms such as AWS, DigitalOcean, Render, fly.io, Vercel, Heroku, etc. I am not sure which one I should pick up for my project (Django, django rest framework, postgresql, reactjs). Moreover, in spite of the pricing of platforms, I am not able to predict my monthly costs. Also, I am not able to find any video tutorial on youtube which fulfills my expectations. In other words, everything bad :)) My requirements should be: lower costs, fast loading images, easy configuration, easy scalability. I only have a basic/junior experience with web development. In fact, I only deployed MERN app on fly.io since it was recommended in a module/course at the university. Otherweise, I have only developed app … -
Django "Pinax" magick ... unexplained form behavior
This legacy Django website uses "Pinax" for notification. I know for certain that the following "Signup" template is being used: {{ form.captcha.label }} {{ form.captcha }} {{ form.captcha.errors }} <br/> {{ form.email.label }} {{ form.email }} {{ form.email.errors }} <br/> {{ form.email2.label }} {{ form.email2 }} {{ form.email2.errors }} But here are my two problems. First of all, my "captcha" field is not appearing in the output. Second of all, I find no justification for the existence of "email2!" The "form" definition consists, in relevant part: email = forms.EmailField(widget=forms.TextInput()) confirmation_key = forms.CharField( max_length = 40, required = False, widget = forms.HiddenInput() ) # "Solve a math problem" challenge captcha = CaptchaField( label = "Solve A Simple Math Problem", widget = forms.TextInput() ) Notice that there is no "email-two." Yet, it appears with the label, "Email (again)." And, my "captcha" field does not appear in the template at all. I do not understand this "Django magick." I have searched the source code diligently for the phrase, "(again)." And I find no reference to it with regards to "email." (I have already, for other reasons, brought "pinax" directly into my project, because it appears to have been abandoned.) -
Add dynamic data to template
I need to put data into the sidebar. Haven't figured out any other sollution than context_processors. Is this the cleanest and optimal way to do this? Any help appreciated. I find it a bit strange that it has been so hard to find information re. this issue. So maybe this could be of help to others as well. # animals/context_processors.py from animals.models import Cows, Horses from django.shortcuts import render def allcows(request): cows = Cows.objects.all() return {"cows": cows} def lasthorses(request): horses = Horses.objects.all().order_by("-id")[:2] return {"horses": horses} Sidebar.html <h1>Sidebar</h1> <h3>All cows:</h3> {%for cow in cows%} <div> The name is {{ cow.name }}, and the age of {{ cow.name}} is {{ cow.age }}. </div> {%endfor%} <h3>last 2 horses:</h3> {%for horse in horses%} <div> The name is {{ horse.name }}, and the age of {{ horse.name}} is {{ horse.age }}. </div> {%endfor%} base.html <body> <div class="holy-grail-grid"> <header class="header">{% include 'animals/nav.html' %} </header> <main class="main-content"> <header id="main-header"> <h1>{% block main_heading %}Main Heading{% endblock %}</h1> <h3> {% block header_content %}Heading{% endblock %}</h3> </header> {% block content %} {% endblock %} </main> <section class="left-sidebar"> <p>My left sidebar{% include 'animals/sidebar.html' %} </p> </section> <aside class="right-sidebar"> <p>My right sidebar{% include 'animals/justinfo.html' %}</p> </aside> <footer class="footer"> <p>The footer</p> </footer> </div> … -
403 Forbidden Error for Django View Despite Permissions on Custom User Model (in userauths app)
I’m working on a Django project where I’ve implemented a custom user model (CustomUser) in the userauths app. The custom user model uses email as the unique identifier instead of the username. My goal is to allow certain users with specific permissions (change_product or delete_product) to edit or delete a product. However, even after assigning the appropriate permissions to the user, they’re still receiving a 403 Forbidden error. I’ve followed Django’s documentation for creating a custom user model, but I suspect there’s a misconfiguration or step I’ve overlooked. Here’s the detailed setup: Custom User Model and Manager (in userauths app): Below is the code for my custom user model and its manager: # userauths/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def _create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff=True.') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class …