Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert single <li>?
I am trying to handle multi-level menu with AlpineJS. Is it posible to insert single <ul> (or </li>) in the code below? <template x-if="item.has_children"> <!-- insert <ul> here--> </template> <template x-if="! item.has_children"> <!-- insert </li> here--> </template> -
Celery crashes when PgBouncer closes idle connections (idle timeouts enabled)
I’m encountering an issue when running Celery with PgBouncer and PostgreSQL after enabling idle connection timeouts. My stack includes: Django (served via Tornado) Celery (workers + beat) PostgreSQL PgBouncer (in front of PostgreSQL) Due to a large number of idle database connections caused by Tornado + Django, I introduced idle timeout settings to protect PostgreSQL from running out of connections. PgBouncer idle_transaction_timeout=240 (4mins) client_idle_timeout=240 PostgreSQL idle_in_transaction_session_timeout=300000 (5mins) idle_session_timeout=300000 (5mins) Problem: After applying these settings, Celery occasionally crashes with the following error: [2025-12-16 06:12:01,578: ERROR/MainProcess] Unrecoverable error: DatabaseError('client_idle_timeout\nserver closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n',) Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 351, in start component.start() File "/usr/local/lib/python2.7/site-packages/celery/worker/consumer.py", line 393, in start self.consume_messages() File "/usr/local/lib/python2.7/site-packages/celery/worker/consumer.py", line 885, in consume_messages self.connection.drain_events(timeout=10.0) File "/usr/local/lib/python2.7/site-packages/kombu/connection.py", line 276, in drain_events return self.transport.drain_events(self.connection, **kwargs) File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 760, in drain_events item, channel = get(timeout=timeout) File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/scheduling.py", line 39, in get return self.fun(resource, **kwargs), resource File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 780, in _drain_channel return channel.drain_events(timeout=timeout) File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 578, in drain_events return self._poll(self.cycle, timeout=timeout) File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 287, in _poll return cycle.get() File "/usr/local/lib/python2.7/site-packages/kombu/transport/virtual/scheduling.py", line 39, in get return self.fun(resource, **kwargs), resource File "/usr/local/lib/python2.7/site-packages/djkombu/transport.py", line 31, in _get m = … -
Django Deployment on Render: ModuleNotFoundError for WSGI Application The Problem
Demo of the Project The Problem I am attempting to deploy a Django portfolio project to Render. While the project runs perfectly on my local machine using python manage.py runserver, the deployment fails during the build process. The Render logs indicate that Gunicorn cannot locate the project module, even though the folder structure appears correct in my GitHub repository. Error Log: Bash ==> Running 'gunicorn foremanbportfolio.wsgi:application --bind 0.0.0.0:$PORT' Traceback (most recent call last): ... ModuleNotFoundError: No module named 'foremanbportfolio' ==> Exited with status 1 Minimal Reproducible Example 1. Project Structure: My repository is structured as follows: Foreman-B_MyPortfolio/ ├── manage.py ├── portfolio/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ └── asgi.py ├── pages/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ ├── views.py │ └── static/ # App-specific static │ └── pages/ │ ├── css/ │ ├── js/ │ └── images/ ├── static/ # Global static folder (all large assets) │ ├── admin/ # Admin CSS/JS/images │ ├── bootstrap/ │ ├── css/ │ ├── js/ │ ├── img/ │ └── rest_framework/ ├── templates/ │ └── pages/ │ └── foremanbportfolio.html └── staticfiles/ 2. Current Configuration … -
My Journey as a Beginner Web Developer – Need Advice [closed]
As a beginner web developer, I started my journey with **HTML, PHP, and MySQL**. I built only one real project, a **school management system** . One day, I saw someone working with **React** as a front-end developer. That moment really inspired me — I felt a bit of envy and motivation at the same time. I decided to start learning **JavaScript**, and after a few months of understanding the basics, I moved on to **React**. My long-term goal has always been to become a **full-stack developer**. While learning React, some friends advised me to choose **Node.js** as my backend, saying that _React and PHP don’t really make sense together_. I followed that advice and started learning **React + Node.js**.So far, I’ve completed **three to four small React projects**, built my **portfolio** (https://abouzari.vercel.app/), and spent **more than six months learning JavaScript and React**. Later, I enrolled in **OpenLabs (Ghana)** for an **8-month full-stack developer training program**. At the beginning, I faced a challenge: I wasn’t learning much because we were covering fundamentals I had already learned earlier — **UI/UX, HTML, CSS, JavaScript, CSS frameworks, and jQuery**. Because of that, I decided to start **Node.js on my own** while continuing with **React**. … -
"No module named django_heroku" (or django_on_heroku) error
I'm trying to install OWASP PyGoat, and then create a secure version of it. I followed method 2 on the repository's site (https://github.com/adeyosemanputra/pygoat?tab=readme-ov-file#method-2), but running the "python3 manage.py migrate" command yielded the error message in this post's title. I used "pip3 list" to verify that django_heroku was installed. I also tried with the newer django_on_heroku, but got the same result. I saw on another post that somebody tried installing psycopg-binary to fix this, but that's already installed as well. What else should I do to diagnose this problem? -
When building platforms with multiple Python services (FastAPI, Flask, Django, internal APIs), we kept facing the same issues:
When building platforms with multiple Python services (FastAPI, Flask, Django, internal APIs), we kept facing the same issues: • Authentication duplicated across services • Roles and permissions drifting over time • Weak tenant isolation • No clear audit trail We built Verge Auth to solve this centrally. It’s a Python-first authentication & authorization service that: Integrates once across FastAPI, Flask, Django, or custom Python APIs Automatically generates permissions from routes Enforces RBAC and tenant isolation centrally Provides detailed audit logs It can be: Fully self-hosted using Docker Compose (on-prem) Or used as a managed service This is aimed at teams running multiple Python services, not simple apps. Would love feedback: • Would this simplify your setup? • What would make you hesitant to adopt it? -
I just couldn't connect Railway volume With my django-Project
Here in settings.py I've added if os.environ.get("MOUNT_MEDIA"): MEDIA_ROOT = "/app/media" print("Using Railway mounted volume for MEDIA_ROOT") else: MEDIA_ROOT = BASE_DIR / "media" print("Using local folder for MEDIA_ROOT") MEDIA_URL = "/media/" in urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) else: # allow Django to serve media in production (NOT recommended, but works) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Model is image = models.ImageField(upload_to="products", default="product.jpg") description = models.TextField(blank=True, null=True) Whatever I do. I can't get to view those images..! Here is the edit product view where I am being able to view the photo @login_required def edit_product(request, pk): product = get_object_or_404(Product, pk=pk, user=request.user) if request.method == "GET": # print("GET request for product data") # Return product data as JSON for prefill return JsonResponse({ "id": product.id, "name": product.name, "price": float(product.price), "discounted_price": float(product.discounted_price) if product.discounted_price else "", "stock_quantity": product.stock_quantity, "description": product.description, "status": product.status, "image": product.image.url if product.image and hasattr(product.image, "url") else "" }) elif request.method == "POST": # Update product with submitted form data product.name = request.POST.get("name") product.price = request.POST.get("price") product.discounted_price = request.POST.get("discounted_price") or None product.stock_quantity = request.POST.get("stock_quantity") product.description = request.POST.get("description") product.status = request.POST.get("status") == "True" if "image" in request.FILES: product.image = request.FILES["image"] product.save() return JsonResponse({"success": True, "message": … -
Django Admin is showing a different model
I understand there might be a design issue here but I'm a little confused. I have two very similar models => Submission and Partial Submission. There are two other models linked to them, CheckedSubmission and CheckedPartialSubmission. The way they are displayed and checked is pretty similar, it's just that I need a separate submission model for user convenience. The problem is not with the models, but with how Django admin chooses to display them -- the submission model for some reason displays partial submissions, and the partial submission model is showing submissions. The fields and related names might be the issue too, the partial check model has this: submission = models.ForeignKey(PartialLRSubmission, on_delete=models.CASCADE, related_name="partial_checks") key_source = models.ForeignKey(AnswerKey, on_delete=models.CASCADE, related_name="partial_checks", null=True) And the full check model has this: submission = models.ForeignKey(LRSubmission, on_delete=models.CASCADE, related_name="checks") key_source = models.ForeignKey(AnswerKey, on_delete=models.CASCADE, related_name="checks", blank=True, null=True) Here's a PasteBin with models, inlines and Admins. -
How to set table column width to django admin list_display?
I want column foo (TextField 2500 chars) to have a width of 30% in admin view. Yet whatever I try, the columns widths remain equal (50% / 50%). td.foo {width: 30%;} has no effect at all. admin.py: class FooAdmin(ModelAdmin): list_display = ['foo', 'bar'] # foo column width should be 30% class Media: css = {'all': ('css/custom.css', )} custom.css: table { table-layout: fixed; } td.field-foo { width: 30%; } Working minimal html example of desired result: <!DOCTYPE html> <html> <head> <style> table { table-layout: fixed; } td.foo { width: 30%; } </style> </head> <body> <table border="1"> <tr> <td class="foo">30% width</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </table> </body> </html> -
Viviene Sandhu: Experienced Mediator & Litigator
Viviene Sandhu is a highly seasoned Advocate and Co-Managing Partner at Clifford Law LLP, listed in the Law Guide Singapore directory for her comprehensive practice. Admitted to the Singapore Bar in 1998, she possesses over 25 years of experience in dispute resolution. Viviene's core practice areas include contentious Family Law, Employment Law, and Personal Injury & Negligence Claims, as well as Wills & Probate. Beyond litigation, she is a distinguished Principal Mediator at the Singapore Mediation Centre and an Accredited Mediator (Level 4) with the Singapore International Mediation Institute (SIMI). Viviene Sandhu is committed to providing every client with clear, strategic, and compassionate legal counsel to navigate complex legal processes. -
How to see changes in django admin base.css
I want to change some css in static/admin/css/base.css After some attempts I now fail to understand the static-file concept at all. As a matter of fact I can delete the whole static directory without any effect/error (browser CTRL + F5). # settings.py STATIC_URL = "static/" STATIC_ROOT = BASE_DIR.joinpath('static') # urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Long story short; How to change base.css? -
Is it a bad idea to use the builder pattern to construct elasticsearch queries in Python/Django?
So here's the issue. I am maintaining a somewhat large Django app and am tasked with creating a search bar that relies on elastic search data and need to in the near future convert a large number of Django DB queries into Elastic queries. I'm using python's elasticsearch.dsl package version 8.19.2 for this. Assuming the app uses Articles as a model that needs to be represented as Elastic document. Here is my implementation of the builder pattern from elasticsearch.dsl import Document, Text, Keyword class ArticleDocument(Document): id = Integer() title = Text( fields={ 'keyword': Keyword() } ) class Index: name = INDEX_VAR from app import handle_elastic_connection @dataclass class ElasticSearchResults: count: int results: object class ArticleRepository: def __init__(self, client: Elasticsearch): self.client = client def return_results(self, search: Search): return ElasticSearchResults(results=search.execute(), count=search.count()) class ArticleQueryBuilder: def __init__( self ): # handles index refer self.search: Search = ArticleDocument.search() def builder_method1(self, list_of_values:List): if list_of_values: self.search = self.search(Q('terms', key=list_of_values)) def builder_method2(self, single_value:str): if single_value: method2_filter = Q('term', value1=single_value) | Q('term', value2=single_value) self.search = self.search(method2_filter) # .... more builder methods def build(): return self.search # Usage, most likely in view ec = handle_elastic_connection() repo = ArticleRepository(ec) artcile_search = ArticleQueryBuilder.builder_method1().builder_method2.build() results: ElasticSearchResults = repo.return_results(artcile_search) I know the builder pattern gets … -
Django / Serializer - How to pass label attached to choice field in API?
I am trying to get the label attached to the relevant interger for the choice field. Although the API returns the interger, I cannot seem to be able to return the actual label value. This is the current return: [ { "id": 16, "frequency": 0, }, { "id": 15, "frequency": 2, } ] What am I missing? models FREQUENCIES=( (0,'Monthly'), (1,'Weekly'), (2,'Daily'), (3, 'Bi-Weekly'), ) class Model(models.Model): frequency = models.IntegerField(choices=FREQUENCIES, default=0,null=True, blank=True) serializer class ModelSerializer(serializers.ModelSerializer): frequency_label = serializers.ChoiceField( choices=FREQUENCIES, source='frequency', read_only=True ) class Meta: model = Model fields = [ 'frequency', 'frequency_label', ] viewset class ModelViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] @swagger_auto_schema( method='get', responses={200: ModelSerializer(many=True)} ) @action(detail=False, methods=['get'], url_path='list-rules') def a(self, request): q = Model.objects.filter(field=some_variable) return Response( ModelSerializer(q, many=True).data, status=status.HTTP_200_OK ) -
optimization django admin panel queries with select_related and prefetch_related
These are my django models (only the FK s are written) class SellerBuyable(TimeStampMixin, GBSoftDeleteModel): seller = models.ForeignKey(Seller,related_name="seller_buyables",on_delete=models.CASCADE, null=True) buyable = models.ForeignKey(Buyable,on_delete=models.CASCADE,null=True,related_name="seller_buyables",related_query_name='seller_buyable') ... class CampaignItem(TimeStampMixin, GBSoftDeleteModel): campaign = models.ForeignKey(Campaign, related_name='items', on_delete=models.CASCADE) item = models.ForeignKey(SellerBuyable, on_delete=models.CASCADE, null=False) ... class Campaign(TimeStampMixin, GBSoftDeleteModel): name = models.CharField() ... (has no FK) And these are my codes in admin panel: class CampaignItemStackedInline(SortableStackedInline): model = CampaignItem extra = 0 .... @admin.register(Campaign) class CampaignAdmin(SortableAdminMixin, admin.ModelAdmin): inlines = [CampaignItemStackedInline] ... A sample campaign had 11 items. When I open it's page, silk showed 84 queries. I have simplified them to 40 queries by writing CampaignItemStackedInline like this: class CampaignItemStackedInline(SortableStackedInline): model = CampaignItem extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related("campaign", "item__seller", "item__buyable") return qs But I still have 3 queries for each "campaign inline item". 1 for Seller table, 1 for buyable and 1 for seller_buyable. I've tried prefetch_related in CampaignAdmin. The last version is this: @admin.register(Campaign) class CampaignAdmin(SortableAdminMixin, admin.ModelAdmin): ... def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.prefetch_related( Prefetch("items", queryset=CampaignItem.objects.select_related("item__seller", "item__buyable")) ) return qs But it only adds 1 prefetch query and turns into 41 queries Hope to send enough info. -
How to mock django timezone.now in a abstract model
I'm unable to mock timezone.now in the model's created field. The test fails due unmocked/current datetime. I tried patch('django.utils.timezone.now') to no avail. # app/models.py from django.utils import timezone class BaseModel(models.Model): created = models.DateTimeField(default=timezone.now, editable=False) class Meta: abstract = True class MyModel(BaseModel): ... # app/tests/test.py from app.models import MyModel from datetime import dateHow to mock django timezone.now in a abstract modeltime from django.utils import timezone def test_(self): dt=datetime(2018, 1, 24, tzinfo=timezone.utc) with patch('app.models.timezone.now', return_value=dt): instance = MyModel.objects.create() assert instance.created == dt -
Using group_by to find sum in Django
I'm working on a website to track music practice and I'm trying to set up a query to show how many minutes you've spent with a certain instrument or song. I modeled this behavior using Khan Academy (to test the SQL): https://www.khanacademy.org/computer-programming/music-tracker/5599297716994048 but can't find a way to do it in Django. The SQL query would look something like this: SELECT song, SUM(duration) AS total_time_practiced FROM logs GROUP BY song ORDER BY total_time_practiced DESC How does this translate to Django? I've tried a few things and the most promising is: Log.objects.distinct().annotate(total_practice_time=Sum("duration")) but it still doesn't work. I've checked the docs and Django doesn't seem to have a GROUP BY method for QuerySets. Any advice? This is from one database, by the way, not using any joins. (apologies for the lack of syntax highlighting on the code snippets; every time I tried to add rich formatting, the webpage crashed) -
Storing WAV recording to disk plays as static
I'm recording voice via jquery then sending it to django view: views.py ... elif voice_value: #get voice voice_value = request.FILES.get('sound_file.wav') #read as bytes file_content_bytes = voice_value.read() #using pydub audio_bytes = file_content_bytes # Replace with your actual audio data audio_segment = AudioSegment( data=audio_bytes, sample_width=2, # Example: 2 bytes per sample (16-bit audio) frame_rate=48000, # Example: 44.1 kHz sample rate channels=1 # Example: Mono audio ) audio_segment.export("output_1.wav", format="wav") data = {'payload':'anything'} return JsonResponse(data,safe=False) It produces the output as a wav file, but it's distorted and just static when played. I should say that the parameters (channels,sample_width,framerate) are the default. What seems to be the problem ? -
Could not translate host name to address
When I run python manage.py migrate I get this error: (venv) mac@MACs-MBP-2 backend % python manage.py migrate Traceback (most recent call last): File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 332, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "db.jpjvgnlyxkkhgihmneys.supabase.co" to address: nodename nor servname provided, or not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/mac/Documents/projects/community_app/backend/manage.py", line 22, in <module> main() File "/Users/mac/Documents/projects/community_app/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 416, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File … -
How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site?
How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site? I experiencing 503 errors on our production server due to a high volume of requests to the /admin/jsi18n endpoint when multiple members use the Django admin simultaneously. -
Django Allauth Google OAuth: MultipleObjectsReturned even though no duplicates in MySQL
I’m using Django + MySQL with django-allauth and Google OAuth. Login fails with this error: MultipleObjectsReturned: get() returned more than one SocialAccount The confusing part is that the database does not contain duplicates. Here is what I checked: 1. No duplicate Google accounts SQL: SELECT uid, COUNT(*) FROM socialaccount_socialaccount GROUP BY uid HAVING COUNT(*) > 1; → returns 0 rows. 2. No duplicate users by email Python: User.objects.values("email") .annotate(count=Count("id")) .filter(count__gt=1) → also empty. 3. My relevant allauth settings: SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" 4. Only one Google OAuth app and only using localhost in callback. Credentials are correct. 5. Even after deleting all rows from auth_user and socialaccount tables, the next login still throws the same error. 6. There is really only one row in socialaccount_socialaccount, but allauth still raises MultipleObjectsReturned during login. My question: What else in django-allauth or the authentication pipeline can cause a MultipleObjectsReturned error even when the database does not contain duplicates? Is there something like: a temporary duplicate created during login? signals or adapters running twice? duplicate queries on email lookup? a caching issue? Any debugging tips would help. -
How do I preview a Pdf fike via a presigned S3 URL in React?
I have an api which is responsible for download the file of any mime type if its available in the s3 bucket now in the response it draws a presigned url, hmacsignature, urlbucket name, etc. Now I want to use that presigned url to create an react preview popup to display the pdf without downloading it. My backend code is in Golang. -
How to combine Django server-side rendering with a dynamic JavaScript frontend?
I’ve been working with Django for a while and I’m trying to find an approach that provides fast server-side rendering while still allowing highly interactive, JavaScript-driven behavior on the client side. What are the recommended best practices for combining Django’s server-rendered templates with a modern JavaScript frontend? I currently use Django Ninja as an API layer with a separate JS frontend, but I’m wondering if there’s an established pattern for integrating both approaches effectively. For example, the server could deliver an up-to-date, cached HTML page immediately via Django’s template rendering, and then JavaScript would take over to update or enhance the dynamic parts of the page, but the page should be displayed immediately. -
When are user permissions ready? - trying to assign permission in post-migration signal
Fairly new to django so there must be a lot I have no idea about. How can I assign user related permissions to user groups in a post migration signal? I have read everywhere that post migration signal can work which actually does... to an extent. I can create the required user groups and assign permissions to them but the ones related to user model. E.g. view_user, create_user, change_user are not ready to be assigned in post migration. Im not sure of all the options I have here but already tried to define a migration file and nitpicking sender does not look like a way forward either. Signal handler: @receiver(post_migrate) def create_groups_and_assign_permissions(sender, **kwargs): print(f"sender: {sender}") # Only run after auth migrations if sender.label != "auth": return for (code_name, name), permission_codenames in GROUPS_AND_PERMISSIONS.items(): group, _ = Group.objects.get_or_create(name=name) GroupMetadata.objects.get_or_create( group=group, code_name=code_name, display_name=name ) for codename in permission_codenames: try: perm = Permission.objects.get(codename=codename) group.permissions.add(perm) except Permission.DoesNotExist: print(f"[WARNING] Permission '{codename}' does not exist yet") Singal is imported in the AppConfig: from django.apps import AppConfig class UserGroupsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "apps.users.features.user_groups" def ready(self): # Register signals import apps.users.features.user_groups.signals # pylint: disable=unused-import, import-outside-toplevel GROUPS_AND_PERMISSIONS constants: GROUPS_AND_PERMISSIONS = { ("manager", "Manager"): [ ... "add_profile", "change_profile", "view_profile", … -
"You cannot access body after reading from request's data stream"
I have a piece of code that sends a json to the server but form.onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(form); const response = await fetch('api/get-comments/', { method: 'POST', body: formData }); if (response.ok) { await fetchComments(); document.getElementById('commentText').value = ''; } } when I try to read it it comes back with an error that it can't access the body def get_comments(request, gameID: int): """Renders the comment page.""" assert isinstance(request, HttpRequest) if request.method == "POST": comment_text = json.get(request.body) user = request.user # comment = Comments( # userID=user, # gameID = Games.objects.get(gameID=gameID), # commentText=comment_text, # commentTime=datetime.now() # ).save() return HttpResponse(comment_text ,status=201) -
Why does using Python’s print() function cause a rendering error in Django, and what should be passed to render() instead?
Problem Code Snippet (Python: Django)- def home(request): data = {"msg": "Hello"} result = print(data) # Problematic line return render(request, "index.html", result) # why render? Is there any other way?