Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerized django taking long time for build the docker-compose
I'm running a dockerized Django application: only Django + Postgres on local. When I start the application and go to any localhost URL, it takes up to 20-30 minutes to build. Here is my dockerfile: FROM python:3-alpine LABEL maintainer="joyalcs2@gmail.com" ENV PYTHONUNBUFFERED=1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Here is my docker-compose.yml: version: "3.11" services: app: build: context: . args: - DEV=true ports: - "8000:8000" image: app:django container_name: rest_container volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" requirements.txt: Django == 4.2.4 djangorestframework == 3.14.0 psycopg2 == 2.9.7 drf_spectacular == 0.26.4 I tried many times and i changed the image many time .but it takes so much time.Also, i used -
Submit a form with Fetch to a Django View
I'm a beginner trying to figure how to use both Django and Fetch api. I was trying to follow this question Django - taking values from POST request, JavaScript fetch API To figure out how to POST a form to a Django view, and access the data from the view. I'm not sure if my header has an issue. my html form <form class="basicform"> <label for="nametextbox">Change First Name</label> <input type="text" name="nametextbox"> </form>` My fetch POST request function postForm(id, form){ var formData = new FormData (form); let response = fetch("{% url 'fetch-ppl' '12345' %}".replace('12345',id), { method: 'POST', body: formData, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "X-CSRFToken": getCookie("csrftoken") }, }) .then(response => response.json()) .then(data=>{ console.log(data); }) return 'Post Done'; } My POST view, that I'm trying to send the form data to def post_form_rest(request, pk): ppl = PersonalData.objects.get(id=pk) serializer = PersonalDataSerializer(ppl,many=False) if (request.POST): print("It's a Post Request") print(request.POST); data = ["post request done"] return JsonResponse(data) return JsonResponse(serializer.data) My problem is when I send my POST request, the django view doesn't detect any POST data at all, it just skips to the end where it gives me a json response of the initial model object. (I don't get any print statements … -
Kubernetes: Secrets update but server not rolling out with new env values
I've a Kubernetes cluster running Django on DEBUG=True using ConfigMap and some other secrets using K8's secrets. The problem I'm having is that even if I rollout the server it keeps having debug true values, and when I inspect the container, the env shows that it's in False. Any idea why this is happening, and how to solve it? -
Django Grappelli 3.0.7 radio_fields admin.HORIZONTAL not working
Upgraded to Grappelli 3.0.7 with Django 4.0.10 and radio fields are stacking vertically even though specified as radio_fields = {'show_weekends': admin.HORIZONTAL, 'group_by_dept': admin.HORIZONTAL} If I comment out Grappelli in INSTALLED_APPS, they work properly so it's not a Django issue -
Django shows Internal Server Error in Production while uploading images
My django application shows internal server error when I try to upload images in the production server when I turn the debug = False and it works well when debug = True. I'm using django-imagekit for processing the images. I'm using Whitenoise to server my media and static files. Here is my code: setting.py STATIC_URL = '/static/' MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py image = ProcessedImageField(upload_to='authors', format='JPEG', options={'quality': 60}) I hosted the site on Vercel -
Migrations in FastAPI libs?
In Django it is quite convenient that 3d party libs could store their own models and migrations. F.e. django-celery-beat - it has functionality which require database table. It is also convenient to have single settings object from which 3d party libs could get necessary settings. But what about FastAPI? How 3d party lib could say a user which settings it needs? How to provide a user functionality which requires a database table? -
Why CSS works with "python manage.py runserver" but not with Gunicorn?
When I run, from the command line, python manage.py runserver mywebsite.com:8099 the css works fine. But when I use the systemd service with Gunicorn socket, the app works but without the css. Even if I use the following command: gunicorn demo.wsgi:application, the app works fine but without the css. Excerpt from my settings.py: STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "mystaticfiles" ] Excerpt from my nginx config file: location /static/ { root /root/djdeploy/demo/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } My Django project working directory is: /root/djdeploy/demo/, I have put my css files in the following folder: /root/djdeploy/demo/mystaticfiles -
Error Django - SQL Server near "EXEC": syntax error
I have a problem calling Stored Procedured in Django, can you please help, below is the error: My funtion view def homeKTA(request): cursor = connection.cursor() try: cursor.execute("EXEC dbo.processos") result = cursor.fetchall() finally: cursor.close() return render(request, "homeRCKTA.html", result) yes that's exactly what is expected -
Revoke/replace Celery tasks under certain conditions
Let's say I've got a class Foo and a function which can be called like that: calculate(foo, dt) (the first argument is an instance of Foo, the second a datetime.datetime instance). Also, calculate updates various things related to foo in a database, calculate is decorated with @transaction.atomic to avoid reaching an inconsistent state in case of issue, behind calculate lies a recurrence relation, running it is computationally expensive, this is one of the reasons why it's called through a Celery task, when dateX > dateY, running calculate(foo, dateX) is pointless if you know you'll have to run calculate(foo, dateY) anyway, because the set of values updated by calculate(foo, dateX) is included in the set of values updated by calculate(foo, dateY). Now, how to run calculate as often as necessary without unnecessary calculations? In other terms, I think I'm looking for a function schedule_calc, taking 2 arguments foo and dt (like calculate), also matching the following requirements: when there isn't any task related to foo, a new one is created which will eventually run calculate(foo, dt), when there is such a task which will eventually run calculate(foo, date1), let's call it T1, several possible outcomes: if date1 <= dt and T1 … -
How to upload mutiple images in the django admin
It involves uploading multiple images to the django admin and the only one should show in the listings.html , and then in that instance post the other images should display there . I have done majority of the work to ensure the post is saved. Please bear in mind that i use an html page (pro.html) where i have the form my users will input whatever they want to post . Once the post in submited , it is automatically saved in the django admin . Amongst the form i require 8 images . The thing now is, if i upload 8 images it is going to save 8 times instead of once. This is my views.py from django.conf import settings from django.conf.urls.static import static from .forms import PostForm from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage from django.http import HttpResponse # Create your views here. def post_create(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() for file in request.FILES.getlist('image'): image = Image(image=file) image.save() else: form = PostForm() return render(request, 'estateapp/pro.html', {'form': form}) def home(request): return render(request, 'estateapp/home.html') def Listings(request): posts = [] for post in Post.objects.all(): post = { 'title': post.title, … -
Django Management Command Triggers URLs When Checking Database Connection
I've encountered an unexpected behavior while working on a Django project involving a custom management command. The command I've created, named wait_for_db, is intended to test whether the database connection is ready before proceeding with other tasks. However, when I trigger this command using python manage.py wait_for_db, it seems to be invoking some URLs, leading to database-related errors. I've structured the management command to primarily check the database connection's readiness without interacting with URLs or the web server. The goal is to ensure that the database is available before proceeding with other operations. Here's a simplified version of my management command: """ Django command to wait for the database to be available. """ import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for database.""" def handle(self, *args, **options): """Entrypoint for command.""" self.stdout.write('Waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg2OpError, OperationalError): self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) Despite my best efforts, when I execute python manage.py wait_for_db, it seems to trigger some URLs or components that access the database. As a result, I receive errors indicating that … -
Django static and media files in production
I've deployed my first django ( learning ) project to a hosting server. I turned "DEBUG" off and run "collectstatic" so I have "static" and "media" folders in my main directory ( besides "manage.py" and ... ). But static and media files are not accessible unless I move the their folders to "public-html" directory every time. How can I change my root directory from "public-html" to "social" (main django folder). And does this fix the problem? Note: In my cpanel there is no apache configs available in etc folder. I asked the hosting provider to change the root directory for me but they said it can be done by me through some .htaccess configs. I added this to .htaccess file: RewriteEngine On RewriteCond %{HTTP_HOST} ^sadeqmousawi.ir [NC] RewriteRule ^(.*)$ /social/$1 [L] But it didn't work. -
Edit Django Admin JS Sheet Element
I am using this js form to select users: <style> .selector { float: none; display: block; height: 330px; } .selector-available, .selector-chosen { float: left; width: 380px; height: 330px; text-align: center; margin-bottom: 8px; } .selector ul.selector-chooser { float: left; width: 22px; height: 330px; background-color: var(--selected-bg); border-radius: 10px; margin: 10em 5px 0 5px; padding: 0; } .selector input[type="submit"] { display: block; clear: both; } .selector h2 { font-size: 15px; } textarea { display: block; width: 450px; } </style> Which results in a page rendering: I am trying to put the remove all button as well as the directional arrows between the Available users and Selected Users boxes so everything is even but, I am not sure how to do so. Could someone point me in the right direction? -
Prevent LDAP users from being automatically created in the Django admin site
I setup an LDAP authentication to login to a Django admin site from an active directory(AD) After logging in, the user are populated in the Users of Django admin site. Is there a way to prevent that the users are populated in the Django admin site? I though that AUTH_LDAP_USER_ATTR_MAP is what populates the user but I removed it and the users are still populated after logging in. Here is the settings.py import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesTypes, LDAPGroupQuery AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ] AUTH_LDAP_SERVER_URI = "ldap://server.name" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = "cn=user,ou=group,dc=example,dc=example" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False } AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=example,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "ou=group,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)" IS_STAFF_FLAG = ( LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") | LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") ) AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_staff': IS_STAFF_FLAG, 'is_superuser': "cn=group,ou=group,dc=example,dc=example" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 -
Relation programmingError
I have model code for which migrations have successfully created and passed: from django.db import models from django.contrib.auth.models import AbstractUser class Employee(AbstractUser): probation = models.BooleanField(default=False) position = models.CharField(max_length=50, blank=True) groups = None user_permissions = None class Order(models.Model): name = models.CharField(max_length=100) description = models.TextField() employee = models.ForeignKey('employee', on_delete=models.CASCADE) def __str__(self): return self.name after which I registered them in the admin panel from django.contrib import admin from .models import Employee, Order @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'probation', 'position') list_filter = ('probation', 'position') search_fields = ('username', 'first_name', 'last_name', 'email') @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ('name', 'employee') list_filter = ('employee',) search_fields = ('name', 'employee__username', 'employee__first_name', 'employee__last_name') then when I try to add a new employee through the admin panel, I get an error relation "main_employee" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "main_employee" ^ Please tell me what is wrong with my code, I will be grateful -
Statistic on Django admin Index page
I know that Django admin main page is in index.html. I want to change this page, and add some statistic things, like last 5 errors from DB. My question is: that it is possible, create model for main admin page and show in there some information like I can when I will create some custom models and views? Do you have some example for that somewhere ? -
How to schedule a function in aiogram
I have Django+aiogram bot and that's how my mailing works: Manager/admin create a instance of the Post/Poll model in the admin panel -> Admin approve/disapprove it in telegram PM with inline keyboard -> if approves ("post" callback data) -> do_mailing function immediately works But I added the "scheduled_time = models.DateTimeField" field in my Post/Poll models and I want do_mailing function to work in that scheduled_time once, without repeats. Post model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Менеджер') text = models.TextField(verbose_name='Текст') scheduled_time = models.DateTimeField(blank=True, null=True, verbose_name="Дата и время рассылки") approved = models.BooleanField(default=False, verbose_name='Подтверждён') total_media_count = models.PositiveIntegerField(default=0, verbose_name='Сколько фотографий загрузите?') group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Группа пользователей бота') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name='Создано') There's a handler for "post" callback data which works after admin's approval: @dp.callback_query_handler(lambda query: query.data == 'post', state="*") async def post_handler(callback_query: CallbackQuery, state: FSMContext): admin = callback_query.message['chat']['id'] message = callback_query.message.text.split('\n') await change_post_status(message[0].split(': ')[1]) await do_mailing(message) logging.info(f"Пост {message[0].split(': ')[1]} был одобрен на рассылку админом") await bot.send_message(chat_id=admin, text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") await bot.send_message(chat_id=message[-1].split(': ')[1].split(' ')[0], text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") So do_mailing function is what I need to schedule. I can get "scheduled_time" field from the "message" variable, so don't think about it, let's just say … -
Understanding TemplateDoesNOtExist at home.html
I am working on django for beginners and the code provided does not work. I have copied and pasted after manually typing it in and the error persists around this class based view. It claims that home.html does not exist. The file certainly does. There is an odd home = value in the code that I do not understand why it is there as it is outside the norm. However I clearly see the hashtag # new which means to include the new code. I tried the extra removing home= and a red squiggly line immediately appeared as an error. The error message reads: Traceback (most recent call last): File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 90, in rendered_content template = self.resolve_template(self.template_name) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 72, in resolve_template return select_template(template, using=self.using) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: home.html Another problem I am experiencing is that I went to a prior commit and github is saying hey, you need to do a pull request on the most … -
Change font color in Django ModelChoiceField widget after selection made
I have styled the font and font color for the select menu in my Django form using the widget. Is it possible to change the font color once a selection is made? For example, select menu text starts off white and after selection is made it turns green. I am using Crispy Form tags on the front end. class FootballLineup(forms.ModelForm): class Meta: model = FootballContestEntry fields = ['qb'] qb = forms.ModelChoiceField(label='', queryset=NFLPlayer.objects.filter(active=True, position='QB'), empty_label="Select Quarterback", required=True) qb.widget.attrs.update({'class': 'text-center lineup-select marker'}) -
Django logging issue on IIS
I'm new to Django and IIS server. I have a web server deployed with IIS, and I'm encountering an issue with the code. I'd like to try fixing it on my own, but I don't have a console (like in development mode) to show me what's going on. So, I started trying the logging functions in settings.py. Here's my configuration FORMATTERS = ({"verbose": {"format": "{levelname} {asctime:s} {name} {threadName} {thread:d} {module} {filename} {lineno:d} {name} {funcName} {process:d} {message}","style": "{",},"simple": {"format": "{levelname} {asctime:s} {name} {module} {filename} {lineno:d} {funcName} {message}","style": "{",},},) HANDLERS = {"console_handler": {"class": "logging.StreamHandler","formatter": "simple","level": "DEBUG"},"info_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_info.log","mode": "a","encoding": "utf-8","formatter": "verbose","level": "INFO","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},"error_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_error.log","mode": "a","formatter": "verbose","level": "WARNING","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},} LOGGERS = ({"django": {"handlers": ["console_handler", "info_handler"],"level": "INFO",},"django.request": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},"django.template": {"handlers": ["error_handler"],"level": "DEBUG","propagate": True,},"django.server": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},},) LOGGING = {"version": 1,"disable_existing_loggers": False,"formatters": FORMATTERS[0],"handlers": HANDLERS,"loggers": LOGGERS[0],}` taken from this explaination [https://www.youtube.com/watch?v=m_EkU56KdJg ](here): this code generates 4 files: blogthedata_detailed.log blogthedata_error.log blogthedata_info.log the detailed.log contains this:INFO 2023-08-25 11:53:47,710 Thread-1 (process_request_thread) 8792 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/login_script.js HTTP/1.1" 200 751INFO 2023-08-25 11:53:47,780 Thread-2 (process_request_thread) 20080 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/jQuery.js HTTP/1.1" … -
I get an error { "error": "Invalid email or password" }
I want to implement the ability to log in to my account, he says that I have the wrong email or password, but I checked the correct email and password through the administrative line. help me understand why the error comes out and how to fix it class LoginView(APIView): serializer_class = LoginSerializer # def get(self, request): # return render(request, 'login.html') def post(self, request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) return Response({'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED) class LoginSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate( username=data['email'], password=data['password'] ) if not user: raise serializers.ValidationError('Неверные учетные данные') data['user'] = user return data class User(models.Model): email = models.EmailField(max_length=255, unique=True) password = models.CharField(max_length=128) -
Changing Year, Month, or Day in a Django model's date field using annotate
I have a Django model MyModel class MyModel(models.Model): """My Model that stores date.""" date = models.DateField() In my API I am receiving a param, review_month I need to get all the entries in MyModel and replace their date's year value. I have the following condition for what year to add: -> If date__month is greater than review_month the year will be current year otherwise the year will be previous year. I need these new date fields with updated years for every entry of the MyModel queryset MyModel.objects.annotate( updated_year=Case( When( Q(review_date__month__gt=review_month.month), then=previous_year), default=current_year, output_field=IntegerField(), ), ) ) This only give me year separately but I want an updated_date that has day and month of date field and this new updated year in it and must be a DateField as I need to apply sorting to it. -
user match query does not exist
I have been tasked to create separate user model for third_party users who are to access our endpoint so i created separate user named ApiCliet and inherited the Abstract user model of Django i also created a custom authentication for that user model only and then crated two mutation to create an api client and also generate and access_toekn for the existing user how ever i get user matching query does not exist which is baffling after debugging i get the username is correct and the password is correct below is my code . Model class ApiClientManager(BaseUserManager): def create_user(self, username, email=None, password=None, **extra_fields): if not username: raise ValueError("The Username field must be set") email = self.normalize_email(email) if email else None user = ApiClient(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email=None, 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(username, email, password, **extra_fields) class ApiClient(AbstractBaseUser, PermissionsMixin): id = models.AutoField(db_column="Api_client_ID", primary_key=True) uuid = models.CharField(db_column="Api_clientUUID", max_length=36, default=uuid.uuid4, unique=True) username = models.CharField(db_column="Api_client_username", max_length=100, unique=True, default='test_username') email = models.EmailField(db_column="Api_client_email", blank=True, null=True) access_token = models.CharField(db_column="Api_client_access_token", max_length=100, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) … -
Compare Python Dictionary values with Django Database fields
I'm looking for a way to compare a python dictionary values with Django ORM entries. I have a dictionary contains product information like following: product_1 = { "ProductId": "552049", "BarCode": "552049", "Height": 200, "WholesalePrice": 10.65, "RetailPrice": 18.78, "Length": 62, "LongDescription": "Spray 400ml", "ShortDescription": "Spray 400ml", "Volume": 818, "Weight": 354, "Width": 66, } These values stored on a Django database. The number of products are very big, about 200.000 products and after a few days I need to compare and update the products if something change. I know that a way is to iterate to products and compare values but I'm looking for a better approach to compare products more faster. I'm thinking about to create a checksum and stored as a field in database and later when I update the products, first compare the checksum and if is different then update the database field. But I don't know if this the best way. Can someone suggest me a fast way for this? -
Django forms value getting the last id but wanted specfic id and first save is working the rest is not working
**I have a Django code where i am retrieving the tin number and tin type ** ``if ("_generate_form_1099" in self.request.POST) and self.request.POST["_generate_form_1099"] == "Generate Form 1099": elif ("_send-bulk-email" in self.request.POST) and self.request.POST["self-bulk-email"] == "Send Bulk Email": elif ("action" in self.request.POST) and self.request.POST["action"] == "Save Tin": user_id = self.request.POST.get('user_id') tin = self.request.POST.get('tin_value') tin_type = self.request.POST.get('tin_type') input_name = f"tin_value{{ user.id }}" if input_name in self.request.POST: tin_value = self.request.POST[input_name] user = CustomUser.objects.get(id=user_id) user.seller_tin = tin user.tin_type = tin_type user.save() context = {'user_contexts': user_contexts} return render(self.request, 'admin/generate_form.html', context) elif ("_send-tin-email" in self.request.POST) and self.request.POST["_send-tin-email"] == "Send Email": user_id = self.request.POST.get('user_id') user_name = self.request.POST.get('user_name') email_mess = {"seller": user_name} send_notification([user_id], 'notification_31', email_mess) ` `{% extends "admin/base_site.html" %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div> <input type="submit" class="action-button" value="Generate Form 1099" name="_generate_form_1099"> </div><br> {% if download_link %} <a href="{{ download_link }}" target="_blank" class="download-button"> <div style="display:inline-block">Download</div> </a> {% elif download_link %} <div><p>The Form 1099 has not been generated for the specified fiscal year. Click on Generate Form 1099</p></div> {% endif %} {{ block.super }} </form> <div> <h2>Seller Information Without Tin</h2> <table> <tr> <th class="header-table">USER ID</th> <th class="header-table">Name</th> <th class="header-table">Email</th> <th class="header-table">TIN Details</th> <th class="header-table">Actions</th> </tr> {% for user in user_contexts %} …