Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django not hot-reload on M1 Mac?
I have a Django application. Back when I was using an Intel mac, it's hot-reloading functionality was working. However, a year ago I switched to one of the new Macs and now I can't get it to hot-reload. Here is my settings.py: import os import firebase_admin BASE_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY_1 = '12312312' # ... some more secret keys DISABLE_SERVER_SIDE_CURSORS = True DEBUG = True AUTH_USER_MODEL = 'my_project.MyUser' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_project', ] MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'my_project/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, 'replica': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' … -
Can't une checkout session in Stripe sandbox
I'm trying to set a stripe payment on my django app. I use a stripe sandbox to run some tests, and I'm following the tutorial. The view: @csrf_exempt @require_http_methods(["POST"]) def create_checkout_session(request): domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = '2025-03-31.basil' try: # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param checkout_session = stripe.checkout.Session.create( ui_mode = 'custom', line_items=[ { 'price': 'price_1REvRjPI8ecN8OJKIS8uPTSJ', 'quantity': 1, }, ], currency="eur", mode='payment', # success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', # cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], return_url=domain_url + '/return.html?session_id={CHECKOUT_SESSION_ID}', ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) On client side: async function initStripe() { const stripe = Stripe(stripePk); const fetchClientSecret = () => fetch("/create-checkout-session/", { method: "POST", headers: { "Content-Type": "application/json" }, }) .then((r) => r.json()) .then((r) => {console.log(r); return r.sessionId}); const appearance = { theme: 'stripe', }; checkout = await stripe.initCheckout({ fetchClientSecret, elementsOptions: { appearance }, }); ... }); I have <script src="https://js.stripe.com/basil/stripe.js"></script> on my html checkout page. Issue: when I'm on the checkout page and initStripe is launched, I get this error: Uncaught (in promise) IntegrationError: Invalid client secret. The resolved value returned from `fetchClientSecret` should be a client secret of the form ${cs_id}_secret_${secret}. But the value received was: cs_test_a1Ybi... … -
Django template loader looking at an old installed_apps list from settings.py
I have Django 5.2 installed. I had an app named 'home' in my installed_apps list in settings.py. I renamed the app to 'core' and did a full refactor. Now, Django is loading the views from the 'core' app, but for some reason, the template loader is still looking in 'home/templates/home/homepage.html'. It is somehow still using the installed_apps list from the previous settings.py. Does anyone have any idea why this is happening? -
I can't find the cause for a 405 error in my POST method
I am working on a form using the Django framework and I keep getting a 405 error which I can't seem to fix. I have an html template which contains a form allowing admins to add new TAs to the database accountAdd.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Courses</title> <style> body { font-family: Arial, sans-serif; padding: 2rem; background-color: #f4f4f4; } .container { max-width: 600px; margin: auto; background: #fff; padding: 2rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h1 { text-align: center; margin-bottom: 1.5rem; } label { display: block; margin-bottom: 0.5rem; font-weight: bold; } select { width: 100%; padding: 0.5rem; margin-bottom: 1rem; border: 1px solid #ccc; border-radius: 4px; } .button-group { display: flex; justify-content: space-between; } button { background-color: #333; color: #fff; padding: 0.5rem 1.5rem; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #555; } </style> </head> <body> <center> <div class="container"> <h1>Add Account</h1> {% if submitted%} TA added succesfully {% else %} <form action ="" method=POST> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endif %} </div> </center> </body> </html> Views.py (relevant method and imports only) from django.shortcuts import render from django.views import View from .models import * from .forms import * from django.http import HttpResponseRedirect class accountAdd(View): def … -
drf-standardized-errors not generating 404 for RetrieveAPIView
The documentation for drf-standardized-errors says that it can be integrated with DRF-Spectacular and will generate error response documentation. It specifically provides instructions on how to "Hide error responses that show in every operation", e.g. standard 404 or 401 responses. But I haven't been able to generate 404 error responses for standard DRF views, e.g. RetrieveAPIView: class MemberDetailsView(generics.RetrieveAPIView): serializer_class = MemberDetailsSerializer schema = AutoSchema() def get_queryset(self): member_id = self.kwargs["pk"] cache_key = f"member_{member_id}" cached_member = cache.get(cache_key) if cached_member is None: print("NO CACHE") cached_member = TE_MemberList.objects.filter(id=self.kwargs["pk"]) cache.set(cache_key, cached_member, timeout=600) return cached_member It only generates a 200 response. I've looked into the code of drf-standardized-errors AutoSchema, and noticed that it calls get_response_serializers() method of drf-spectacular AutoSchema, which does not have a 404 code among the responses. If I have something like raise NotFound(detail="Object not found") in a view, then it does generate a 404 response documentation. Am I misunderstanding the purpose of this auto-integration? -
Error "Couldn't import Django" running MS Visual Code Tutorial
I am a newbie to coding and MS Visual Studio Code and trying to learn Django using MS Visual Studio Code (VCS) tutorial: https://code.visualstudio.com/docs/python/tutorial-django on a Dell XPS running Windows11 Home. I have successfully completed the first section to get Django running from VSC using: Terminal Window: python manage.py runserver Edge Browser: http://127.0.0.1:8000/ The Browser displays: Hello, Django! Then I try to use the VCS debugger and get the following error: Exception has occurred: ImportError • Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 22, in main() ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I created a launch.json file using the following options: Python … -
Can't add a field with an election
I'm student. Please don't scold me. models.py: from django.db import models class Teacher(models.Model): MATH = 'MT' PHYS = 'PH' COMP = 'CS' SUBJECTS_TEACHER_CHOICES = { MATH: 'Math', PHYS: 'Phys', COMP: 'Comp', } subjects = models.CharField( max_length=2, choices=SUBJECTS_TEACHER_CHOICES, default=MATH, ) first_name = models.CharField(max_length=128) error: ERRORS: TeachersApp.Teacher.subjects: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. I want to add a field with choices. -
How to implement images relationship with Abstract model in Django?
I'm working on a Django project where I have an abstract Post model that serves as a base for two concrete models: RentalPost and RoomSeekingPost. Both of these post types need to have multiple images. Here's my current model structure: class Post(BaseModel): title = models.CharField(max_length=256) content = models.TextField(null=True) status = models.CharField(max_length=10, choices=Status, default=Status.PENDING) class Meta: abstract = True class RentalPost(Post): landlord = models.ForeignKey("accounts.User", on_delete=models.CASCADE) # other fields specific to rental posts class RoomSeekingPost(Post): tenant = models.ForeignKey("accounts.User", on_delete=models.CASCADE) # other fields specific to room seeking posts I want to add image functionality to both post types. Ideally, I'd like to define the image relationship in the abstract Post model since both child models need this functionality. However, I understand that Django doesn't allow ForeignKey or ManyToMany relationships in abstract models because they can't be properly resolved without a concrete table. I've considered: Duplicating the image relationship in both concrete models (seems redundant) Using generic relations (I not like this approach) What's the recommended approach for handling this kind of situation where multiple concrete models inheriting from an abstract base need the same relationship? -
Implementation of django-allauth-ui==1.6.1 in the project
I'm trying to get through the tutorial https://www.youtube.com/watch?v=WbNNESIxJnY&t=499s. At 4:17:26 the author implements the django-allauth-ui library into the project. The tutorial is from 10 months ago and currently the latest version of this library requires the use of the slippers library. I followed the README file (https://github.com/danihodovic/django-allauth-ui/blob/master/README.md). I installed django-allauth-ui, django-widget-tweaks, slippers libraries. I added the apps to settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'commando', 'visits', # Third-party-apps "allauth_ui", 'allauth', 'allauth.account', 'allauth.socialaccount', "widget_tweaks", "slippers", ] I run command python manage.py collectstatic After using the command runserver I get a warning: WARNINGS: ?: (slippers.E001) Slippers was unable to find a components.yaml file. HINT: Make sure it's in a root template directory. So I created a components.yaml file in the templates folder src/ ├── templates/ │ ├── components.yaml with code: components: {} Warning disappeared but templates are not loading: Page How to implement the latest version of the library into the project to make it work like in the tutorial? -
Is it possible to use Django Admin's sortable list in my own app?
The Django Admin interface displays tables in sortable lists, where the columns are clickable to change the sort order. Is it possible to use this type of list view in my own code? I want to display a list and make it sortable like this, but I don't want to expose the admin interface to my users. I've tried django-sortable-listview, but it's not well maintained and doesn't quite do what I want. Suggestions of other third-party modules also very welcome! I'm just trying desperately not to reinvent the wheel. -
How can I efficiently perform symbolic and numerical tensor computations in a Python web app using Django and SymPy
I'm building a scientific web tool that allows users to input custom spacetime metrics and compute geometric quantities from general relativity — including Christoffel symbols, Ricci, Einstein, and Weyl tensors. The backend is built in Python using Django, and I’m using SymPy for symbolic computation. I'm also working on a separate C-based module for ray-tracing visualizations of curved spacetime, which may be called through bindings later. Right now, the frontend is ready and deployed, but the backend (which handles heavy symbolic calculations) is not hosted yet due to cost constraints. I’d like to understand the best architecture and optimization strategies for when I do host it. My main challenges: Performance: SymPy can get slow with complex metrics. Are there any best practices to cache or optimize repeated tensor computations? Deployment: Would you recommend platforms like Render, Fly.io, or Railway for a Django app with heavier symbolic loads? Is there a better approach to split symbolic and numerical parts to make them more efficient/scalable? Any security concerns when exposing symbolic input processing to the public? This is part of an open project I’ve been working on solo. Here's the frontend version: https://itensor.online Docs: https://itensor-docs.com Backend source: https://github.com/Klaudiusz321/Tensor-backend-calculator Would appreciate any advice … -
100% CPU utilization on EC2
My EC2 instance has been crashed by periods of 100% utilization twice during the last 2 days and I am trying to figure out what is happening here. As you can see in the image below there were two plateaus of 100% CPU usage (the subsequent spike is me rebooting the instance). This started happening after I started running a Django server on the instance. Prior to that, I had an Express.js server running there with no issues. My Django server is being hosted by apache with mod_wsgi. I checked the access and error logs for apache and there seems to be nothing weird going on - all the activity is from me playing around and the occasional bot. Where should I start investigating? -
Django multi-table-inheritance + django-model-utils query optimization
I have some troubles to optimize ManyToManyField in child model with concrete inheritance. Assume I have models: class CoreModel(models.Model): parent = ForeignKey(Parent) class Parent(models.Model): pass @cached_property def child(self): return Parent.objects.get_subclass(pk=self.pk) class ChildA(Parent): many = ManyToManyField(SomeModel) class ChildB(Parent): many = ManyToManyField(SomeModel) In template I make a call: {% for m in parent.child.many.all %} {{ m.title }} {% endfor %} And this performs extra query for each instance. In my view I've tried to optimize in this way : core_instance = CoreModel.objects.prefetch_related( Prefetch( "parent", queryset=Parent.objects.select_subclasses()\ .prefetch_related("many") ) However I'm getting error: ValueError: Cannot query ChildAObject(some_pk). Must be "ChildB" instance. As I understand select_subclasses() "converts" parent class into child class. Both child classes have same field but still getting error. What I'm missing? -
How to restrict a foreign key form field based on previously selected field?
To preface this I know that there are some previous posts about this but the answers refer to using 3rd party packages and I was wondering if there is a solution using vanilla Django as these posts are a few years old. I am creating an music based app which has models for Artists, Albums and Tracks. What I'd like to do is when adding new tracks in the admin panel, if I select an Artist in the form then the Album choices are restricted to ones by that Artist but can't find anyway to make this work, at first I thought I may have been able to use "__" to make the relation, like in list_filter for the model admin but that didn't work. I added the artist field to the Track while trying to find a solution for this but am unsure if it is required. I am yet to develop most of the views for this app, this is currently just for the admin panel to add new tracks. class Artist(models.Model): name = models.CharField(max_length=100, verbose_name="Artist") genre = models.CharField(max_length=100) country = CountryField(blank_label="(select country)") is_approved = models.BooleanField(default=False) def __str__(self): return self.name class Album(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = … -
Django ORM, append external field to QuerySet
I have a simple queryset resulting from this: Books.objects.all() Books is related to Authors like this: Class Books: ... author = models.ForeignKey(Authors, on_delete=models.CASCADE) Class Authors: id = models.AutoField(primary_key=True) name = models.CharField() So for each book there's only one author. I want to add to each instance of the Books queryset the related Author 's name, as in this query: SELECT a.*, b.name FROM Books as a JOIN Authors as b on a.author_id = b.id I tried to read the documentation on Annonate or the selected_related method but didn't find a solution. -
Uncaught runtime errors: × ERROR (TypeError) + initStripe
Uncaught runtime errors: × ERROR Cannot read properties of undefined (reading 'match') TypeError: Cannot read properties of undefined (reading 'match') at initStripe (http://localhost:3000/static/js/bundle.js:41222:22) at http://localhost:3000/static/js/bundle.js:41264:12 I tried: analyzing the stack trace and understanding how .match() works. I expected: that a variable you assumed was a string wasn’t actually defined at runtime. -
Celery keeps throwing an error when I run my workers with --pool gevent or eventlet but works fine without these pools specified
I have a celery task like so: from celery import Celery from asgiref.sync import async_to_sync from celery_app.celery_commands import some_async_command import os redis_connection_string = os.environ.get("REDIS_URL") celery_app = Celery( 'tasks', backend=f"{redis_connection_string}/0", broker=f"{redis_connection_string}/1") @celery_app.task() def sample_task(**kwargs): result = async_to_sync(some_async_command)(**kwargs) return result When I use run celery for this task with : celery -A celery_app.tasks worker --loglevel=INFO -n my_app_worker --concurrency=4, it works fine. However, since the async function some_async_command is mainly I/O-bound and makes calls to the network, I was considering using gevent pool. I have installed gevent, but when I run celery -A celery_app.tasks worker --loglevel=INFO -n my_app_worker --concurrency=4 --pool gevent, it throws the error: Usage: celery [OPTIONS] COMMAND [ARGS]... Try 'celery --help' for help. Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'select' has no attribute 'epoll' What am I missing? -
Django form field is required while content is visibly in the form
View def work_entry(request): if request.method == "POST": form = WorkHoursEntryForm(data=request.POST) if form.is_valid(): form.save() return redirect('home') else: print(form.errors) else: form = WorkHoursEntryForm() return render(request, 'Work_Data_Entry.html', context={'form': form}) Form class WorkHoursEntryForm(forms.ModelForm): time_worked = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'id': "entry_time_worked", 'type': 'text'})) shift_num = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'id': "shift_num", "type": "text"})) class Meta: model = WorkHoursEntry fields = ('shift_number', 'time_worked_entry') Model: class WorkHoursEntry(models.Model): entry_date = models.DateField(auto_now=True) entry_time = models.TimeField(auto_now=True) time_worked_entry = models.CharField(max_length=50) shift_number = models.CharField(max_length=10) I have entered the required data into the form but the form error i keep getting is ul class="errorlist"shift_number ul class="errorlist" id="id_shift_number_error"This field is required. id=time_worked_entry ul class="errorlist" id="id_time_worked_entry_error">This field is required. and i can't figure out how to fix it as the inputs are filled out but i get this error. does anyone see something i am missing. Any help would be great. -
I need help to create a multi-task calendary for my Django framework website
I have a project and I need help. I have several bikes in my database, each bike has a number and a status (available, in maintenance, etc.). And I need to create, on my main page, a table that would be as follows: A month selector (each month would have its own table), and the table itself, with the columns being the days of the month (yes, 31 columns), and the rows being each bike. On each different day, the bike's status would be stored, and each day the user would update the table, adding the correct status for the day. For example: In the column for day 24, there are all the different statuses of the bikes, represented by different colored dots. This table would be used to keep a history of the data of all the bikes in the system. This way, we would have both a status history and a table that would be updated daily. But I honestly have no idea how to do this. JavaScript-based calendars seem to be inefficient in my case, but I'm accepting any tips. Thanks for your help! -
Sizing list-style-image
I wish to apply images as list icons to the list below: <ul id="AB1C2D"> <li id="AB1C2D1">Dashboard </li> <li id="AB1C2D2">Mechanics </li> <li id="AB1C2D3">Individuals </li> <li id="AB1C2D4">Settings </li> <li id="AB1C2D5">Messages </li> <li id="AB1C2D6">Support </li> <li id="AB1C2D7">Logout </li> </ul> I tried ul li{ padding-left: 22px; background: url("img/piz.png") left center no-repeat; line-height: 22px; list-style-position: outside; } I got my list in box shaped background without images anywhere also I tried ul li{ list-style-image: url("img/piz.png"); width: 10px; height: 10px; } ul li:before { width: 10PX; height: 10PX; size: 3px; } I got large images beside my list creating large spaces between each list item what i am looking for is how to control the list size to be small icons by the side of the list. please assist -
Django Advanced Tutorial: Executing a Command in Dockerfile Leads to Error
I followed the advanced django tutorial on reusable apps, for which I created a Dockerfile: FROM python:3.11.11-alpine3.21 # Install packages (acc. to instructions # https://github.com/gliderlabs/docker-alpine/blob/master/docs/usage.md) RUN apk --no-cache add curl ca-certificates sqlite git WORKDIR /app COPY setup.py . COPY pyproject.toml . # Install `uv` acc. to the instructions # https://docs.astral.sh/uv/guides/integration/docker/#installing-uv ADD https://astral.sh/uv/0.5.29/install.sh /uv-installer.sh RUN sh /uv-installer.sh && rm /uv-installer.sh ENV PATH="/root/.local/bin/:$PATH" # Install packages with uv into system python RUN uv pip install --system -e . # Expose the Django port EXPOSE 8000 RUN git config --global --add safe.directory /app Now, I have the following structure: django-polls-v2/ - dist/ - .gitignore - django_polls_v2-0.0.1-py3-none-any.whl - django_polls_v2-0.0.1.tar.gz - django_polls_v2/ - migrations/ - ... - static/ - ... - templates/ - ... - __init__.py - admin.py - ... - README.rst - pyproject.toml - MANIFEST.in - LICENSE In order to install my own package, cf. here, the documentation states to execute the following (where I adjusted the filenames to reflect my setting): python -m pip install --user django-polls-v2/dist/django_polls_v2/0.0.1.tar.gz Now, when I execute this command inside a running docker container (where I get into the docker container by running docker run -p 8000:8000 --shm-size 512m --rm -v $(pwd):/app -it django:0.0.1 sh), the package gets installed. … -
Cannot get NGINX, UWSGI, DJANGO working on port 80
I'm following this tutorial to setup Nginx --> uwsgi --> Django. It all works fine when the Nginx server block is set to listen on port 8000 but I cannot get it to work when the port is set to 80. I eventually get site unreachable. My sites-enabled/conf file is: # tracking_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/dconran/django3/tracking/mainsite.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # <--- works # listen 80; # <--- doesn't work # the domain name it will serve for server_name corunna.com www.corunna.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media # location /media { # alias /path/to/your/mysite/media; # your Django project's media files - amend as required # } location /static { alias /home/dconran/django3/tracking/tracker/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/dconran/django3/tracking/uwsgi_params; # … -
Output django formset as table rows
I have a Django formset which I'd like to output as one table row per nested form like so: <form> {{ feature_formset.management_form }} <table> {% for form in feature_formset %} <tr> {% for field in form %} <td>{{ field.name }} {{ field }}</td> {% endfor %} </tr> </table> {% endfor %} </form> However, somehow (I think) the automatic field rendering gets confused by the table wrapper. What I'd expect would be output like: <form> ... <table> <tr> <td>id: <input ...></td> <td>name: <input ...></td> <td>foobar: <input ...></td> </tr> <tr> <td>id: <input ...></td> <td>name: <input ...></td> <td>foobar: <input ...></td> </tr> <tr> <td>id: <input ...></td> <td>name: <input ...></td> <td>foobar: <input ...></td> </tr> </table> {% endfor %} </form> However, what I'm getting is a form row for the first form of the formset, and the rest of the forms just dumping the fields. Somehow the {% for field in form %} does not iterate properly, and I guess the remaining fields are dumped: <form> ... <table> <tr> <td>id: <input ...></td> <td>name: <input ...></td> <td>foobar: <input ...></td> </tr> id: <input ...> name: <input ...> foobar: <input ...> id: <input ...> name: <input ...> foobar: <input ...> </table> {% endfor %} </form> Any pointers as to … -
django custom user and django admin
#views.py def destroy(self, request,pk, *args, **kwargs): employee = get_object_or_404(Employee, pk=pk) user = CustomUser.objects.filter(id = employee.user.id) print('employee', employee) print('user', user) employee.delete() user.delete() # manually delete linked user return Response({"detail": "Employee and user deleted successfully."}, status=status.HTTP_204_NO_CONTENT) #models.py #Base model class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True #Custom user model class CustomUser(AbstractBaseUser,BaseModel): EMPLOYEE = "employee" CLIENT = "client" USER_TYPE_CHOICES = [ ( EMPLOYEE, 'Employee'), (CLIENT, 'Client'), ] email = models.EmailField(unique=True, validators=[email_validator]) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES) username = None # Remove username field since we use email for login objects = CustomUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["user_type"] def __str__(self): return f"{self.email} - {self.user_type}" #Employee model class Employee(BaseModel): MALE = "Male" FEMALE = "Female" OTHER = "Other" GENDER_CHOICES = [ (MALE, "Male"), (FEMALE, "Female"), (OTHER, "Other"), ] user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="employee") name = models.CharField(max_length = 250) father_name = models.CharField(max_length=250) contact_no = models.CharField(max_length=250, validators=[contact_no_validator]) alternate_contact_no = models.CharField(max_length=15, validators=[contact_no_validator], null=True, blank=True) gender = models.CharField(max_length=10, choices= GENDER_CHOICES, default=MALE) pan_no = models.CharField(max_length=20) aadhar_no = models.CharField(max_length=12, validators=[aadhar_no_validator]) dob = models.DateField(null=True, blank=True) department = models.ForeignKey(Department, on_delete=models.SET_NULL, related_name="department_employees", null=True) designation = models.ForeignKey(Designation, on_delete= models.SET_NULL, related_name="designation_employees", null=True) joining_date = models.DateField() … -
Backend development
I'm a systems engineering student in Mexico. I'm interested in backend engineering because of a project I need to develop. So, if anyone could give me advice or recommend tutorials so I can learn more about this and pursue it professionally, I'd be very grateful I expect help from developers