Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django as API gateway & authorizations service in Microservice
I wanted to create a Microservice that will use Django as its API Gateway for the GraphQL. This is the desired output of my service architecture. Can some one please explain to me how to reach to this end, or provide a meaningful resources to create a microservice with Django. -
React and Django connection with channel setup - WebSocket connection failed
I'ved tried to setup Django with channels to provide notification to React. https://github.com/axilaris/react-django-channels <-- I have put my project code here. in backend/backend/settings.py INSTALLED_APPS = [ .. 'channels', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } ASGI_APPLICATION = 'backend.routing.application' in backend/backend/asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter #import backend.routing import user_api.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( user_api.routing.websocket_urlpatterns #backend.routing.websocket_urlpatterns <-- not sure if should be this ), }) in backend/user_api/routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from . import consumers application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/notifications/", consumers.NotificationConsumer.as_asgi()), ]), }) in backend/user_api/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): print "XXX connect" await self.accept() async def disconnect(self, close_code): print "XXX disconnect" pass async def receive(self, text_data): print "XXX receive" text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({ 'message': message })) Finally in Reach, App.js useEffect(() => { const ws = new WebSocket('ws://localhost:8000/ws/notification/'); ws.onopen = () => { console.log('Connected to notification websocket'); }; ws.onmessage = e => { const data = JSON.parse(e.data); setMessage(data.message); }; ws.onerror = e => { console.error('WebSocket error', e); }; ws.onclose = e => { console.error('WebSocket closed', e); }; return () => … -
Auto Pagination issues in Django, how to fix?
Auto Pagination issues in Django, how to fix? How to resolve duplication with automatic pagination? There's a template home.html and home_list.html; In home_list.html, JSON format is successfully passed, but Ajax misbehaves and creates a bunch of duplicate posts during automatic pagination; how to fix? home.html: <script> $(document).ready(function(){ var nextPageUrl = '/load-posts/'; // Using URL for loading posts function loadMorePosts() { // Display loading element //$('#loading').text('Loading...'); // Perform a GET request to the server $.get(nextPageUrl, function(data) { // Hide loading element //$('#loading').text('Load more'); // Append HTML with posts to the end of the container $('#post_contenter').append(data.posts_html); // Update URL for the next page nextPageUrl = data.next_page_url; }).fail(function() { // Handle request error if it occurs console.error('Error loading posts'); // Hide loading element $('#loading').hide(); }); } // Event handler for page scroll $(window).scroll(function() { if($(window).scrollTop() + $(window).height() >= $(document).height()) { // Call the function to load additional posts loadMorePosts(); } }); // Initialize loading of the first page of posts when the page is loaded loadMorePosts(); }); </script> views.py: from django.shortcuts import render, redirect from usercreatepost.forms import PostForm from publication.models import Userpublication from user.models import Profile****, Subscription from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.urls import reverse from django.http … -
How to Prioritize Celery Tasks When Processing Large Numbers of Files to Prevent Long User Wait Times?
I am working on a Django application where users can upload files to be processed by Celery tasks. Each file upload triggers a Celery task that processes the file individually. The problem arises when a user uploads a large batch of files (e.g., 10,000 files), as it causes subsequent users' uploads (e.g., 100 files) to wait until the first user's batch has completely processed. This results in significant delays and a poor user experience for those uploading smaller batches of files. Tasks are segregated into user-specific queues. Each queue is named following the pattern user-{user_id} (e.g., user-1, user-2, ..., user-10). My objective is to achieve a round-robin processing strategy across these queues: after processing a task from user-1's queue, the worker should move on to process a task from user-2's queue, and so on, cycling through the queues in a round-robin fashion until all tasks are processed. Stuck on: I have not been able to configure Celery to listen to queues using a pattern (e.g., user-.*). The queue list for the Celery worker must be predefined and cannot dynamically adjust to match new user-specific queues as they are created. Question: Is there a way to configure Celery workers to process … -
Django migrations not creating tables on PostgreSQL despite successful execution
Description: I'm encountering an issue with Django migrations on a PostgreSQL database. Despite running python manage.py migrate successfully without any errors, the tables are not being created in the database. Details: Environment: Django version: Django 4.2 PostgreSQL version: PostgreSQL 15.6 Operating System: Ubuntu server 22.04.4 Issue Description: When I run python manage.py migrate, it executes successfully without any errors. However, upon checking the database, no tables are created in the specified schema. Steps I've Taken: Checked the permissions for the database user used by Django. It has all privileges, including the ability to create tables. Verified the configuration in settings.py to ensure the database settings are correct. Looked for error messages in both the Django logs and PostgreSQL logs, but found no relevant errors. Specifically created a new PostgreSQL database and user, intentionally not granting any permissions. Troubleshooting Attempted: Checked the database user permissions. Examined Django and PostgreSQL logs for errors. Ensured that migrations are applied in the correct order and do not contain errors. Expected Outcome: After running python manage.py migrate, I expect the tables specified in the migrations to be created in the PostgreSQL database. Additional Context: This issue occurs specifically on the production server. On my local … -
class Media in Django formsets
I have a form named SpecificDateForm. Additionally, I have a formset named SpecificDateFormset, which is created using Django's inlineformset_factory. This formset uses HiddenDeleteInputFormset, a custom formset that, as the name suggests, hides the delete checkbox. from django import forms class SpecificDateForm(forms.ModelForm): class Meta: model = SpecificDate fields = ['date',] labels = { 'date': 'Datum', } widgets = { 'date': DatePickerInput(), } help_texts = { 'date': 'fix vordefinierter Termin', } class HiddenDeleteInputFormSet(forms.BaseInlineFormSet): def add_fields(self, form, index): super().add_fields(form, index) if 'DELETE' in form.fields: form.fields['DELETE'].widget = forms.HiddenInput() SpecificDateFormset = forms.inlineformset_factory( Directive, SpecificDate, form=SpecificDateForm, formset=HiddenDeleteInputFormSet, extra=1, can_delete=True, localized_fields=['date'] ) I recently learned that with class Media I can inject a custom javascript that loads with the form. Does this work with formsets? I can't get it to work. I tried class Media at various locations in the code, but my custom javascript never shows up in the {{ my_formset.media }} tag. So my question is: Where do I define class Media? Or is it simply impossible with formsets? -
Are there any ways to add Bootstrap Carousel in CKEditor (django-ckeditor)
I want to make feature for admin in my django site to add bootstrap carousels (or just carousels) to show images in CKEditor RichTextUploadingField field on my model instanses. What is the better way to implement that thing? Maybe there are ready-made solutions? I heard about bootstrapCarousel plugin, but maybe it is deprecated, although it supports Bootstrap 4. -
Is there any efficient algorithm for updating ordered data in DRF?
I had a problem with algorithm which updates ordered data. For example, I have one model called Route. class Route(models.Model): order = models.IntegerField(null=False, blank=False) memo = models.CharField(max_length=400, null=True, blank=True) I have Route ordered data such as... (doesn't fit in the grammar) (id:1, order:1, memo:"aaa")->(id:2, order:2, memo:"bbb")->(id:3, order:3, memo:"ccc") And user can change, delete, add to the order in one endpoint, such as... (order:3)->(order:1)->(order:2) # change order (order:1)->(order:3) # delete elements (order:2) (order:1)->(order:2)->(order:3)->(order:4) # add elements At first, I thought that I can remove all these existing data and recreate incoming data. (I know it's really inefficient, but I decided to do this.) But I have problem with preserving memo data among the data that have not been added or deleted. What should I do? -
In DRF, How to inject full `ErrorDetail` in the response, using a custom exception handler?
I'm using a pretty complex custom handler in DRF. For example, for a given response, response.data could look like to: {'global_error': None, 'non_field_errors': [], 'field_errors': {'important_field': [ErrorDetail(string='Ce champ est obligatoire.', code='required')]}} However, when getting the actual response from the API, the ErrorDetail will be transformed in a simple string, losing the code information. Is there a simple way to ensure ErrorDetail is always written in a response as {"message": "...", "code": "..."} without transforming the response manually in the custom handler? I know there exists the DRF get_full_details() method that returns exactly this on an exception. But I'm the response level. -
Docker nginx ELB(load balancer) 499 error
I am facing a issue and cannot solve it even though I looked for some other questions related to nginx 499 error. I am using Django for my project, and the problem is from the social login (kakao login) error. my accounts/views.py looks like this: BASE_DIR = Path(__file__).resolve().parent.parent env_file = BASE_DIR / ".env" if os.getenv("DJANGO_ENV") == "production": env_file = BASE_DIR / ".env.prod" env = environ.Env() env.read_env(env_file) BASE_URL = env("BASE_URL") KAKAO_CALLBACK_URI = BASE_URL + "accounts/kakao/callback/" REST_API_KEY = env("KAKAO_REST_API_KEY") CLIENT_SECRET = env("KAKAO_CLIENT_SECRET_KEY") @extend_schema( summary="카카오 로그인", description="카카오 로그인 페이지로 리다이렉트합니다.", responses={ 302: OpenApiResponse( description="Redirects to the Kakao login page.", response=None ) }, ) @api_view(["GET"]) @permission_classes([AllowAny]) def kakao_login(request): return redirect( f"https://kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={KAKAO_CALLBACK_URI}&response_type=code" ) # @extend_schema(exclude=True) # @permission_classes([AllowAny]) # def finish_login(data): # accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data) # return accept @extend_schema(exclude=True) @permission_classes([AllowAny]) def kakao_callback(request): code = request.GET.get("code") print(f"code: {code}") # Access Token Request token_req = requests.get( f"https://kauth.kakao.com/oauth/token?grant_type=authorization_code&client_id={REST_API_KEY}&client_secret={CLIENT_SECRET}&redirect_uri={KAKAO_CALLBACK_URI}&code={code}" ) print(f"token_req: {token_req}") token_req_json = token_req.json() print(f"token_req_json: {token_req_json}") error = token_req_json.get("error") if error is not None: raise JSONDecodeError(error) access_token = token_req_json.get("access_token") print(f"access_token: {access_token}") # Email Request profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}, ) profile_data = profile_request.json() print(f"profile_data: {profile_data}") kakao_oid = profile_data.get("id") kakao_account = profile_data.get("kakao_account") username = kakao_account["profile"]["nickname"] profile_image_url = kakao_account["profile"]["profile_image_url"] email = kakao_account.get("email") # 회원가입, 로그인 로직 data = … -
RichTextField django + html
Has anyone had experience working with RichTextField? When I add an entry in the admin panel, the code there is highlighted and its background is gray, but when output to the html template there is no design. Here are my settings: CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline', 'Strike'], ['NumberedList', 'BulletedList'], ['Link', 'Unlink'],enter image description here ['Image', 'CodeSnippet'], ], 'extraPlugins': 'codesnippet', 'width': '550px', }, } enter image description here I didn't add any plugins except ckeditor itself -
Invalid base URL provided: http://127.0.0.1:8888/ [closed]
I suddenly started seeing this error when running server Invalid base URL provided: http://127.0.0.1:8888/ -
Deploy my Django project in my private network
I have created my django project and now I need to deploy the project in my network (DNC IP address) the IP address for example 10.xxx.005.xxx the main point is to let all the employees can access with the same IP and the IP address not connected to the internet it is only local network The way how to deploy my privet local network and make it accessible how is in the same network -
Combine django tests and testcafe?
I'm experminenting testing of frontend with testcafe https://testcafe.io/documentation/402631/guides/overview/why-testcafe and backend with django https://docs.djangoproject.com/en/5.0/topics/testing/overview/#running-tests If I start two separate shell: python ./manage.py test #backend testcafe chromium ./tests/testcafe.js #frontend The backend test run faster than the frontend. I'd like to use the django test feature that create an empty database for each execution. And django tests for backend, is there a way to make a combo of those? -
launching the Django project
I can't launch the Django project. I do everything as in the manual, but it does not start.enter image description here I can't launch the Django project. I do everything as in the manual, but it does not start.What am I doing wrong? -
Django. Correct way to get and pass complicated data to template
My problem is i need to display data from Report and Plan models to this table in the template enter image description here It's a calendar which displays data from Reports and Plans to correct cell by their .date (rows) and .machine (columns). The way i do it... sucks. Load times is insane because of amount of queries by daterange in get_shifts_tables() and code is unreadeble. But i can't come up with an alternative. Here it is. views.py @login_required(login_url="login_user") @allowed_user_roles(["ADMIN", "MODERATOR"]) def stats(request): leftovers = get_leftovers() orders = Order.objects.all().order_by("-id") order_entries_leftovers = {} for order_entry in OrderEntry.objects.all(): order_entries_leftovers[order_entry.id] = order_entry.quantity for report_entry in ReportEntry.objects.filter(report__order=order_entry.order): order_entries_leftovers[order_entry.id] -= report_entry.quantity current_date = Table.objects.all()[0].current_date today = now() today = today - datetime.timedelta(days=6) today = today.replace(hour=current_date.hour % 12, minute=current_date.minute, second=current_date.second, microsecond=current_date.microsecond) Table.objects.all().update(current_date=today) active_step_pk, machines, table = get_shifts_table() context = { "orders": orders, "leftovers": leftovers, "order_entries_leftovers": order_entries_leftovers, "steps": Step.objects.all(), "active_step_pk": active_step_pk, "machines": machines, "table": table } return render(request, "core/stats.html", context) get_shifts_table() - from scripts.py def get_shifts_table( shifts_count=28): from_date = Table.objects.all()[0].current_date step = Table.objects.all()[0].current_step table = [] timestamps = [ from_date + datetime.timedelta( hours=12 * i) for i in range(0, shifts_count)] machines = Machine.objects.filter(step=step) for i in range(len(timestamps) - 1): row_report_entries = ReportEntry.objects.filter( report__date__range=(timestamps[i], timestamps[i + 1]), report__step=step) … -
Django formatter that can convert double quotes to single quotes [closed]
I need to convert double quotes to single quotes and Black can't do it, so are there other ways to do it? I tried unify, witch works but only one file at a time and flake8 rich gives me this error: There has been a critical error: There was a critical error during execution of Flake8: plugin code for flake8-single-quotes[flake8_single_quotes] does not match ^[A-Z]{1,3}[0-9]{0,3}$ -
Serving media content with Django and Nginx
A am creating DRF application, that is hosted on a remote server. I have PostgreSQL and Django Rest Framework running inside Docker containers, and Nginx directly on the host. Now, it works successfully when I make request to https://example.com/path/to/file - I get image served by Nginx correctly. But my problem is that when Django returns me a JSON object with data, the image_url field (Django's ImageField - path to file) is equal to http://localhost:6500/path/to/file This 6500 port and localhost are generated by Docker. Instead, I supposed it to return this: https://example.com/path/to/file. Here is my Nginx file: server { server_name api.example.com www.api.example.com; access_log /var/log/nginx/api.example.com-access.log; error_log /var/log/nginx/api.example.com-error.log; location /media/ { alias /opt/site_backend_docker/Site_Backend/apps/media/; } location / { client_max_body_size 0; gzip off; ## https://github.com/gitlabhq/gitlabhq/issues/694 ## Some requests take more than 30 seconds. proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name api.example.com www.api.example.com; listen 80; return 404; # managed by Certbot } And my … -
Django Channels on IIS
I have a Django app deployed on IIS with FastCGI. Now, I have installed Django Channels in it and also Daphne to run WebSockets. Everything is working fine locally, but now I am struggling to understand how to handle Django Channels on IIS. Any ideas? I have IIS instaled in Window Server 2019 and I implement Redis Layer in sockets how to handle this? -
How to setup VScode debugger in cookiecutter django template?
File: docker-compose.debug.yml version: '3.4' services: vscodedjangodocker: image: vscodedjangodocker build: context: . dockerfile: ./Dockerfile command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 manage.py runserver 0.0.0.0:8000 --nothreading --noreload"] ports: - 8000:8000 - 5678:5678 FIle name: lunch.json { "configurations": [ { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/app" } ], "projectType": "django" } } ] } File name: tasks.json { "configurations": [ { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/app" } ], "projectType": "django" } } ] } i did implement it in normal django docker project vscode-django-docker-debugging it work just fine but cant seem to implement into the cookecutter django template. when i try to implement it into the cookecutter Django template im getting .env error. Did anyone implement VScode docker debugger in cookecutter django. please do share. I want to implement cookecutter docker debugger vscode. -
How to compare two integer fields in a model method in django?
I want to compare two integer fields inside a method in a django model. The two fields are not correctly getting compared and it is throwing an error for example: total_slots = models.IntegerField(default=0, help_text="Total number of vehicle slots available for allocation.") allocated_slots = models.IntegerField(default=0, validators=[ MaxValueValidator(total_slots), MinValueValidator(0) ], ) def available_slots_left(self): if self.allocated_slots < self.total_slots: return True return False I tried to just simply do this: def available_slots_left(self): if self.allocated_slots < self.total_slots: return True return False but it didn't work and it returned this error: TypeError: '<=' not supported between instances of 'IntegerField' and 'int' -
How to integrate VVVVEBJS with a Django project
I have an existing Django project, and I want to integrate the VVVVEBJS library (https://github.com/towfiqi/VVVVEBJS) to provide a drag-and-drop website builder functionality. VVVVEBJS is a JavaScript library, and I'm not sure about the best approach to integrate it with my Django project. Here are the steps I've taken so far: However, I'm unsure about how to properly initialize and use the VVVVEBJS library within my Django views and templates. I'm also not sure about the best way to handle user-generated content from VVVVEBJS and save it to the database. Can someone please guide me through the steps required to integrate VVVVEBJS with my Django project? I'd appreciate any tips, examples, or resources that can help me achieve this integration successfully. Thank you in advance for your help -
Django apache environment variables
I have a django project in which environment variables from a .env file work just fine in development mode, I can read them in my settings.py by using SECRET_KEY = os.getenv('SECRET_KEY') but when I confugure the project in the apache httpd.conf and access the django project, the error log complains about the missing values. How can I load those values to the apache server? -
getting failed to setup new system in my device
btw i am using windows :: (system used Django to build) when i try to run this command in my terminal ( pip install -r requirement.txt) it shows this error even i tried to install and update reportlab but still cant note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for reportlab Running setup.py clean for reportlab Failed to build reportlab ERROR: Could not build wheels for reportlab, which is required to install pyproject.toml-based projects -
how to prefetch comments in django
class Comment(models.Model): parent_comment=models.ForeignKey( to='self', related_name='_comments', on_delete=models.DO_NOTHING, null=True, blank=True, how to prefetch _comments: child_comment The deeper the depth, the deeper the N+1 query problem