Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy_forms using
I have been using crispy_forms for my form on django project. But While Project is running. A problem A problem appears suddenly. how can I solve this problem on my project ? can you help me ? I have to go on this project very faster [[[enter image description here](https://i.stack.imgur.com/x8kr2.png)](https://i.stack.imgur.com/UF8XI.png)](https://i.stack.imgur.com/fDG6k.png) -
Im trying to make a Instagram reel downloader and keep getting this error Expecting "property name enclosed in double quotes: line 1 column 2 (char 1)
Im using django to create a instagram reel downloader but it keeps giving me json errors My code: from django.shortcuts import render , redirect from instascrape import * import json import time # Create your views here. def index(request): if request.method == "GET": return render(request, "index.html") else: if request.POST['url']: google_reel = Reel("https://www.instagram.com/reel/CumvX9VgNQt/?utm_source=ig_web_copy_link&igshid=MzRlODBiNWFlZA==") google_reel.scrape() google_reel.Download(fp = "{path\filename.mp4}") else: return render(request, "index.html", { "error": "Invalid url" }) return redirect("/") The error im getting is "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" im thinking it is a python package problem the one im using is instascrape (https://github.com/chris-greening/instascrape) -
How to send message through django-channels from asyncio loop with add_reader
I am trying to listen for notifications from postgres database and send message through django-channels on each row insertion, for that I want to use asyncio loop, where I am adding reader for connection. However, I am receiving following error on attempt to use async_to_sync: RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Here is my code: import asyncio import logging import channels.layers from asgiref.sync import async_to_sync from django.conf import settings from django.core.management.base import BaseCommand from django.db import connections channel_layer = channels.layers.get_channel_layer() logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): conns = [(connections[db].cursor().connection, db) for db in settings.DATABASES] loop = asyncio.get_event_loop() for conn, db in conns: conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute("LISTEN event_changed;") loop.add_reader(conn, partial(self.handle_notify, conn=conn, db=db)) logger.info("Starting runlistener loop.") loop.run_forever() def handle_notify(self, conn, db): conn.poll() for notify in conn.notifies: logger.debug(f"new event received on db {db}: {notify.payload}.") async_to_sync(channel_layer.group_send)( db, {"type": "on_new_event", "event": notify.payload} ) conn.notifies.clear() I can't use await in handle_notify since it is not async function and I couldn't find any way to use async function as a callback for add_reader. I've managed to implement this functionality without asyncio, by simply checking connection with select.select in … -
How can fix ' Error: No application module specified.' on DigitalOcean
I am getting ' Error: No application module specified. ' error while I'm trying to deploy my django project. After Successful Build, Digital Ocean is trying deploy it and raise this error after short time. Can you help me about this? Where should I change? settings.py >>> """ Django settings for djcrm project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv # .env dosyasını yükle load_dotenv() DEBUG = os.getenv('DEBUG') # SECRET_KEY'i al SECRET_KEY = os.getenv('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #third party apps 'crispy_forms', "crispy_tailwind", 'tailwind', #local apps 'leads', 'agents', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": … -
Query many to one backward relation Django
I have these 2 models: class User(models.Model): full_name = models.CharField(max_length=255) class WorkSchedule(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) day_of_week = models.IntegerField() start_time = models.TimeField() end_time = models.TimeField() Is it possible for me to use a single query here to get back something like this: { "id": 1, "full_name": "User name", "work_schedule": { { "day_of_week": 1, "start_time": 8:00, "end_time": 20:00 }, { "day_of_week": 2, "start_time": 8:00, "end_time": 20:00 } } } -
Form field not showing in tempate
after defining form field when I try to access in django template using {{form.Date_Joined}} not working class UserAdd(forms.ModelForm): class Meta: model=CompanyUsers fields= '__all__' exclude=['usrPsswd','usrId','usrCmpnyId','lstLogin','is_active','usrDOJ'] widgets={ 'Date_Joined':forms.DateInput(attrs={'type':'date'}), } The widget i've declare not showing <div class="order"> <!-- <div class="head" > --> <h4> ADD COMPANY</h4> <!-- </div> --> <table id="table-datas"> <form method="POST" action=""> {% csrf_token %} <tbody> <tr><td>Username</td><br><td>{{ form.usrNme}}</td></tr> <tr><td>First Name </td><br><td>{{ form.usrFNme}}</td></tr> <tr><td>Last Name </td><br><td>{{ form.usrLNme}}</td></tr> <tr><td>Date of join</td><br><td>{{form.Date_Joined}}</td></tr> <tr><td>Department</td><br><td>{{ form.usrDpt}}</td></tr> <tr><td>Email</td><br><td>{{ form.usrMail}}</td></tr> <tr><td><button type="submit">Register</button></td></tr> </form>``` so the Date Joined field shows nothing -
How to make table editable in django on the clientside
I am building this Django webapp, where I have data stored in the SQLite. And being fetched into a table in the client side. But I have this idea of patching the data from the table itself, just like Edit in grid view, of sharepoint list. Where If I click the toggle button 'editable mode', the all cells become editable and after making necessary changes, if click the toggle button again, the changes should be saved in the database as well. Below are the snippets of the project. views.py class EmployeeUpdateView(View): def patch(self, request, employee_id): data = json.loads(request.body) try: employee = Employee.objects.get(id=employee_id) for change in data: field_name = change['field_name'] field_value = change['field_value'] setattr(employee, field_name, field_value) employee.save() return JsonResponse({'success': True}) except Employee.DoesNotExist: return JsonResponse({'success': False, 'error': 'Employee not found'}) except Exception: return JsonResponse({'success': False, 'error': 'Error saving changes'}) this is url path path('update/<int:employee_id>/', EmployeeUpdateView.as_view(), name='update_employee'), this is the table template <tbody class="thead-light"> {% for employee in page_obj %} <tr style="font-size: 12px;"> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.name }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.phone }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.dob }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.doj }}</td> … -
Wagtail Image Chooser Template returns 404 http not found
When I deploy my wagtail django with nginx and I want to choose an image for a ForeignKeyField to wagtailimages.Image I get a HTTP 404 for <base-url>/cms/images/chooser/ although when I directly access the url it returns the correct json. Is this a nginx Problem or a wagtail / django problem? -
Convert PDF to PDF/A with python
I am working on a Python project and I need to convert a PDF file to PDF/A format programmatically. Ideally, I'm looking for a Python library or tool that supports PDF to PDF/A conversion and provides options to specify PDF/A compliance levels, such as PDF/A-1a or PDF/A-3b. Any example code or a step-by-step guide would be greatly appreciated. I have explored some libraries such as PyPDF2 and pikepdf, but I haven't found a straightforward way to achieve this. Can anyone provide guidance on how to convert a PDF file to PDF/A using Python? -
Django: Rest Framework (Serializer)
I'm new to using the django rest framework. I'm trying to understand how I can validate a field with the serializer based on the input from the user, for example: Serializer: from rest_framework import serializers VALID_REGION = 'region' def validate_region(value): if value != VALID_REGION: raise serializers.ValidationError('Invalid region, make sure region parameter is spelled correctly.') return value class RegionSerializer(serializers.Serializer): region = serializers.CharField(required=False, validators=[validate_region]) Here I want to validate that the region is spelled correctly. views.py def get(request, *args, **kwargs): serializer = RegionSerializer(data = request.data) if serializer.is_valid(): data = serializer.validated_data region = data.get('region', '') regions = region_lib.get_regions(region) return Response({"regions" : regions}, status=status.HTTP_200_OK) else: errors = serializer.errors return Response({"error" : errors}, status=status.HTTP_400_BAD_REQUEST) Here I pass 'regoin' misspelling it intentionally. { "regoin": "Test" } When I run serializer.is_valid() it returns true. Not sure what I'm missing. -
In Django, how to get the return of two functions in the same html page? Error: TypeError: kwargs argument must be a dict, but got function
In Django I have two functions contained in views.py. One is called def city_detail and the other is called def DemoView. Both return return render(request, 'app1/home.html', context). In url.py I would like to use both functions, but it seems I can only use 1 at a time. If I use only one of the two, then it works (only one of the two works). If I write in urlpatterns I write: path('home/', views.city_detail, views.DemoView, name='home'), path('home/', views.DemoView, name='home'), I get the error: raiseTypeError( TypeError: kwargs argument must be a dict, but got function. How can I use both functions in home? -
How to filter the model property value using custom filter in Django admin
I have the model with property and custom filter. Depending on the custom filter value, I need to update the _approved property value (not the model queryset) on the Django admin page. model.py class Model(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created') updated = models.DateTimeField(auto_now_add=False, auto_now=True, verbose_name='Updated') @property def _approved(self): return ModelRecordRelation.objects.filter(model_id=self.id, status='A').count() admin.py class TimeFrameFilter(SimpleListFilter): title = 'timeframe' parameter_name = 'timeframe' def lookups(self, request, model_admin): return [ ('Today', 'Today'), ('ThisWeek', 'This Week'), ] def queryset(self, request, queryset): return queryset.filter() class ModelAdmin(admin.ModelAdmin): list_display = ['created', 'updated'] class Meta: model = Model def approved(self, obj): return obj._approved approved.admin_order_field = 'approved' -
Unable to fetch data with axios from Django backend using relative path
I am currently developing a web application using React for my frontend and Django for my backend. The frontend and backend are running on separate local servers. I am trying to fetch some data from my Django backend using axios in my React application with the following code: const handleButtonClick = () => { setLoading(true); axios .get("/bucket-size/") .then((response) => { const size = response.data.bucketsize; const unit = response.data.unit; setOutput(size + " " + unit); }) .catch((error) => { console.error(error); }) .finally(() => { setLoading(false); }); }; The Django backend route looks like this: path('bucket-size/', BucketSize.as_view(), name='bucket-size'), Note -- i do not want to add a proxy to my package.json since the backend will be running on Docker and i want it to fetch relatively. Can anyone help? -
Generate IFCRoad via IFCOpenShell
I have this model class Tramif_PCI_agrup(models.Model): id = models.AutoField(primary_key=True) pci = models.FloatField(null=True) geom = models.LineStringField(geography=True, srid=4326, null=True) That i want to translate into an IFCRoad using the IFCOpenShell library to get a final IFC file with every Object with its geom and its PCI value. This is what i tried but it didnt work # Get all objects from the Tramif_PCI_agrup model tramif_pci_agrups = Tramif_PCI_agrup.objects.all() # Create a blank model ifc_file = ifcopenshell.file(schema='IFC4X3') # Create an IfcRoad entity road = ifc_file.create_entity("IfcRoad") road.Name = "Simple Road" # Fetch objects from the model and iterate over them for tramif_object in tramif_pci_agrups: # Extract geometry and PCI values from the model object geom = tramif_object.geom pci = tramif_object.pci # Convert the geometry to WKT format wkt_geom = geom.wkt # Create an IfcAlignment entity for each object alignment = ifc_file.create_entity("IfcAlignment") alignment.Name = f"Alignment {tramif_object.id}" alignment.Description = f"PCI: {pci}" # Create an IfcAlignmentCurve entity for the geometry curve = ifc_file.create_entity("IfcAlignmentCurve") curve.Axis = ifc_file.create_entity("IfcCurve") curve.Axis.Points = ifc_file.create_entity("IfcPointList") curve.Axis.Points.Coordinates = [(coord[0], coord[1], 0) for coord in GEOSGeometry(wkt_geom)] # Add the alignment curve to the alignment entity alignment.Representation = curve # Add the alignment entity to the road road.Representation = alignment # Write the IFC file ifc_file.write("/images/road_test.ifc") But … -
How to set env variables for django test in vscode
I would like to set env variable for django test in vscode. These env variables will be different from env variables to be used in django run server. -
TinyMCE is not working correctly in my django project
I have created a Django blog site where I can write blog posts both from the main site and the admin site. To compose my blog posts, I am using the TinyMCE editor. When I am in the admin site, I can successfully write and submit my blog posts using TinyMCE. However, when I attempt to write a blog post from the main site using TinyMCE, I encounter an issue. Although my submit button appears to be working correctly, it does not perform any action upon clicking it. Strangely, if I refresh the page and then click the submit button again, my blog post gets posted, and everything works fine from that point onward. Please tell me What is the mistake that I'm doing. This is my tiny.js file var script= document.createElement('script'); script.type='text/javascript'; script.src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload=function(){ tinymce.init({ selector: "#id_content", height:656, plugins: [ 'advlist autolink link image lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor … -
Gunicorn Fargate ELB healthcecks fail before auto scale
I have setup a django application using gunicorn server on ECS with Fargate backend. I have setup auto scaling based on both CPU and Memory utilisation. Fargate capacity: 2 vCPU and 4 GB RAM The problem is that whenever the load is high, even before the CPU utilisation is high, the ELB healthchecks are failing and as a result the task is getting deregistered and never leads to auto scaling. gunicorn is running with 2 workers and 4 threads. gunicorn <appname>.wsgi:application --workers 2 --threads 4 I'm trying to understand the reason for this and how to solve this issue. -
why for loop not working in django .Error in rendering html in django using for loop
i am writing code to get a carousal which consists of products using for loop in python But there is some isuue it is generating everthing but not generating my items inside carousal Things defined here: list_of_range=[[0, 1, 2], [3, 4]] Now my no of slides in carousal is generated pretty well but items in side each slide is not get generated Here's the code in index.html <div class="container mt-5" > <div id="carouselContainer" class="carousel slide" data-ride="carousel"> <div class="carousel-inner justify-content-center"> {% for i in list_of_range %} {% if i == list_of_range.0 %} <div class="carousel-item active"> {% else %} <div class="carousel-item "> {% endif %} <div class="row"> {% for d in list_of_range.i %} <div class="col-sm-3 col-md-3"> <div class="card" style="width: 18rem"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyRql003EXAw9EVs6V3koKd5wXbW0Lt-yJOA&usqp=CAU" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{products.0.product_name}}</h5> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} and the code in main.py is as follows : def index(request): all_products_list = Product.objects.all() n= len(all_products_list) nslides = n//3+ ceil((n/3)-n//3) print(nslides) prod_range_list = [] to_range = n for c in range(nslides): if to_range/3>=1: prod_range_list.append(list(range(c * … -
how do you associate a user with a payment when using mpesa express on python django
the response body on the call back is usually: { "Body": { "stkCallback": { "MerchantRequestID": "21605-295434-4", "CheckoutRequestID": "ws_CO_04112017184930742", "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": 500 }, { "Name": "MpesaReceiptNumber", "Value": "WHAkLK451H35OP" }, { "Name": "Balance" }, { "Name": "TransactionDate", "Value": 20171104184944 }, { "Name": "PhoneNumber", "Value": 254710549039 } ] } } } } This is my callback url, which works fine and saves the data in a model. How can you associate a user with a payment once the response is received and saved in a general model not associated with any user: @csrf_exempt def callbackurl(request): if request.method == 'POST': m_body =request.body.decode('utf-8') mpesa_payment = json.loads(m_body) payment = StatusPayment( phoneno=mpesa_payment['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value'], transcode=mpesa_payment['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value'], ) payment.save() context = { "ResultCode": 0, "ResultDesc": "Accepted" } return JsonResponse(dict(context))` -
Is it possible in Django to use threaded=True (like in Flask) to e to handle each request in a new thread?
On Flask you can use threaded=True to handle each request in a new thread. For example: if __name__=="__main__": app.run(host="0.0.0.0", port=8000, threaded=True) With Django can i use something like threaded=True (or simil) to handle each request in a new thread? (without using async). Or is it more complicated in Django? -
Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\\Z']
estoy haciendo una todo app con Django y estoy queriendo hacer el update/delete de las tareas pero me salta el error del titulo, dejo las partes del código que, entiendo, son de interés: El HTML completa la tarea: <form action="{% url 'task_complete' task.id %}" method="POST"> {% csrf_token %} <button> Complete </button> </form> La lista de patterns: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('singup/', views.singup, name="singup"), path('tasks/', views.tasks, name="tasks"), path('tasks/create/', views.create_task, name="create_task"), path('tasks/<int:task_id>/', views.task_detail, name="task_detail"), path('tasks/<int:task_id>/complete/', views.task_complete, name="task_complete"), path('logout/', views.singout, name="logout"), path('singin/', views.singin, name="singin"), ] La función que debería completarlas: def task_complete(request, task_id): task = get_object_or_404(Task, pk=task_id, user=request.user) if request.method == "POST": task.date_completed = timezone.now() task.save() return redirect('tasks') Esperaba que complete la tarea y deje de aparecer en tareas, pero tira el error Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\Z'] -
how to set log level for a specific url path in django?
my view is below @api_view(['GET']) def get_test(request): return HttpResponse('Ok', status.HTTP_200_OK) and my path in urls.py in urlpatterns is as below. path('api/test', views.get_test), This path is called a lot as part of the liveness probe in kubernetes and i want the log level just for this url to be set to CRITICAL so that it would not be logged or ideally i want to disable django logging altogether for this particular url and right now it is set to DEBUG by default. How do i go about changing the log level or disable the log? -
Error during template rendering in DjangoCMS plugin from {% translate 'Clear' %} [closed]
I’m trying to create a custom CMS Plugin and when i click to create the plugin this error happens: Error during template rendering from {% translate 'Clear' %} How can i solve this? In the past it was working. I don’t what happens. Thank you! I tryed to access the template "/usr/local/lib/python3.8/site-packages/filer/templates/admin/filer/widgets/admin_file.html" but i couldn't because it was build by docker. -
Power BI Embedded for customers - Creating embeded URL
I'm embedding a Power BI report on a "Embed for customer" manner and authenticating via service account. I have managed to get the embed token for a single report and a single workspace using Microsoft guides. The issue comes when making a POST request to https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}. I get a 403 error. Also, note that I am using Django and the final purpose is to process everything on the backend and just send a URL to the front end to put inside an iframe. This is my Django View: from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views import View from django.shortcuts import get_object_or_404 from .models import Dashboard, ReportConfig, EmbedConfig, EmbedTokenRequestBody from .serializer import DashboardSerializer from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from powerbi.aadservice import AadService import requests import json class DashboardView(viewsets.ModelViewSet): serializer_class = DashboardSerializer permission_classes = [IsAuthenticated] def get_queryset(self): # Retrieve the user's groups user = self.request.user user_groups = user.groups.all() # Filter the dashboards based on group membership queryset = Dashboard.objects.filter(group__in=user_groups) return queryset class PbiEmbedService(View): def get(self, request, workspace_id, report_id, additional_dataset_id=None): '''Get embed params for a report and a workspace''' report_url = f'https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}' api_response = requests.get(report_url, headers=self.get_request_header()) if api_response.status_code != … -
Django-MPTT using Parent and Child in same form
My goal is straightforward: I want to enable the selection of a parent category first and then choose its corresponding child categories. Unfortunately, I am encountering difficulties in implementing this functionality. My code is <form> <div class="mb-3"> <label for="main-category" class="form-label">Ana Kategori</label> <select class="form-select" id="main-category" name="main_category"> <option value="">Seçin</option> {% recursetree categories %} <option value="{{ node.id }}">{{ node.name }}</option> <div class="mb-3"> <label for="sub-category" class="form-label"></label> {% if not node.is_leaf_node %} <select class="form-select" id="children" name="children"> <option value="{{ node.id }}">{{ children }}</option> {% endif %} {% endrecursetree %} </select> </div> </div> <button type="submit" class="btn btn-primary">Gönder</button> </form> current result: