Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Cookiecutter Django 'docker: Error response from daemon'
I'm trying to set up a new project and keep getting this error: Installing python dependencies using uv... sha256:bdb43f6ddf37f279e9384342167f6bb16c5a97e7514d890714d9fbf0eb753f15 docker: Error response from daemon: create .: volume name is too short, names should be at least two alphanumeric characters. See 'docker run --help'. Error installing production dependencies: Command '['docker', 'run', '--rm', '-v', '.:/app', 'cookiecutter-django-uv-runner:latest', 'uv', 'add', '--no-sync', '-r', 'requirements/production.txt']' returned non-zero exit status 125. ERROR: Stopping generation because post_gen_project hook script didn't exit successfully Hook script failed (exit status: 1) I downloaded the latest cookiecutter django, and it suddenly starts this problem. Was working quite well before. -
django admin migration with postgres_fdw
I use postgres_fdw to create relations between my databases Here I have a foreign model with the name: class User(AbstractUser): ... class Meta: db_table = '"foreign_user"."accounts__user"' managed = False which pointing to this model in another django project: class User(AbstractUser): ... class Meta: db_table = 'accounts__user' managed = False I did run the python manage.py makemigrations and python manage.py migrate I got an error from django admin Applying admin.0001_initial...Traceback (most recent call last): ... django.db.utils.ProgrammingError: referenced relation "accounts__user" is not a table but when I ran migrations with specific apps (my installed app only) and the admin migrations didn't run, everything worked well and all relations with User model created. I also made sure that I set AUTH_USER_MODEL='accounts.User I already made the foreing servers and foreign schemas as needed I did check the database, and all of the tables and relations were fine -
Django Testing in microservices with more than 1 db running
I would like to ask about a certain topic that is tough one. Im working in a project that has microservices architecture with more than 1 databases running every time. in django, how can I perform unit tests to it? im like everything is in a different database and totally seperate and the whole idea of unit tests seperates everything more. I tried to use mocking, but the problem is that I need certain information from the other database to run some tests in another one. the problem is that I dont know how to run 2 databases (temporal for the unit test purposes) concurrently. -
DRF pagination “next” link uses a stale hostname behind GKE Ingress — how do I make it use the real host?
What are the details of your problem? I’m running a Django REST Framework API on Google Kubernetes Engine (GKE) behind an Ingress. When I request: https://www.my-api-url.com/api/stores/?page=1&active=true I get correct results, but the pagination next link is built with a stale hostname: https://api-back.my-api-url.com/api/stores/?active=true&page=2 That hostname used to exist in a previous ingress but was removed. I searched the entire codebase, Kubernetes manifests, and ingress configs and I can’t find it anywhere. I found this related question stating DRF uses the request hostname for the paginator, but I still can’t figure out where that stale host is coming from in a GKE/Ingress setup: How to change the host in next key in a paginated URL in django rest framework? What did you try and what were you expecting? I expected DRF to build next with www.my-api-url.com. I checked and/or tried: ALLOWED_HOSTS contains the correct host. Toggling USE_X_FORWARDED_HOST (True/False). Setting SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'). Ensuring the new ingress uses the correct public host and removing the old one entirely. Verified no hard-coded references to api-back.my-api-url.com in the repo or K8s manifests. Despite that, the next link still shows the stale hostname. Question: In a GKE Ingress setup, which header/setting actually controls the host … -
action button to export questionnaire in csv form in Django web app causing 504
Ya so i created this action button on a django web app and when i tried to use it got this error {"code":504,"message":"upstream request timeout"} so i do agree that its a big DB, although it would have become a big DB in future , so how can i get rid of this error here is my code class UserQuestionnaireAdmin(admin.ModelAdmin): readonly_fields = ( "user", "questionnaire", "token", "completed_at", "created_at", "total_score" ) inlines = [UserQuestionnaireAnswerInline] actions = ['export_as_csv'] def export_as_csv(self, request, queryset): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="questionnaire_results.csv"' writer = csv.writer(response) # Header row writer.writerow([ "User ID", "User Name", "Questionnaire", "Question", "Answer", "Score", "Completed At", ]) for uq in queryset: answers = uq.answers.all() # for those questionnaire which have populated rows if answers.exists(): for answer in answers: writer.writerow([ uq.user.id, f"{uq.user.first_name} {uq.user.last_name}" if uq.user.first_name and uq.user.last_name else "", uq.questionnaire.title if uq.questionnaire else "", answer.question.text if answer.question else "", answer.answer_option.text if answer.answer_option else "", answer.answer_option.weight if answer.answer_option else "", uq.completed_at if uq.completed_at else "", ]) else: # Write empty row for the questionnaire writer.writerow([ uq.user.id, f"{uq.user.first_name} {uq.user.last_name}" if uq.user.first_name and uq.user.last_name else "", uq.questionnaire.title if uq.questionnaire else "", "", "", "", # no question/answer/score uq.completed_at if uq.completed_at else "", ]) return response export_as_csv.short_description … -
Modal window in wagtail page editing interface
I want to add a custom BlockFeature and for that i need a modal window for input. I don't understand how to make a modal input window so that the entred data will go straight to my custom blockfeature props. The feature i'm working on is an ordered list that starts with a given number (). So yeah, basically, i need that modal window to enter the starting number @hooks.register('register_rich_text_features') def register_ol_custom_feature(features): feature_name = "ol-custom" type_ = "ol-custom" control = { "type": type_, "label": "ol+", "element": "ol", "description": "Set start", } features.register_editor_plugin( 'draftail', feature_name, BlockFeature( control, js=["static/js/orderedListCustom.js"], ), ) db_conversion = { "from_database_format": { "ol[start]": BlockElementHandler(type_) }, "to_database_format": { 'block_map': { type_: lambda props: DOM.create_element( "ol", {"start": props.get("start") if "start" in props else 1} ) } }, } features.register_converter_rule("contentstate", feature_name, db_conversion) features.default_features.append(feature_name) I tried several js codes that i found online or got from ai, none of them worked (my bad, i suck at js). Also came across one post on here, but it didn't help (: In the end, i'm not even sure what things i need to consider/add/alter, what's the workflow here. Can anyone help? -
I can’t find the information in the knowledge base pinecone
I’m developing a RAG system with Python, Django, and Vapi for a voice client, but when I ask a question, it tells me it can’t find any results. My scores range from 0.2687 to 1.0004. An important point is that the transcription I’m creating sometimes isn’t very good. I’m sending you the code for my search function to see if you can help me. def search_context(query, top_k=5): import unicodedata import re def limpiar_texto_ligero(texto: str) -> str: # Solo para extraer keywords/fallback; NO para el embedding principal t = texto.lower() t = re.sub(r'\s+', ' ', t).strip() return t try: # 1) Embedir la consulta ORIGINAL (mejor señal semántica) print(f"[DEBUG search_context] Query original (sin normalizar): '{query}'") emb = openai_client.embeddings.create( input=[query], # <- sin normalizar model="text-embedding-3-small" ).data[0].embedding resultados_finales = [] vistos = set() # Búsqueda A: consulta original print(f"[DEBUG search_context] Búsqueda A: consulta original") rA = index.query(vector=emb, top_k=top_k*2, include_metadata=True, include_values=False) for m in (rA.matches or []): if m.id not in vistos: resultados_finales.append(m); vistos.add(m.id) print(f"[DEBUG search_context] Búsqueda A encontró: {len(rA.matches or [])}") # Búsqueda B: palabras clave (limpieza ligera) if len(resultados_finales) < 2: print(f"[DEBUG search_context] Búsqueda B: palabras clave") qlite = limpiar_texto_ligero(query) keywords = [w for w in qlite.split() if len(w) > 3][:3] if … -
How to find out the number of connections to websocket and get a set of users in Django channels
I need to somehow get all users collected to the group in order to exclude them from receiving real-time notifications. Can this be done using standard methods, or are there libraries available to solve this problem? At the moment, I have not been able to find a function that would count the number of connections. -
How can I fix the "Calling format_html() without passing args or kwargs is deprecated." in PyCharm?
I have the following code: def _demo_preview_message(request): if not getattr(settings, 'IS_DEMO', False): return last = DemoEmail.objects.order_by('-id').first() if last: messages.success( request=request, message=format_html("Email queued (demo). <a href='{}'>Preview</a>", reverse('demo_outbox_detail', args=[last.pk])) ) At the line: message=format_html("Email queued (demo). <a href='{}'>Preview</a>", reverse('demo_outbox_detail', args=[last.pk])) PyCharm gives me the following message: Calling format_html() without passing args or kwargs is deprecated. How can I fix this? -
How to use Better-Auth with Django Rest Framework and apply role-based actions (admin vs user)?
I’m building a project with: Frontend: Next.js using Better-Auth for authentication Backend: Django + Django REST Framework (DRF) Better-Auth issues JWTs to clients, and I want Django to trust those tokens. For example: Normal users can access basic endpoints (/profile, /orders/). Only admins should be able to access certain resources (e.g. /reports/, /admin-tools/). What’s the correct way to: Make Django validate Better-Auth’s JWTs? Parse the role claim from the token so that I can distinguish between "user" and "admin"? Apply those roles in DRF so that only admins can access certain views? I’ve seen examples with rest_framework_simplejwt, but those usually assume Django is the one issuing the tokens. In my case, tokens are issued by Better-Auth (Next.js). Previously, I was using Djoser + Auth.js, but since the Auth.js team officially announced it will now be maintained by the Better-Auth team and recommended using Better-Auth for new projects, I’ve decided to ditch Auth.js and move forward with Better-Auth. How should I configure DRF authentication + permissions for this setup? -
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 …