Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding automatic field in django
i have a product model in Django these products have some specific field which should be set for some products for example if product is tier the admin should add size field which must be numeric or if the product is t-shirt the admin should add color field for it i don't know how to code this in Django please help me thanks -
Filtering Django QuerySet after using a Window function
For a simple model: from django.db.models import CharField, Model, PositiveIntegerField class Example(Model): category = CharField(max_length=20, null=False, blank=False) version = PositiveIntegerField(null=False, blank=False) class Meta: unique_together = ["category", "version"] And some sample data: Example.objects.update_or_create(id=1, category="Thing 1", version=1) Example.objects.update_or_create(id=2, category="Thing 1", version=2) Example.objects.update_or_create(id=3, category="Thing 1", version=4) Example.objects.update_or_create(id=4, category="Thing 2", version=1) Example.objects.update_or_create(id=5, category="Thing 2", version=2) Example.objects.update_or_create(id=6, category="Thing 3", version=3) I would like to use window functions to get: The examples that, only from the sub-set with the latest version in each category, have ids either 1, 4, 5 or 6. I am trying to do this using the RowNumber window function: from django.db.models import F, Window from django.db.models.functions.window import RowNumber results = Example.objects.alias( rn=Window( expression=RowNumber(), partition_by=[F("category")], order_by="-version" ), ).filter(rn=1).filter(id__in=[1,4,5,6]) print(results.query) print(results) This generates the query: SELECT "col1", "col2", "col3" FROM ( SELECT * FROM ( SELECT "greatest_n_example"."id" AS "col1", "greatest_n_example"."category" AS "col2", "greatest_n_example"."version" AS "col3", ROW_NUMBER() OVER (PARTITION BY "greatest_n_example"."category" ORDER BY "greatest_n_example"."version" DESC) AS "qual0" FROM "greatest_n_example" WHERE "greatest_n_example"."id" IN (1, 4, 5, 6) ) "qualify" WHERE "qual0" = 1 ) "qualify_mask" And returns examples 1, 5 and 6; which is not what is required. The latest for category="Thing 1" is version=4 and the filter on rn should be applied before the filter … -
Keeping the current chosen option from <select> marker passed from Django
I'm currently trying to create a website/webapp for my portfolio's bank using Django 5.2/HTML/CSS/JS. I got stuck on one small part of creating bank statement subpage. The issue I have encountered is: When user is setting how he wants his statement to be ordered the option of both select tags is reverting back to it's default state. Please keep in mind I'm currently focusing on learning Django as part of my Python learning plan and I'm practically a noob in JS. I do however understand a lot since I've done basics of Python(I passed PCEP and PCAP) and apart from semanthic changes most of the rules seems to be similar in OOP. Here is my current code from statement.html: {% extends "bank_accounts.html" %} {% block title %} Statement {% endblock %} <script type="text/javascript"> function change_order(o, o2) { document.getElementById(o).selected=True; document.getElementById(o2).selected=True; } </script> {% block main %} <p>{{ order }} {{ order2 }}</p> <h1>STATEMENT</h1> <h3> Below you can see statement from current month for your account({{ acc }}):</h3> <form method="POST" onload="change_order('{{ order }}', '{{ order2 }}');">{% csrf_token %}Sort by: <select name="order-by" id="order-by"> <option id="date" value="date">Date</option> <option id="from" value="from">From</option> <option id="to" value="to">To</option> <option id="type" value="type">Type</option> <option id="sum" value="sum">Sum</option> </select> <select name="order-by2" id="order-by2"> <option … -
Admin list filter, grouped by first letter and expanded group
I have a model Source with a foreign key to model Place. On the changelist page of the Source model, I would like a list filter that shows all letters of the alphabet, and when clicked on 'A' shows all place names starting with 'A', which are clickable to show only Sources in the list that have that place in there fk field. Simplified models: class Source(models.Model): place = models.ForeignKey(Place, null=True, place=True, on_delete=models.SET_NULL class Place(models.Model): name = models.CharField(max_length = 255, primary_key=True) I currently have this: class PlaceFilter(admin.SimpleListFilter): title = 'first letter of place name' parameter_name = 'letter' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) options = qs.values_list(Substr('place__name', 1, 1), Substr('place__name', 1, 1)) \ .annotate(fl=Count(Substr('place__name', 1, 1))).distinct() \ .order_by(Substr('place__name', 1, 1)) options = [(i, f'{j} ({k})') for i,j,k in options] return options def queryset(self, request, queryset): if self.value(): return queryset.filter(place__name__istartswith=self.value()) Which does show all the letters, but when clicked on a letter the list contains all sources with a place that starts with that letter. Furthermore, I'm in the Netherlands and some places here have names that start with 's, 't, sometimes followed by a hyphen, sometimes not. These names should not be grouped by the starting single quote, but (usually) … -
Django Celery Beat sending many-per-hour tasks but not daily tasks
This is a really weird situation. Tasks that are scheduled to run every several minutes every hour of the day (e.g. "*/20 * * * *") are being sent to Celery (with entries in Celery Beat's log) and Celery is running them. Tasks that are to be run once per day (e.g. "15 11 * * *") are not happening at their designated times though, and nothing is being written to Celery Beat's log for those. I have checked the contents of the tables in the database, and everything looks right, except, of course, that last_run_at is null for the tasks that are not being sent. # select * from django_celery_beat_periodictask where id=7; id | name | task | args | kwargs | queue | exchange | routing_key | expires | enabled | last_run_at | total_run_count | date_changed | description | crontab_id | interval_id | solar_id | one_off | start_time | priority | headers | clocked_id | expire_seconds ----+----------------------------------------------+---------------------------------+------+--------+-------+----------+-------------+---------+---------+-------------+-----------------+-------------------------------+-------------+------------+-------------+----------+---------+------------+----------+---------+------------+---------------- 7 | hub_builtin__dhmaintenance.tasks.rotate_logs | dhmaintenance.tasks.rotate_logs | [] | {} | | | | | t | | 0 | 2025-09-25 04:39:20.172338+00 | | 6 | | | f | | | {} | | # select * from django_celery_beat_crontabschedule where id=6; … -
Why are some records not added to the m2m table?
Why aren't some records being added to the m2m table? If the table already contains a record with a specific topic and system (service can be any), then the next addition of a record with a similar topic and system does not occur. I don't get any errors when run this code. Expected result: Expected result Actual result: Actual result Models: class Systems(BaseModel): sys_id = models.AutoField(primary_key=True) sys_name = models.CharField(max_length=256, unique=True, null=False) def __str__(self): return self.sys_name class Meta: verbose_name = "Systems" verbose_name_plural = "Systems" ordering = ['sys_id'] class ServiceCatalog(BaseModel): sc_id = models.AutoField(primary_key=True) sc_service = models.CharField(max_length=250, unique=True, null=False) def __str__(self): return self.sc_service class Meta: verbose_name = "Service catalog" verbose_name_plural = "Service catalog" ordering = ['sc_id'] class ChatTopics(BaseModel): ct_id = models.AutoField(primary_key=True) ct_systems = models.ManyToManyField(Systems, blank=True, through="chattopics_m2m") ct_chat_id = models.CharField(max_length=20, null=False, blank=False) ct_chat_name = models.CharField(max_length=50, null=False, blank=False) ct_topic_id = models.CharField(max_length=10, null=True, default=None, blank=True) ct_topic_name = models.CharField(max_length=50, null=True, default=None, blank=True) def __str__(self): return f'{self.ct_chat_name} ({self.ct_topic_name})' class Meta: verbose_name = 'Topics' verbose_name_plural = 'Topics' constraints = [ models.UniqueConstraint(fields=('ct_chat_id', 'ct_topic_id'), nulls_distinct=False, name='chattopics_ct_chat_id_ct_topic_id_unique') ] class ChatTopics_m2m(BaseModel): ctm_id = models.AutoField(primary_key=True) ctm_chat_topic = models.ForeignKey(ChatTopics, on_delete=models.CASCADE, null=False) ctm_system = models.ForeignKey(Systems, on_delete=models.CASCADE, null=False) ctm_service = models.ForeignKey(ServiceCatalog, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering = ['ctm_system'] with transaction.atomic(): chat_topic = ChatTopics.objects.get(ct_id=chat_topic_id) system = Systems.objects.get(sys_id=system_id) … -
Trouble deciding schema of an SQL database in Django
I am building a database which has in it a bunch of molecules and a bunch of different attributes ( e.g. ionization energy levels ). Each attribute may have one or many values and I'm not sure what the best way to represent this is. I am very new to relational databases so I'm having trouble figuring out the best ACID compliant way of storing it. I am also very new to Django, though I have worked through the tutorial and some of the documentation. I should mention as well that currently I'm using sqlite as my RDBMS, as the website will be read only. My current conception is to have two models. One for describing the molecule, right now this is just its name, but it may end up including other descriptors as well. The second model would be for the attributes, its effectively just attribute name, molecule name, and a single value that the attribute holds. They have a one to many relationship from the molecule name to the attribute values. But this means that the attribute name and molecule name will be repeated a lot. Is this ok? Is there a better method? Eventually I'd like users … -
How can I render unlimited nested replies (Reddit-style) in a single Django template?
I’m building a Reddit-style comment system with Django, and need users to be able to reply not only to a post but also to any comment, indefinitely deep. My goal in here is when a user replies to a reply, that reply should itself be commentable, forming a true tree—not just two levels. With below code: Top-level comments display fine, direct replies to a top-level comment show up, but replies to those replies never appear even though they’re saved correctly in the database. I’d love to keep it clean and avoid infinite {% for %} nesting. Is there a recommended Django-template pattern (perhaps a recursive template tag or custom inclusion tag) that works without breaking CSRF for the reply forms? My model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="comments" ) up_vote = models.BigIntegerField(blank=True, null=True) down_vote = models.BigIntegerField(blank=True, null=True) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.CASCADE, related_name="replies" ) body = models.TextField() created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["created_at"] def __str__(self): return f"Comment by {self.author} on {self.post}" my views: @login_required def post_details(request, slug): post = get_object_or_404(Post, slug=slug) community = post.community # Handle comment or reply POST if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): … -
TypeError: string indices must be integers when using Google login with django-allauth
I'm encountering the following error when attempting to implement Google login using django-allauth in my Django project: social_login = adapter.complete_login(request, app, token, response=response) File "/.venv/lib/python3.8/site-packages/allauth/socialaccount/providers/google/views.py", line 43, in complete_login response["id_token"], TypeError: string indices must be integers Right now im using django-allauth version 0.54.0 and django 2.2.28 I have the following GoogleLogin class set up for handling Google OAuth2 authentication: class GoogleLogin(SocialLoginView): authentication_classes = [] permission_classes = [] adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client callback_url = "https://developers.google.com/oauthplayground" Frontend sends me just the access_token In the GoogleOAuth2Adapter, the complete_login method is implemented to decode the id_token from the Google response: class GoogleOAuth2Adapter(OAuth2Adapter): provider_id = GoogleProvider.id access_token_url = ACCESS_TOKEN_URL authorize_url = AUTHORIZE_URL id_token_issuer = ID_TOKEN_ISSUER def complete_login(self, request, app, token, response, **kwargs): try: print(response) identity_data = jwt.decode( response["id_token"], # Since the token was received by direct communication # protected by TLS between this library and Google, we # are allowed to skip checking the token signature # according to the OpenID Connect Core 1.0 # specification. # https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation options={ "verify_signature": False, "verify_iss": True, "verify_aud": True, "verify_exp": True, }, issuer=self.id_token_issuer, audience=app.client_id, ) except jwt.PyJWTError as e: raise OAuth2Error("Invalid id_token") from e login = self.get_provider().sociallogin_from_response(request, identity_data) return login oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter) -
Count distinct values of Subquery
I've got these models: class Component(models.Model) name = models.CharField(max_length=50) class ComponentAttribute(models.Model) component = models.ForeignKey(Component) context = models.ForeignKey(Context) subcategory = models.ForeignKey(SubCategory) material = models.ForeignKey(Material) measurement = models.ForeignKey(Measurement) value = models.FloatField() I want to annotate the count of unique attributes to each component in a QuerySet. A attribue is unique when it has a unique combination of context, subcategory and material for a given component. Based on other posts here and the Django documentation I craftet a Query based on a subquery. # Create a subquery that counts the distinct combinations float_attributes_count = Subquery( ComponentAttributeFloat.objects .filter(component=OuterRef('pk')) .order_by( 'subcategory_id', 'context_id', 'material_id') .distinct( 'subcategory_id', 'context_id', 'material_id') .values("component__id") .annotate(count=Count('id')) .values('count')) components = Component.objects.annotate( unique_attributes=float_attributes_count ) When I now try to equate that query with this basic loop to print my result. for component in components: print(f'{component}: {component.unique_attributes}') I get hit with this error: NotImplementedError: annotate() + distinct(fields) is not implemented. It looks like the combination of requirements I have lead to an query that is unexecutable and I can't find examples that check all the boxes for me. Can anyone help me with a working query using an other path? (For refrence I use a PostgreSQL database which should support this distinct statement see: https://docs.djangoproject.com/en/5.2/ref/models/querysets/#django.db.models.query.QuerySet.distinct) -
ModuleNotFoundError: No module named 'captcha'
guys, I'm trying to add a Google Captcha to a Django form, but I still keep getting the following error even when everything has been successfully configured. ** Is there a better way to make it work?** Here are my code configuration and I installed the pip install django-recaptcha. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contact', 'captcha', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] from django import forms from django_recaptcha.fields import ReCaptchaField from django_recaptcha.widgets import ReCaptchaV2Checkbox class ContactForm(forms.Form): email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) -
StreamingHttpResponse being buffered when using uvicorn/gunicorn/daphne in Django
I have a very simple view that Streams a repsonse. When using python manage.py runserverthe stream works as expected. But, when we use uvicorn app.asgi:application or daphne app.asgi:application or gunicorn app.asgi:application the stream is buffered in the UI and the response arrives completed instead of by chunks. result = core_services.generate_ai_v3_response( prompt=prompt, previous_response_id=previous_response_id, broker_id=broker_id, ) response = StreamingHttpResponse(result, content_type="text/event-stream") # Add proper streaming headers # Add aggressive streaming headers response["Cache-Control"] = "no-cache" response["X-Accel-Buffering"] = "no" return response -
What's the difference between blank=True and null=True in Django model fields?
I'm learning Django and trying to understand the difference between blank=True and null=True when defining model fields. I created a model with both null=True and blank=True, and then tried submitting a form with the field left empty. I expected it to save NULL in the database and not throw a validation error. It worked, but I'm not sure why both options are needed — that's what I'm trying to understand clearly. -
django-vite static assets being served but not loading on an Nginx deployment
I'm deploying a simple Django project on a local Ubuntu server VM running Docker (3 containers, Postgres, nginx and Django). The project uses a lot of HTMX and DaisyUI. On my dev environment they worked well while being served by a Bun dev server and using django-vite, but now on prod everything works perfectly fine, except for the static assets generated by django-vite. The strangest part is that the files are being delivered to the clients but not loading correctly (the app renders but only the static assets collected by Django, like icons, are being displayed. If I check the network tab on my devtools, I can see the django-vite files are being served). Any idea what could be causing this? Here is my vite.config.mjs import { defineConfig } from "vite"; import { resolve } from "path"; import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ base: "/static/", build: { manifest: "manifest.json", outDir: resolve("./src/staticfiles"), emptyOutDir: false, write: true, rollupOptions: { input: { main: "./src/static/js/main.js", }, output: { entryFileNames: "js/[name].[hash].js", chunkFileNames: "js/chunks/[name].[hash].js", assetFileNames: "assets/[name].[hash][extname]", }, }, }, plugins: [tailwindcss()], }); Here is my nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; # sendfile on; # tcp_nopush on; … -
Django migration successfully applied, but the database is not modified
I need to use a secondary SQLite database in a new Django project. This database is on the local filesystem but outside the Django folder. Its path is specified in a .env file at the root of the Django project. I want Django to be able to manage migrations on that database, but I already have data in it, which I don't want to loose. I was able to integrate the database into the Django project, and I see no error at any point. I can fetch data from the database via the Django shell. However, when I try to apply migrations, nothing happens: the database is not modified, but Django doesn't give me any error (in fact it says the migration has been applied). Here's what I did: created an "archiver" app within Django within this app, created a routers.py file with the following code: class ArchiverDbRouter: def db_for_read(self, model, **hints): if model._meta.app_label in ['archiver']: return 'archiver' return None def db_for_write(self, model, **hints): if model._meta.app_label in ['archiver']: return 'archiver' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in ['archiver']: return db == 'archiver' return None configured settings.py to use two databases. The idea is to keep the … -
How do you deal with permission management when using Elasticsearch indexes?
I am using django-guardian for per-object permission management and django-elasticsearch-dsl for quicker queries across our data. It's pretty straightforward for public lists, but I am having difficulties designing a scalable permission management, so that the filtered list would show only those items that the current user request.user has access to view and change. Some solutions suggested by AI: Get a list of uuids that the user has access to, and then filter items in elasticsearch by those uuids (not very scalable). Post-process the public results with django-guardian API functions - however that takes too long for entries with tens of thousands of results (there is a possibility to skip pagination and process only the first page, but that's not preferable). Add a list of user ids and group ids who can view, edit, and delete items to the item index and check the current user's id and group ids against those fields. Create an index for the User model with all viewable, editable, and deletable items by their uuids and then do terms_lookup in that index to filter list of items in question by the uuids the user can access. All those approaches are questionable to me, when I am … -
"Internal Server Error" when sending email via Django using DigitalOcean
When trying to send an email from a Django production setup (using gunicorn) on a Digitalocean droplet, I get "Internal Server Error" on the browser, and gunicorn logs this error: … File "/usr/lib/python3.13/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) ~~~~~~~~~~~~^^^^^^^^^^^^ File "/usr/lib/python3.13/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^ self.source_address) ^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/socket.py", line 849, in create_connection sock.connect(sa) ~~~~~~~~~~~~^^^^ File "/usr/lib/python3.13/site-packages/gunicorn/workers/base.py", line 204, in handle_abort sys.exit(1) ~~~~~~~~^^^ SystemExit: 1 This used to work without issues last year. -
How to use DRF serializer fields as django-filter filter fields?
I’m working with Django REST Framework and django-filter to implement API filtering. I created custom serializer fields (for example, a JalaliDateField that converts between Jalali and Gregorian dates, and applies Django’s timezone settings). I expected that I could just pass these serializer fields into a django_filters.Filter by setting field_class, but it turns out Filter.field_class is only compatible with django.forms.Field, even when using django_filters.rest_framework. So my question is: Is there a clean way to make django-filters work directly with DRF serializer fields? What I tried Naively plugging in DRF serializer fields: class JalaliDateFilter(django_filters.Filter): field_class = MyCustomJalaliDateSerializerField This fails, since django-filters expects a forms.Field, not a DRF serializers.Field. Proposed solution #1: Write a wrapper that adapts DRF fields into Django form fields Here’s a minimal sketch: from django import forms from rest_framework import serializers class DRFFieldFormWrapper(forms.Field): """ Wrap a DRF serializer field so it can behave like a Django form field. """ def __init__(self, drf_field: serializers.Field, *args, **kwargs): self.drf_field = drf_field kwargs.setdefault("required", drf_field.required) kwargs.setdefault("label", getattr(drf_field, "label", None)) super().__init__(*args, **kwargs) def to_python(self, value): if value in self.empty_values: return None return self.drf_field.run_validation(value) def prepare_value(self, value): return self.drf_field.to_representation(value) Then, a custom filter: import django_filters class DRFFieldFilter(django_filters.Filter): def __init__(self, *args, drf_field=None, **kwargs): if drf_field is None: … -
SSL Certificate error on SMTP Django DRF App
I have a Django DRF Backend that works just OK when using EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend". But then, switching to SMTP powered by Google as: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config("GMAIL_APP_HOST_USER") EMAIL_HOST_PASSWORD = config("GMAIL_APP_HOST_PASSWORD") DEFAULT_FROM_EMAIL = "TestApp" ACCOUNT_EMAIL_SUBJECT_PREFIX = "" I get a [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Basic Constraints of CA cert not marked critical This is being tested in a Windows 11 PC. Error details with Traceback: Django Version: 5.2.6 Python Version: 3.13.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.headless', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'dj_rest_auth', 'dj_rest_auth.registration', 'corsheaders', 'authentication.apps.AuthenticationConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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', 'allauth.account.middleware.AccountMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware'] Traceback (most recent call last): File "C:\dev\myProject\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\generic\base.py", line 105, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\utils\decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\decorators\debug.py", line 143, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch return super().dispatch(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\rest_framework\views.py", line 515, … -
Discussion About Architecture: ROS2-Django-Webinterface
I am currently building a cobot/robot arm control interface and workflow planning tool. I am currently contemplating all my architecture choices so far, because I feel like the architecture is not scaling well and could fail under large loads. So I need to ask the community... General Architecture Overview The whole architecture is what I would call microservice-based (correct me if I am wrong). I have multiple standalone components (standalone means containerized in this case and also with its own area of functionality. E.g. camera controller, robot controller, gripper controller etc.). All of these components use ROS2 for communication and are implemented in their respective language, mostly C++ and Python. Then there is the Core Application which is a backend for connecting all information and managing the components. This is kind of the brain. This brain also has a UI. For the Core/UI stack I chose Python Django + ReactJS. I chose this stack because: I am fluent in Python and React, fast Prototyping for the first Prototype, Direct ROS2 Integration in Python, Django has a good ORM and supports async operations so that I can connect ROS2 (as a bridge for the UI kind of) and store data through … -
Django WeasyPrint high memory usage with large datasets
I am using WeasyPrint in Django to generate a PDF. However, when processing around 11,000 records, it consumes all available resources allocated to the Kubernetes pod. As a result, the pod restarts, and I never receive the generated PDF via email. Are there: Any lightweight PDF libraries that can handle generating PDFs for thousands of records more efficiently? Any optimization techniques in WeasyPrint (or in general) to reduce resource usage and generate the PDF successfully? -
Django model with FK to learner app model Group is displaying options from user admin Group
I have the following models: learner app class Group(models.Model): short_name = models.CharField(max_length=50) # company acronym slug = models.SlugField(default="prepopulated_do_not_enter_text") contract = models.ForeignKey(Contract, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() notes = models.TextField(blank=True, null=True) class Meta: ordering = ["short_name"] unique_together = ( "short_name", "contract", ) management app I've set up an Invoice model: class Invoice(models.Model): staff = models.ForeignKey(Staff, on_delete=models.RESTRICT) group = models.ForeignKey(Group, on_delete=models.RESTRICT) date = models.DateField() amount = models.DecimalField(max_digits=7, decimal_places=2) note = models.CharField(max_length=500, null=True, blank=True) When I try to add an invoice instead of the learner groups I'm being offered the user admin Group options: Can anyone help with what I'm doing wrong. I have the learner group as a FK in other models without issue. -
Django Unit Test - using factory_boy build() on a Model with Many-To-Many relationship
I’m working on writing unit tests for a DRF project using pytest and factory_boy. I’m running into issues with many-to-many relationships. Specifically, when I try to use .build() in my unit tests, DRF attempts to access the M2M field which requires a saved object, leading to errors. tests_serializers.py def test_serialize_quality_valid_data(self): user = UserFactory.build() quality = QualityFactory.build(created_by=user) serializer = QualitySerializer(quality) data = serializer.data assert data["num"] == quality.num error: FAILED quality/tests/tests_serializers.py::TestQualitySerializer::test_serialize_quality_valid_data - ValueError: "<Quality: Quality object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. model.py class QualityTag(ExportModelOperationsMixin("quality_tag"), models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField() class Quality(ExportModelOperationsMixin("quality"), models.Model): num = models.IntegerField() title = models.CharField(max_length=64) ... tags = models.ManyToManyField(QualityTag, related_name="qualities", blank=True) factories.py class QualityTagFactory(DjangoModelFactory): class Meta: model = QualityTag name = factory.Sequence(lambda n: f"Quality Tag {n}") class QualityFactory(factory.django.DjangoModelFactory): class Meta: model = Quality num = factory.Faker("random_int", min=1, max=999) @factory.post_generation def tags(self, create, extracted, **kwargs): if not create: return if extracted: for tag in extracted: self.tags.add(tag) serializers.py class QualitySerializer(serializers.ModelSerializer): tags = QualityTagDetailSerializer(many=True) created_by = UserProfileSerializer() updated_by = UserProfileSerializer() class Meta: model = Quality fields = "__all__" read_only_fields = ["quality_num", "tags", "created_by", "updated_by"] I’ve been advised to switch to .create() instead of .build(), but I’d prefer to … -
Django HttpOnly cookies not persisted on iOS Safari and WebView, but work on Chrome and Android ITP
I'm using Django to set HttpOnly and Secure cookies for my React web application. These cookies work perfectly on Chrome (both desktop and mobile) and Android devices. However, I'm encountering a major issue on iOS: -iOS Safari: Cookies are not persisted; they are treated like session cookies and are deleted when the browser is closed. -iOS React Native WebView: Similar to Safari, the cookies are not persisted. -İOS Chrome: It works. -Android React Native WebView: It works. MAX_AGE = 60 * 60 * 24 * 360 COMMON = { "httponly": True, "secure": True, "samesite": "None", "path": "/", "domain": ".kashik.net", "max_age": MAX_AGE, } def set_auth_cookies(response, access_token: str, refresh_token: str): response.set_cookie("refresh_token", refresh_token, **COMMON) response.set_cookie("access_token", access_token, **COMMON) return response I have confirmed that the max_age is set to a long duration, so it's not a session cookie by design. This issue seems to be specific to the iOS ecosystem. What could be causing this behavior on iOS Safari and WebView, and how can I ensure these cookies are properly persisted? <WebView ref={webRef} source={{ uri: WEB_URL }} style={styles.full} /* COOKIE PERSIST */ sharedCookiesEnabled thirdPartyCookiesEnabled incognito={false} /* FIX */ javaScriptEnabled domStorageEnabled allowsInlineMediaPlayback allowsFullscreenVideo mediaCapturePermissionGrantType="grant" startInLoadingState cacheEnabled={false} injectedJavaScriptBeforeContentLoaded={INJECT_BEFORE} injectedJavaScriptBeforeContentLoadedForMainFrameOnly={false} onMessage={handleWebViewMessage} onLoadEnd={() => { setLoadedOnce(true); lastLoadEndAt.current = … -
How to set up an in-project PostgreSQL database for a Django trading app?
I’m working on a Django-based trading platform project. Currently, my setup connects to a hosted PostgreSQL instance (Render). My client has now requested an “in-project PostgreSQL database”. From my understanding, this means they want the database to run locally within the project environment (rather than relying on an external hosted DB). Question: What is the best practice for including PostgreSQL directly with the project? Should I: Use Docker/Docker Compose to spin up PostgreSQL alongside the Django app, Include migrations and a seed dump in the repo so the DB can be created on any machine, or Is there another recommended approach? I want the project to be portable so the client (or other developers) can run it without needing to separately set up PostgreSQL.