Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I pass an attribute value inside a StructBlock in Wagtail 4.1?
I am trying to create a StructBlock in Wagtail that contains a ChoiceBlock. The choices for this ChoiceBlock should be generated from an import that takes an id from a previous ModelChooserBlock value. However I am doing something wrong as I am unable to read the value from the ModelChooserBlock to be able to get it's id. Is there a way to get the value.id of the ModelChooserBlock and pass it back to the StructBlock to generate the choices? See my code: class StartListBlock(blocks.StructBlock): """ Display the start list for a specific race """ class Meta: template = 'blocks/startlist_block.html' icon = 'site' label = _('race_startlist') title = blocks.CharBlock( required=False, label=_("title"), ) # model id will be passed to import race choices race_day = ModelChooserBlock( target_model=RaceDay, label=_("race day"), ) race = blocks.ChoiceBlock( required=False, label=_('race'), choices=[], # choices will be generated outside the block ) I tried to create a new ChoiceBlock inside get_context and pass it back to the StructBlock with the new choices, but for the choices to show I needed to refresh the page and the selected race value did not get pass to the context. Please advise if this is not the correct approach and how it might … -
Chartjs data not loading when working with Django templates
I created a base template for my project and then tried to load data for a page that is using this template. The html {% block content %} works just fine but the {% block script %} doesnt seem to load. When each page had its own code this problem didn't occur; but now since I'm trying to inherit from a base template even console.log('test') doesn't seem to work. Base.html <!DOCTYPE html> <html> <body> <main> {% block content %} {% endblock content %} </main> <script> {% block footer_scripts %} {% endblock footer_scripts %} </script> </body> </html> page.html <!DOCTYPE html> <html> <body> <main> {% block content %} <div class="relative p-4 h-72"> <canvas id="doughnutChart"></canvas> </div> {% endblock content %} </main> <script> {% block footer_scripts %} <script> const SubscriptionData=[] {% for i in SubscriptionStatus %} SubscriptionData.push({{ i }}); {% endfor %} const doughnutChart = new Chart(document.getElementById('doughnutChart'), { type: 'doughnut', data: { labels: ['Subscribed','Renew', 'Unsubscribed'], datasets: [ { data: SubscriptionData, backgroundColor: [colors.primary, colors.primaryLighter], hoverBackgroundColor: colors.primaryDark, borderWidth: 0, weight: 0.5, }, ], }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', }, title: { display: false, }, animation: { animateScale: true, animateRotate: true, }, }, }) </script> {% endblock footer_scripts %} </body> </html> -
Django File Upload using a self-made dropzone
I am at the moment trying to build a practice-project where I implement different ways to upload files using django 4.17. Upon creating my dropzone, I receive the following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 4.1.7 Python Version: 3.10.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'upload_files'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in getitem list_ = super().getitem(key) During handling of the above exception ('upload'), another exception occurred: File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kevin/PycharmProjects/uploader/upload_files/views.py", line 16, in upload_file if request.method == 'POST' and request.FILES['upload']: File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in getitem raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /upload/ Exception Value: 'upload' My upload.html looks like this, I for now, extend a base.html: {% block content %} <h1>Upload your files</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=" .txt"> <!-- <div type="file" name="upload" accept=" .txt" id="drop-zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);" style="width:400px;height:300px;background:grey;"></div> --> <button type="submit"> Go</button> </form> <h2> Uploads so far</h2> {% if file_url %} <p> uploaded to <a href="{{ file_url }}"> {{ file_url }}</a></p> {% else %} <ol> {% … -
Rest Framework serializer to create parent and add different child typess
I will want create form app and i have one problem I want add two different type child to parent how can help me That is my model class Answer(models.Model): question_id = models.ForeignKey( "app.Question", on_delete=models.CASCADE, related_name='answers') answer_title = models.CharField(max_length=100, null=True, blank=True) answer_weight = models.DecimalField(max_digits=9, decimal_places=4, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #parent=models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: verbose_name = 'Answer' verbose_name_plural = 'Answers' def __str__(self): return self.answer_title class Question(models.Model): question_title = models.CharField(verbose_name='question', max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) stage=models.ForeignKey('app.Stage', related_name = 'questions', on_delete=models.CASCADE) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return self.question_title That is my serializer class QuestionListSerializer(serializers.ModelSerializer): answers = AnswerListSerializer(many=True, read_only=True) class Meta: model = Question exclude = ['created_at', 'updated_at', 'stage'] class AnswerListSerializer(serializers.ModelSerializer): class Meta: model=models.Answer exclude=["question_id"] That is my apiviews class QuestionListApiView(APIView): def get(self, request): question = Question.objects.prefetch_related('answers') serializer = QuestionListSerializer(question, many = True) return Response({"questions": serializer.data}) That is my code i want when user send get method to my question api i want send api structur look like this [ { "id": 1, "question": "dsdsdssd?", "answers": { "A": [ { "id": 1, "answer": "tehsil alitem" }, { "id": 2, "answer": "sen necesen?" } ], "B": [ { "id": 1, "answer": … -
Geodjango cache
I'm using geodjango and wrote an API to paginate stores by distance, all stores can be 20 or something, so I can just cache them, but how to order them by distance for each user? evaluated queryset is just a list so I can't use the query functions here's my queryset code: def get_queryset(self): user_location = self.request.user.location qs = Store.objects.all() qs = qs\ .annotate(distance=Distance('location', user_location))\ .order_by('distance') return qs Any ideas? -
Unable to connect Websocket with wss using SSL Certificate
I have added SSL certificate from letsencrypt and did configuration using Nginx but unable to connect to the websocket using WSS. It works fine if change the configuration to ws. Here is the configuration file -
Django_eventstream to send notifications from backend to frontend: the stream is established but it's empty
I'm trying to send notification from backend (Django) to frontend (Vue.js) using django_eventstream Following the library quide, I create endpoint in asgi.py: import django_eventstream import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from django.urls import path, re_path import sv.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ "http": URLRouter([ path( 'frontend-notifications/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'], }), re_path(r'', django_asgi_app), ]), "websocket": URLRouter(sv.routing.websocket_urlpatterns), }) At the frontend: const es = new ReconnectingEventSource(url+ '/frontend-notifications/'); es.addEventListener('success', function (e) { const data = JSON.parse(e.data); console.log('message', data); }, false ); The event stream channel is established, it can be seen in the browser debug panel. Then at the backend I send an event to the stream: from django_eventstream import send_event send_event( "test", "success", { "success": True } ) But there is no data in the stream. I've tried to send data to the stream via requests as well: import requests session = requests.Session() r = session.post(url, headers={'Connection': 'keep-alive', 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'}, data='data: Hello World\n\n', stream=True) The request returns 200 OK, but again no any data in the stream. How to send notification from back to front via SSE? Working example would be great. -
Django does not translate variables loaded on init
When I define a constant in Django file that is loaded while the app is initiating, it does not translate the value when I change the language. Example: # widgets.py from django.translation import ugettext_lazy as _ MY_CONSTANT = _('some text') When I try to use MY_CONSTANT its value is translated to the default init language but not evaluated to the current language on demand. How could I fix this? -
I want any language translation functionality in my "Next.js(version 13) + Django" project. As react-google-translate does not support my tech version
The user wants to add language translation functionality to their project. The project is built using Next.js (version 13) and Django. The user has tried using react-google-translate but it doesn't support their tech version. They need an alternative solution for language translation. The user can consider using a Python package called "translate" to implement translation functionality. The package supports multiple languages and can be installed using pip. To use the package, the user can create an instance of the Translator class and specify the source and target languages. The translate() method can then be used to translate text. The user should also handle any errors that may occur during the translation process. I tried react0google-translate library. I want to translate my website text on single selection of languge. -
How to take file name from file in body, not from header when uploading file in Django Rest framework REST API?
I have method which should upload file ( to be specific - image in JPG format) to some external storage (it does not matter where in this issue). Im sending Post request using Postman. I want that uploaded file to take name from file which I pass in my request body. In Postman this file is passed in body as binary. Lets say this file is called dog.jpg. However my request does not work If I won't add "Content-Disposition" header, and as value of this header I need to pass ": attachment; filename=dog2.jpg". My file will be uploaded then as dog2.jpg, instead of dog.jpg. Also it is a little bit burdensome to have to change that name directly in headers everytime. Is there any way to avoid that header? Beginning of my post method: @api_view(['POST']) @parser_classes([FileUploadParser]) @csrf_exempt @login_required def upload_image(request): print(request.FILES['file']) file = request.data.get('file') For now print(request.FILES['file']) Would dog2.jpg file = request.data.get('file') Would also return dog2.jpg The rest of method I think is not important, as it is only logic to upload file to storage, which works perfectly fine. -
Django: Admin Panel - Select an existing image from any folder without creating duplicates
I'm looking for a way to use images that are already in the media folder. models.ImageField(upload_to = "madia/images/pages" verbose_name=('img')) Selecting images for a post in the admin panel creates a duplicate image. Is there a field that allows you to select an existing image from any folder on the server, without being tied to a specific folder - without duplicating images? -
Python django auth test
I want to write tests for my python django application. For tests, I need to get an API token, I tried it through APIClient with this code: client = APIClient() responce = json.loads(client.post('/api-token-auth/',data={"username":"root", "password":"root"}).content) But in return I get {'non_field_errors': ['Unable to login with provided credentials.']} Through the "requests" library and Postman everything works with the same data -
Error: 'Id' can only be used as a field name if the field also sets 'primary_key=True'. Removal of id doesn't change anything
I used an id field in my django models.py file. Whenever I try to make migrations, I get the following error: `SystemCheckError: System check identified some issues: ERRORS: text_modifier.Posts: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'.` I'm trying to insert id = models.PositiveIntegerField() I'm trying to add the models to postgres I have tried removing the id field from the models.py file, but the error arises again (I have entirely no idea why). Also, I have tried setting the argument primary_key=True myself, this also didn't help. I understand now that id field is default in django, but the removal of it doesn't change anything. I have another problem of django not being able to see the app I'm trying to put the id field in. I have copied the name of the app from the apps.py file and used set DJANGO_SETTINGS_MODULE=search_simple.settings to ensure it works properly. Can it be the issue? My python: Python 3.11.2 My django: 4.1.7 -
DJango pick Operating system username instead of user name present in settings file
About the issue I created the project using command django-admin startproject test and updated the settings file to have mysql database details. Apart from that nothing added/updated/deleted in code. Database details in config file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "Name": "django", "User": "root", "Password": "", "Host": "localhost", "Port": "3306" } } Then ran the command python manage.py runserver and gave me very strange error. It says Access denied for user pankaj@localhost Question Settings file has username = root, why django pick operating system username -
Django form not getting value for clean method
I'm trying to write a clean method form one of my forms in Django 3.0.Here when the user selects the production_process the clean method is not getting any value.And rising an error in my template page as Production process: Select a valid choice. That choice is not one of the available choices. Here is my forms.py class ProductionCapacityForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') self.request = kwargs.pop('request') try: self.work_time = kwargs.pop('work_time') except: pass super(ProductionCapacityForm, self).__init__(*args, **kwargs) self.fields['production_process'].queryset = ProductionProcess.objects.filter(is_deleted=False).values_list("name", flat=True).distinct() self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) def clean(self): production_process = self.cleaned_data.get('production_process') number_of_people = self.cleaned_data.get('number_of_people') datee = self.cleaned_data.get('date') pk = self.instance.pk if production_process: try: if production_process not in ProductionCapacity.objects.get(client=self.client, date=datee,production_process=production_process.id): self.cleaned_data['production_process'] = get_object_or_404(ProductionProcess,client=self.client,id=production_process.id) except: if ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process.id).exists(): raise forms.ValidationError('Production Process is already exists') self.cleaned_data['number_of_people'] = number_of_people self.cleaned_data['date'] = datee return super(ProductionCapacityForm, self).clean() class Meta: model = ProductionCapacity widgets = { "date": McamDateInput1, } fields = ['date', 'production_process', 'number_of_people'] Here is my models.py class ProductionCapacity(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) production_process = models.ForeignKey(ProductionProcess,on_delete=models.CASCADE,blank=True,null=True) number_of_people = models.IntegerField(blank=True, null=True) Here -
i am get all users list and then include which users complete kyc verified using foreign key
user list = user.objects.filter().values('username', 'user id', 'email', 'phone') Query set [{'username': 'muthu12', 'user id': 25, 'email': 'muthu12@gmail.com', 'phone': '9047885819'}, {'username': 'muthu123', 'user id': 26, 'email': 'muthu123@gmail.com', 'phone': '9047885819'}, I'm expect this type of Query set, KYC is Foreign key, query set : [{'username': 'muthu12', 'user id': 25, 'email': 'muthu12@gmail.com', 'phone': '9047885819', 'KYC' : True}, {'username': 'muthu123', 'user id': 26, 'email': 'muthu123@gmail.com', 'phone': '9047885819', 'KYC' : False}, -
How to delete objects in db only one time in for loop
I have json with few for loop iterations in each other and i want to know how to delete objects in db only one time on first iteration? I mean objects.all().delete and then ill create everthing from json task.py for i in json: for j in i.Information: MyModel.objects.filter(date=j.Date).delete() MyModel.objects.create(a=j.A, b=j.B, date=j.Date() #something like that In this for loop its deleting everytime objects in my db -
Use email request for signing in django
How can I use the docusign codes like the code in this link in the Django app? https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-email-remote/ I want to be able to use these codes in my views in django app. -
Is it possible to pass views parameters without using URLs in Django?
In product_detail in views.py, I use slug and pk (which is passed through the url in urls.py) to look up for Product. I'd like to use pk or id along with slug. But, the case is, I don't want to pass id or pk parameter to url. What I have: views.py def product_detail(request, slug, pk): product = get_object_or_404(Product, slug=slug, pk=pk) return render(request, "store/product_detail.html", {"product": product}) urls.py urlpatterns = [ # ... path("<int:pk>/<slug:slug>/", views.product_detail, name="product_detail"), ] Expected: views.py def product_detail(request, slug): pk = some_way_to_get_pk product = get_object_or_404(Product, slug=slug, pk=pk) return render(request, "store/product_detail.html", {"product": product}) urls.py urlpatterns = [ # ... path("<slug:slug>/", views.product_detail, name="product_detail"), ] Is it possible to do it with HttpRequests or some other way and how? Is it bad design? I'd like to know for educational purpose. Thanks in advance. -
Optimal approach for displaying big data tables in a template
Django is used as backend. There is data to display in the template of the client part, that's the question itself. What is the best way to display a table with 5000 rows and 50 columns in a template? which approach would be correct. I'm thinking of implementing it through DataTables, in which case how will the template behave with large data, or are there alternatives and a more suitable pattern for my task? Further in the table I will implement real-time filtering and export to Excel. I'm thinking of trying htmx, I don't know if it will solve my problem with long loading? Or caching can speed up page loading? Please tell me the correct approach, newbie on the fronte Thank you! Попробовал DataTAbles, очень долго грузится. -
docker-compose postgres container creates database locally but not on github actions
I have a project with three containers: python, nodejs, and postgres. The python container is for django and the nodejs container is for react. I'm using docker compose to run all of these containers together. Locally, everything runs properly. When running docker-compose in github actions the postgres container fails to create a database with the specified name. Here is the compose file: services: django: hostname: django container_name: django build: context: ./backend dockerfile: dev.Dockerfile ports: - 8000:8000 volumes: - ./backend:/backend environment: - SECRET_KEY=development_secret - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: db: condition: service_healthy networks: - backend command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" nodejs: build: context: ./frontend dockerfile: dev.Dockerfile ports: - 3000:3000 volumes: - ./frontend:/app depends_on: db: condition: service_healthy networks: - backend command: > npm install npm run start db: image: postgres ports: - 5432:5432 environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} networks: - backend healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"] interval: 5s timeout: 5s retries: 5 networks: backend: name: network driver: bridge The error on github actions is: db_1 | 2023-03-16 04:40:00.177 UTC [75] FATAL: *** "***" does not exist db_1 | 2023-03-16 04:40:05.305 UTC [83] FATAL: *** "***" does not … -
List data print in another for loop in Django template
{% for i in packages %} {% endfor %}` i use this for loop in djnago template, in his loop i need to print another list. package_main_prices_list=[340, 180, 170, 95, 500] problem is i need to print one data from "package_main_prices_list" list in one "Packages" loop in Django template like this: {% for i in packages %} [340] #one data from "package_main_prices_list" {% endfor %} outpur will be: package name 340 date package name 180 date Thanks in advance. Regards Hamid. -
I have entered a value for my volumes field yet I am getting the error. services.inventory_app.volumes.0 type is required
version: "3" services: inventory_app: container_name: inventory_app image: postgres environment: POSTGRES_USER: "inventory_user" POSTGRES_PASSWORD: "inventory123" PGDATA: /data/inventory_app volumes: - inventory_app: /data/inventory_app ports: - "5434:5432" networks: - inventory_app_net restart: unless-stopped networks: inventory_app_net: driver: bridge volumes: inventory_app: I tried to build a successful connection through docker-compose to pgsql -
Can I make the class name to be a variable in python?
Can I make the class name to be a variable in the newer python release? I mean can I short the following instructions to be briefer? if target == "course": return Course.objects.all()[start:end]` elif target == "Subject": return Subject.objects.all()[start:end] elif target == "Teacher": return Teacher.objects.all()[start:end] to be briefer: return VARIABLE.objects.all()[start:end] -
How do I connect to MySQL Workbench on the host Windows from Ubuntu 22.04 using Django?
First, these answers didn't solve my problem: How to connect to WSL mysql from Host Windows, Connecting to MySQL database in django using workbench, and Unable to connect to MySQL on Ubuntu from MySQL Workbench on Windows. I have Ubuntu 22.04 installed on my Windows 11 and want to connect to MySQL Server (installed on the host Windows 11) from Ubuntu using Django but I keep getting Django Runserver Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") and when I changed my database setting (host) from 127.0.0.1 to the IP I found when I ran nslookup "$(hostname).local", I get django.db.utils.OperationalError: (1130, "Host 'Mkw' is not allowed to connect to this MySQL server"). On my old laptop, everything works fine using HOST: 127.0.0.1, PORT: 3306. I don't want to install the MySQL server on Ubuntu since I already have it installed on the host Windows.