Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Sending parts of react components from django server to be rendered in a react client server
I have a unique problem statement. I have a client side react server running on port 3000 and a django server of port 8000. Both the servers communicate through rest framework. But I have a situation where I cannot keep the UI code of react in the react frontend so I should send the react(html) code from the django backend(security reasons) so that I could only load that secure UI react component when I receive the html(react compiled) code from the django server(backend). I think we can use some way to compile the react code from an additional node.js server into html code and keep it in django server. When user with right permissions try to access that component only then the server send the react UI code to the frontend to temporarily display that component in the frontend. Can I know how this can be achieved if it cam be achieved. Feel free to ask any additional questions you have regarding the problem statement in the comments. -
How to create model instances from html form and save to AuraDb?
Most of the online tutorials and videos describe how to create and save model instances to the local database using Django. I found this medium article https://medium.com/swlh/create-rest-api-with-django-and-neo4j-database-using-django-nemodel-1290da717df9 explaining how to upload it to Neo4j. I tried to run the same project and this is what I got when I went to http://127.0.0.1:8000/person (see snapshot below). The "Person" object is a StructuredNode, defined as follows in models/person.py: from neomodel import StructuredNode, StringProperty, IntegerProperty,UniqueIdProperty, RelationshipTo from myapi.models.city import City class Person(StructuredNode): uid = UniqueIdProperty() name = StringProperty(unique_index=False) age = IntegerProperty(index=True, default=0) email = StringProperty(unique_index=True) # Relations : city = RelationshipTo(City, 'LIVES_IN') friends = RelationshipTo('Person','FRIEND') def __unicode__(self): return self.uid I want to get the details from a user through a form and save it as an instance of the Person object in my AuraDB: person.save() So in `views/forms.py' I created a form as such: from django import forms from splitjson.widgets import SplitJSONWidget from myapi.models import Person class testForm(forms.Form): attrs = {'class': 'special', 'size': '40'} data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True)) class Meta: model = Person and I added it as a path to the urls.py: from django.urls import re_path as url from myapi.views import * from django.urls import path urlpatterns = [ path('', home, name='home'), … -
JS script is not included in Django project
I'm learning django and have a problem. JS script is not included in Django project. The path is correct, the page itself with the graph block works, but the output of a round or bar chart does not occur. index.html {% extends 'partials/base.html' %} {% block title %}Home Page{% endblock %} {% block content %} <div class="row "> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart1" width="400" height="300"></canvas> <script src="{% static 'main.js' %}"></script> </div> </div> </div> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart" width="400" height="300"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for order in order %} '{{order.name}}',{% endfor %}], datasets: [{ label: 'Orders', data: [{% for order in order %} {{ order.order_quantity }}, {% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] … -
Django doesn't override base admin template
I'm trying to add small customizations to my Django admin panel such as a favicon. I followed the official guide and have created a base_site.htmlfile in app/templates/admin/. base_site.html {% extends "admin/base_site.html" %} {% load static %} {% block branding %} <img src="{% static 'portal/img/favicon.png' %}" alt="Favicon"> {{ block.super }} {% endblock %} It seems like the template isn't being overridden at all as I don't see an error for not being able to find the favicon / incorrect src (works fine on other pages). urls.py from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.sitemaps.views import sitemap from bmlabs.sitemaps import StaticViewSitemap from .views import robots sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls, name="admin"), ] urlpatterns += staticfiles_urlpatterns() -
Can i run 2 django projects on 2 domains but on 1 ip?
I'm trying to run two django projects using nginx using these two configurations: upstream django { server unix:///home/hypebeeruser/HypeBeer/HypeBeerProject/HypeBeerProject.sock; } # configuration of the server server { server_name hypebeer.com.ua; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/media; } location /static { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/hypebeeruser/HypeBeer/HypeBeerProject/uwsgi_params; } } # the upstream component nginx needs to connect to upstream django_tobabox { server unix:///home/tobabox/TobaBox/TobaBox/TobaBox.sock; } # configuration of the server server { listen 80; server_name tobabox.com www.tobabox.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/tobabox/TobaBox/TobaBox/media; } location /static { alias /home/tobabox/TobaBox/TobaBox/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django_tobabox; include /home/tobabox/TobaBox/TobaBox/uwsgi_params; } } I run uwsgi --socket HypeBeerProject.sock --module HypeBeerProject.wsgi --chmod-socket=666 and it runs my first site, but the second doesn't work with the same comand (yes, i changed the names of .sock and project.wsgi). It runs normally without any errors, but i still can't connect via domain name. Do I need to buy an additional IP or can I …