Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to implement a reports and analytics code in django
This is the reports app for a business management website. One of its features is to identify the top selling product on the platform.Another is that it process low stock alerts,identify stock which has no sales. Also, it should display a table for the product, the units sold, total price of the products and if the product is available.Finally, the report app needs to count order based a date range. It should add revenue generated and filter revenue.enter image description here -
Could not connect to Saleor during installation. Saleor URL that App tried to connect: http://localhost:8000/graphql/
I'm using self hosted Saleor and trying to integrate self hosted stripe app, however I'm getting "Couldn’t Install Stripe The auth data given during registration request could not be used to fetch app ID. This usually means that App could not connect to Saleor during installation. Saleor URL that App tried to connect: http://localhost:8000/graphql/" I'm not sure why saleor url is http://localhost:8000/graphql/ since all variables in my env point to my deployed server api url and not localhost. Nothing is running locally, i'm using my deployed dashboard to install a deployed stripe app. -
How to get mutual friends - Django
I have been able to get the list of all users and also implement sent friend request (following/follower). Now, how do I get mutual friends(following/followers)? For example; if both user have an existing friend in common. Below code is what I have tried, but not displaying mutual friends. What am I doing wrong and how can I get it done correctly? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True) following = models.ManyToManyField( 'Profile', # Refers to the User model itself symmetrical=False, # If A follows B, B doesn't automatically follow A related_name='followers', # Reverse relationship: get followers of a user blank=True, ) def FollowingView(request): page_title = "Following" # All users following posts posts = Post.objects.filter( Q(poster_profile=request.user)| Q(poster_profile__profile__followers__user=request.user)).order_by("?").distinct() # All account users profile_users = Profile.objects.exclude( Q(user=request.user)) # Mutual Followers all_following = request.user.profile.following.values_list('pk', flat=True) mutual_followers = Profile.objects.filter(pk__in=all_following) -
I am building a system mixed of tiktok and amazon store where we can post the video as well and buy products [closed]
Suggest me the technologies and the architecture that I can follow for 1 millions users -
после попытки контеризировать приложения события Celery перестали обрабатываться
я написал простой сайт на Django по покупке билетов, Celery когда пользователь начинает процесс оплаты места, оно бронируется. если через n секунд он все еще не оплатил - то оно освобождается с помощью Celery. когда я запускал сайт локально (поднимая worker and redis manually), то всё работало корректно. Перед контеризацией я изменил настройки для celery: CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' поменял localhost на redis, потому что слышал что Docker делает сетевым именем контейнера то, что указано в docker-compose dockerfule: FROM python:3.11-slim WORKDIR /app COPY . . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD ["python3", "Tickets/manage.py", "runserver", "0.0.0.0:8000"] docker-compose: services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" container_name: ticket-web worker: image: ticket-web working_dir: /app/Tickets command: celery -A Tickets worker depends_on: - redis - web redis: image: redis:6-alpine ports: - "6379:6379" celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Tickets.settings') app = Celery('Tickets') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.update( timezone='Europe/Moscow', # Set your preferred timezone enable_utc=False, ) app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') init: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) логи worker: SecurityWarning: You're running the worker with superuser privileges: this is … -
Unable to run tests django. django.db.utils.ProgrammingError: relation "auth_user" does not exist
I'm writing tests. When trying to run it, it returns the error "django.db.utils.ProgrammingError: relation "auth_user" does not exist". I'm running the project locally using a virtual environment. There is a similar error in the logs in pgadmin. This error also occurs when starting a project in docker. I checked the migrations. I tried all the options from the Internet and GPT. I will be very grateful for your help. -
gunicorn gevent CERTIFICATE_VERIFY_FAILED error
I have a Django website running in a Docker container (Debian), which I deploy with the following command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 33 --worker-class gevent --timeout 1200 I created a simple view with an outgoing request: def my_view(request): import requests requests.get('https://website.domain.com', verify='/etc/ssl/certs/mycert.cer') return HttpResponse('Success') Which throws the error: requests.exceptions.SSLError: HTTPSConnectionPool(host='website.domain.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)'))) What could be the reason for such behavior? What is special about how the gevent worker handles SSL certificates? What I found out for now: The script works fine when I use --worker-class sync or deploy with python manage.py runserver The script works fine when executed via python console or via python manage.py shell (from a running docker container) The certificate is correct (otherwise, it didn't work for cases above) Unsetting REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, SSL_CERT_FILE or setting them to current location of my cert file doesn't help PYTHONHTTPSVERIFY=0 seems to have no effect verify=False and verify=True have no effect Adding monkey.patch_all() in the script has no effect Adding gunicorn.conf.py with monkey.patch_all() in it has no effect The certificate is definitely being used. Because if I set verify parameter … -
Wagtail login downgrades to http, gives error
I am setting up a new, local version of a Django Wagtail project (which I have had running locally before). I am able to see Pages in my browser, but when I try to login (on FF, Chrome, Safari-with-no-plugins) at https://mysite.test/admin/login/?next=/admin/ I get the error: gaierror at /admin/login/ [Errno -2] Name or service not known Request Method: POST Request URL: http://mysite.test/admin/login/ Django Version: 5.0.3 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python3.10/socket.py, line 955, in getaddrinfo Raised during: wagtail.admin.views.account.LoginView Python Executable: /root/uv/.venv/bin/python Python Version: 3.10.12 Python Path: ['/usr/srv/app', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/root/uv/.venv/lib/python3.10/site-packages', '/root/uv/.venv/lib/python3.10/site-packages/setuptools/_vendor'] Server time: Thu, 03 Jul 2025 13:44:22 +0000 which includes the request URL http://mysite.test/admin/login/. I don't have a VPN running and I can't identify anything else which might be causing trouble on the local network (though I can't discount this). If I try https://127.0.0.1:5000/admin I get: Secure Connection Failed An error occurred during a connection to 127.0.0.1:5000. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the web site owners to inform them … -
Django media images not loading in production using Nginx , with Debug=False
I'm deploying my Django project with DEBUG=False, and media files like images are not loading. Nginx Configuration server { listen 80; listen [::]:80; server_name <my_server_ip>; location /media/ { alias /home/ubuntu_server02/cdo_portal/media/; autoindex on; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Django settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') What are the details of your problem? I deployed my Django project with DEBUG=False, and I'm trying to serve uploaded media files (images) using Nginx. However, when I access a media file through the browser (e.g., http://<server_ip>/media/sample.jpg), I get a 404 Not Found error. The media files exist in the correct folder, Nginx is running, and permissions are correct. I'm not sure if the issue is with my Nginx config or something else. What did you try and what were you expecting? I tried accessing media files through the browser directly, like: http://<my_server_ip>/media/sample.jpg I expected the image to load, but it returned a 404. I checked that the file exists, the path in Nginx is correct, and the alias points to the right folder. Still, Nginx doesn't seem to serve the media files. -
django-mptt using get_root() on TreeQuerySet element inside for loop and output stored in list does not persist outside of for loop
I am trying to use get_root() on individual TreeQuerySet elements in a for loop. This seems to work in the Django Python shell as shown below. Upon pressing [Enter] twice to indicate the end of the for loop, the result of applying the get_root() to each element is printed automatically in the shell. The result is correct in that the output does indeed list the top level root of each TreeQuerySet element. However outside of the loop, the list in which these should be stored in is not updated. Instead this list contains the original TreeQuerySet elements. In Django Python shell: >>> topics_w_arttype_articles = topics.Topic.objects.filter(to_ArtTypeArticle_topic_from_Topic__title__isnull=False).distinct() >>> topics_w_arttype_articles <TreeQuerySet [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>]> >>> arttype_topic_roots_list = [] >>> for item in topics_w_arttype_articles.iterator(): ... item.get_root() ... arttype_topic_roots_list.append(item) ... <Topic: Level0Topic1> <Topic: Level0Topic2> <Topic: Level0Topic2> <Topic: Level0Topic3> <Topic: Level0Topic4> <Topic: Level0Topic5> <Topic: Level0Topic5> <Topic: Level0Topic5> >>> arttype_topic_roots_list [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>] >>> I placed the logic of the shell interaction in a custom template tag, shown below (with additional code that should remove duplicates from the list, if it … -
Why aren't my Django Postgres `ArrayAgg` members sorting?
I'm exploring the use of ArrayAgg and I don't understand why 'histidine-[13C6,15N3]' doesn't occur before 'isoleucine-[13C6,15N1]' in this example: In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] The records/rows are sorted based on the first value, which is great, but that first value isn't sorted WRT the other values in the list. For that matter, why doesn't the order of the members of the list change at all when I negate the order_by in the ArrayAgg? According to what I read, this should sort the list items. Am I blind? What am I doing wrong? In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="-tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] -
Django, docker compose, whitenoise and railways: new js files not found in production (it works in local)
I am working in a django project where I have installed and configured whitenoise to serve static files in railways. But railways is not serving or collecting my new js files. In my browser I get a 404 in settings I have configured (theoretically) whitenoise INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'captcha', 'storages', 'whitenoise.runserver_nostatic', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and this is where I am managing my files (I am also using amazon aws s3 to upload pdfs and other files) STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" STORAGES = { "default": { "backend": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "whitenoise.storage.CompressedStaticFilesStorage", # CompressedStaticFilesStorage }, } # Modify storage configuration if ENV_STATE == "production": SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # HIPAA-compliant Backblaze configuration AWS_ACCESS_KEY_ID = os.environ['B2_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['B2_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['B2_BUCKET_NAME'] AWS_S3_ENDPOINT_URL = os.environ['B2_ENDPOINT_URL'] AWS_S3_REGION_NAME = os.environ.get('B2_REGION_NAME', 'us-west-004') # Default region # Security settings AWS_DEFAULT_ACL = 'private' # HIPAA: Private access only #AWS_LOCATION = 'protected' # This should match your prefix AWS_S3_FILE_OVERWRITE = False AWS_S3_ADDRESSING_STYLE = 'path' AWS_QUERYSTRING_AUTH = True # Enable signed URLs for HIPAA compliance AWS_QUERYSTRING_EXPIRE = 3600 … -
How can I display a table in a template with additional category/section rows?
Have a nice day! I have a non-standard table. Which I plan to display in the template. I load the table into the template from the model. And I have additional sections - additional fields. These additional fields characterize - Category, Section, Topics. I am thinking how to display such a table from the model in the template - as shown in the picture. To additionally implement additional fields - categories or sections in the table. I have a rough idea - I have to create a transit model for exactly such a table - in which the number of rows is equal to the number of rows of the original table + plus the number of rows of category sections in addition. That is, there can be about 25 rows of the original table and + plus 6 rows - category sections. In total, the required table will have 31 rows of rows. enter image description here But how to display them in the form as in my picture - separating categories sections? models.py class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="") name_category = models.CharField(verbose_name="") name_working = models.CharField(verbose_name="") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="") value_work = models.FloatField(verbose_name="") lyudi_norma = models.IntegerField(verbose_name="") technik_norma = models.IntegerField(verbose_name="") … -
How to support multiple Google Cloud Storage buckets in a Django FileField without breaking .url resolution?
I'm using Django with django-storages and GoogleCloudStorage backend. My model has a FileField like this: raw_file_gcp = models.FileField(storage=GoogleCloudStorage(bucket_name='videos-raw')) At runtime, I copy the file to a different bucket (e.g. 'videos-retention') using the GCS Python SDK: source_blob = default_bucket.blob(name) default_bucket.copy_blob(source_blob, retention_bucket, name) After copying, I update the .name field: recording.raw_file_gcp.name = f'videos-retention/{name}' recording.save() Everything works until I restart the app. Then, when I access .url, Django tries to build the URL using the original bucket from the storage=... argument, even if the file now belongs to another bucket. It ends up generating invalid URLs like: https://storage.googleapis.com/videos-raw/https%3A/storage.cloud.google.com/videos-retention/filename.mp4 I expected Django to keep working even if the file was moved to a different bucket. After debugging, I realized that the FileField is tightly coupled to the bucket used when the model is initialized. If the file moves to another bucket, .url breaks. ChatGPT suggested removing FileField altogether, using a CharField instead, and dynamically resolving the GCS bucket + path in a custom @property using google.cloud.storage.blob.generate_signed_url(). Is there a better solution for this? How can I support multiple GCS buckets dynamically with Django FileField? -
I tried to implement custom validation error in django
I have wrote this validators.py file: from django.core.exceptions import ValidationError import os def allow_only_images_validator(value): ext = os.path.splitext(value.name)[1] print(ext) valid_extensions = ['.png', '.jpg', '.jpeg'] if not ext.lower() in valid_extensions: raise ValidationError("Unsupported file extension. Allowed extensions: " +str(valid_extensions)) This is my forms.py file: class userProfileForm(forms.ModelForm): class Meta: profile_picture = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) cover_photo = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) But this error is not showing in my template. The SS is here: Can anybody help me on how do I fix it? -
In Django how can I list a Queryset in one view/template generated by another view?
I'm developing a tracking system that has 2 main datasets Orders and Shipments. Focussing on Orders I want to enable users to enter any combination of field data and then display the resulting list using pagination. To achieve this I have 2 views/templates. One, search_orders, displays a form that is, essentially, a list of the majority of the dataset fields. The other, list_orders, displays a list of the selected orders. This all works fine if I just render list_orders from search_orders without any pagination but, in order to get pagination I (believe that I) need search_orders to redirect to list_orders and, so far, I've been unable to do that. Search_orders view: @login_required def search_orders(request): if request.method == 'POST' and len(request.POST) > 1: orders = Order.objects.all() msg = '' fields_selected = '' for fld in request.POST: if fld == 'orderid' and request.POST.get('orderid'): msg += f'{fld} - {request.POST.get('orderid')} and ' fields_selected = True orders = orders.filter(orderid__icontains=request.POST.get('orderid')) if fld == 'bookingtype' and request.POST.get('bookingtype'): msg += f'{fld} - {request.POST.get('bookingtype')} and ' fields_selected = True orders = orders.filter(bookingtype__icontains=request.POST.get('bookingtype')) if fld == 'shp' and request.POST.get('shp'): msg += f'{fld} - {request.POST.get('shp')} and ' fields_selected = True orders = orders.filter(shp__icontains=request.POST.get('shp')) if fld == 'con' and request.POST.get('con'): msg += … -
How can I convert a QuerySet list to a list or a dataset for the choices field?
After doing some filters and operations, I write the data to the model. I get the data after processing in the model. Then I unload the data when displaying the form. There is a field in the form - which is like a choices field. But I'm not quite sure about the correct spelling for the form. My problem is that I can display the data for the choices field only after some processing or as a result of receiving data from another model. My task is to unload data from another model into the code. And then from the code send it to the choices field. How can I do something similar? models.py class Category_pk_for_form_maim (models.Model): categoty_name = models.CharField() def __str__(self): return self.categoty_name class Category_pk_for_form_category (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") category_name = models.CharField() class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_category = models.CharField(verbose_name="Наименование категории/раздела/вида работ") name_working = models.CharField(verbose_name="Наименование работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work = models.FloatField(verbose_name="Объём работ") lyudi_norma = models.IntegerField(verbose_name="Нормативные затраты персонала") technik_norma = models.IntegerField(verbose_name="Нормативные затраты техники") date_begin = models.DateField(verbose_name="Дата начала работ") date_end = models.DateField(verbose_name="Дата окончания работ") class GPRWorkingName (models.Model): name_working = models.CharField(verbose_name="Наименование работы по ГПР") def __str__(self): return self.name_working forms.py class Form_GPR (forms.ModelForm): class Meta: model = … -
invoice bill creation for the specific customers in billing software django forms
i am trying to create a invoice bill for the specific customer , first on the bill customer selection should be available for the selection of the customer , after that we are giving the option to add the items which are taken from the product app along with quantity input option . how can i implement this things using the django and dajngo forms i tried to do this but i am just able to implement the only customer selection option but not of items selection from the product i am giving the my codes of models.py form.py and views.py models.py: from django.db import models from customer.models import Customer from product.models import Product # Create your models here. class Invoice_customer_list(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) # date = models.DateField(auto_now_add=True) # total_amount = models.DecimalField(max_digits=10, decimal_places=2,default=0.00) def __str__(self): return f"Invoice # {self.id} -{self.customer.name}" class Invoice_product_list(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveBigIntegerField() forms.py: from django import forms from .models import Invoice_customer_list,Invoice_product_list,Product # Form for the Invoice model class Invoice_customer_Form(forms.ModelForm): class Meta: model = Invoice_customer_list fields = ['customer'] labels = { 'customer': 'Select Customer', } class Invoice_product_form(forms.ModelForm): class Meta: model = Invoice_product_list fields = ['product', 'quantity'] labels = { 'product':'Select Product', 'quantity':'Enter quantity', … -
Square Webhook doesn't give confirmation if the payment is done or not to Python-django
I'm encountering a critical issue where my Django backend is unable to receive confirmation from Square about whether a payment has been completed. Here are the environment details for reference: Python: 3.13.2 Django: 5.1.6 Square SDK: 43.0.0.20250618 Problem Summary: The core flow of the payment process is as follows: The user creates an order via the CreateSquareOrder method. This successfully generates a Square-hosted checkout page where the user completes the payment. The payment is processed correctly—I can confirm the funds are reaching my Square account. However, the issue arises after payment is completed: The webhook I’ve configured (https://api.mydomain.com/api/wallet/webhooks/square/) is supposed to be triggered automatically by Square to confirm the payment. Unfortunately, this webhook is not being triggered properly. I’ve checked the server logs, and I consistently receive a 401 Unauthorized response from Square's webhook call attempts. Because the webhook is failing, the subsequent logic in my Django app—specifically, the VerifySquareOrder method—is not executed, meaning critical application records are never created. Additional Information: Below is the backend code I’m currently using to handle CreateSquareOrder, SquareWebhookView and VerifySquareOrder requests. I’ve followed the latest version guidelines and best practices as per the Square documentation: import uuid from decimal import Decimal from django.utils import … -
How to show following count in template django
I was able to get count for follower/following users, but when user A follow user B, user B accept user A follow request(they are in friends list). After accept request, I want to display count (1) for user A Follower List and user B following list... So it looks like this: user A follower (1) following (1).... For user B follower (1) following (1). Just as the attached image on my question..... class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) friends = models.ManyToManyField('Profile', related_name="my_friends", blank=True) class FriendRequest(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') def ProfileView(request, username): user = request.user friends_received = FriendRequest.objects.filter(to_user=user) # Option 2: Get users that have sent friend requests to the current user friends_sent = FriendRequest.objects.filter(from_user=user) <p><b>{{ friends_sent|length|humanize_number }}</b> Following</p> <p><b>{{ friends_received|length|humanize_number }}</b> Followers</p> -
How can I split the two forms so that only one of the two forms in the template is processed?
Have a nice day! I am trying to place two independent forms on one template. I have them placed but there is a problem that both forms are being checked. Validation of both forms is being checked. Although I only have one button clicked in the first form. How can I split these two forms so that they are independent? I need the form to be checked separately. Separately - the first and second forms. When I fill out one form - I get an error because both forms are being checked. How can I separate the forms - separate the forms during checking. How can I split the two forms so that only one of the two forms in the template is processed? enter image description here views.py def book(request, pk): context = {} Category_pk_for_form_maim.objects.all().delete() filter_qs_category = Category_pk_for_form_category.objects.filter(name_object=pk) filter_qs_category = filter_qs_category.values("category_name") for item in filter_qs_category: entry = item new_entry = Category_pk_for_form_maim(categoty_name=entry) new_entry.save() form_category_1 = Category_pk_for_form_category_Form(request.POST or None) form_2 = Form_GPR(request.POST or None) if request.method == 'POST': if "form_category_1" in request.POST: if form_category_1.is_valid(): model_instance = form_category_1.save(commit=False) name_object = pk category_name = model_instance.category_name new_entry = Category_pk_for_form_category(name_object=name_object, category_name=category_name) new_entry.save() return redirect("book-detail", pk) if "form_2" in request.POST: if form_2.is_valid(): model_instance = form_2.save(commit=False) name_object … -
how to apply the two dropdown selectors in django
form.py: from django import forms from .models import Invoice, InvoiceItem Form for the Invoice model class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = ['customer'] labels = { 'customer': 'Select Customer', # 'total_amount': 'Total Amount', } this above core is create a field to choose the customer at the time of bill creation but also i want to add the new field for the product adding in that product field i want to select the product which are present in the product list but whenever i am trying to add one more field in this form for the implementation of this functionality its showing me error please any one can help me to solve this and tell me what is the issue whay am i getting this error?? i am expection to add the input dropdown in the invoice app for the invoice creation -
How do I log filtered GET requests on a Django REST Framework ModelViewSet using @action?
I have a ModelViewSet for EventReportLink and need to log every time someone queries with ?event_report__id=<id>. I’ve tried adding a custom @action(detail=False, methods=['get']), but I’m not sure if I’m implementing it correctly or if there’s a better way. I added: @action(detail=False, methods=['get'], url_path='log-test') def log_test(self, request): event_report_id = request.query_params.get('event_report__id') logger.info(f"ID: {event_report_id}") queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Expecting logs and correct filtering results. I’m receiving filtered results but not sure if this is best practice. What would be a more idiomatic approach? P.S. I also consulted this related question, which discusses how to add behavior before/after the default create logic using super().create(request). However, I wasn’t entirely sure if it applies to my case with query param filtering and logging via @action, so I’m still exploring best practices. -
How to remove hardcoded library version info from minified JS files in Django production?
'm using Django to serve static files in production, and I've noticed that many of the third-party JS libraries (like jQuery, Bootstrap, JSZip, and Moment.js) include hardcoded version numbers inside the minified files. For example: /*! jQuery v3.3.1 */ "version": "3.7.1" [ These version details are accessible to anyone via the browser's DevTools, and I’m concerned this could expose the application to targeted attacks if any of the libraries are outdated. Questions: What is the best way to strip or hide these version numbers from minified JS/CSS in a Django production environment? Should I re-minify third-party libraries myself before using them in Django? Are there best practices or tools recommended for this kind of hardening? Thanks! -
How to integrate ZKTeco ZK4500 fingerprint scanner with a Django + React web application?
I'm working on a web application using Django (backend) and React (frontend), and I want to integrate the ZKTeco ZK4500 fingerprint scanner into my system for user authentication. 🔍 My Setup: Device: ZKTeco ZK4500 (USB fingerprint scanner) Backend: Django (Python) Frontend: React (JavaScript) OS: Windows 10 📌 What I want to achieve: Capture a fingerprint using the ZK4500 from the client machine Send the fingerprint data to the Django backend Use this data to register or authenticate a user 🧩 The problem: Since this is a web-based application, I understand that I cannot directly access USB devices like the ZK4500 via browser (React). I’m confused about: What SDK/library should I use (ZKFinger SDK, BioTime SDK, etc.)? How can I create a middleware (Python/C#/Electron) that communicates with the ZK4500 and sends data to Django? Is there any existing solution or recommended architecture for this? 🧪 What I’ve tried: I’ve searched for ZKTeco SDKs and found references to zkemkeeper and ZKFinger SDK for Windows, but most examples are in C# and are designed for desktop applications. I have not found a clear solution for integration with a web-based stack (Django + React). ❓ My questions: What is the best approach to use …