Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How can I resolve errors encountered during migration from SQLite to MySQL in Django?
(venv) PS E:\Easyalgo project\django-tailwind-blog> python manage.py migrate System check identified some issues: WARNINGS: ?: (ckeditor.W001) django-ckeditor bundles CKEditor 4.22.1 which isn't supported anmyore and which does have unfixed security issues, see for example https://ckeditor.com/cke4/release/CKEditor-4.24.0-LTS . You should consider strongly switching to a different editor (maybe CKEditor 5 respectively django-ckeditor-5 after checking whether the CKEditor 5 license terms work for you) or switch to the non-free CKEditor 4 LTS package. See https://ckeditor.com/ckeditor-4-support/ for more on this. (Note! This notice has been added by the django-ckeditor developers and we are not affiliated with CKSource and were not involved in the licensing change, so please refrain from complaining to us. Thanks.) ?: (urls.W002) Your URL pattern '/post' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. Operations to perform: Apply all migrations: Adv_css, DBMS, admin, auth, blogs, contenttypes, cp_sheet, cs_subject, home, htmlapp, mini_sheet, networking, patterns, prepration_sheet, programming, sessions, stl Running migrations: Applying home.0003_blog_remark...Traceback (most recent call last): File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\MySQLdb\cursors.py", … -
how to upload and execute a file in django then show the result?
I want to build a web application using Django These are the flow I'm planning to execute: Page1 - User upload file to be executed using the upload button and then press execute button. Page2 - execute the Python code and show the result. i have tried the upload part but i still need help in the execution and the show of the result . -
Django Allauth Bad Request Error, Error Retrieving Access Token: Invalid Grant
I am using Django Allauth from PyPi in a Django project to authenticate users so they can upload YouTube videos. The way I do this is with a button on the login page that should collect tokens from Google to upload the videos. I am able to send the user to Google for authentication, but I get an error in the Allauth view when the user is returned to the website. {'provider': 'google', 'code': 'unknown', 'exception': OAuth2Error('Error retrieving access token: b\'{\\n "error": "invalid_grant",\\n "error_description": "Bad Request"\\n}\'')} Any idea how to fix this? I have used django-allauth before without any trouble. For reference, the full source code I am using to produce this error is on my github at https://github.com/daisycamber/femmebabe-2024. Thank you for your help. -
How to query child models from parent model data?
I currently have a set of models like so: class BaseModel(models.Model): approved = models.BooleanField() class ModelA(BaseModel): # model fields class ModelB(BaseModel): # models fields class ModelC(BaseModel): # model fields What I'd like to do is get a list of all instances of ModelA, ModelB, and ModelC with approved=True. I can query BaseModel with a queryset: BaseModel.objects.filter(approved=True) but this returns all instances of BaseModel, not ModelA, ModelB, or ModelC. I'd like my queryset to contain instances of each model -- preferably without exhaustively querying every single possible child model of BaseModel. Is there a way to do this? -
[[Errno 2]] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in my Django project
I've been moving development of my website over to using Docker. I recently adjusted the location of media files when I was presented with this error: [Errno 2] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django. So far I've checked for typos in my file location code in my settings, views and models. The website works by simply storing user uploaded media files in a media folder. Uploaded files are stored in media/human. Here is the relevant code: views.py: ... fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file_type = mimetypes.guess_type(uploaded_file_path) request.session['uploaded_file_path'] = uploaded_file_path user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) files = request.FILES.getlist('file') for file in files: user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) uploaded_file = UploadedFile(input_file=file, requirements_chat=user_doc, chat_id = user_id) uploaded_file.save() user_doc.save() ... The error seems to be caused by the uploaded_file.save() line. models.py: class RequirementsChat(models.Model): id = models.CharField(primary_key=True, max_length=40) alias = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) language = models.CharField(max_length=10, blank=True, null=True) due_date = models.CharField(max_length=10, blank=True, null=True) subtitle_type = models.CharField(max_length=10, blank=True, null=True) transcript_file_type = models.CharField(max_length=10, blank=True, null=True) additional_requirements = models.TextField(max_length=500, blank=True, null=True) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) url = models.CharField(max_length=250, blank=True, null=True) task_completed = models.BooleanField(default=False) class UploadedFile(models.Model): input_file = models.FileField(upload_to='human_upload/')#new chat_id = models.CharField(max_length=40, null= True) requirements_chat = models.ForeignKey(RequirementsChat, on_delete=models.CASCADE, …