Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why in the Django + Tailwindcss project, styles are used in one file and not in another?
Here is the project's file system: enter image description here All classes work in this file: file: navbar.html <nav class="bg-white shadow-lg"> <div class="max-w-6xl max-auto px-4"> <div class="flex justifly-between"> <div class="space-x-7"> <div class="flex"> <a href="#" class="flex items-center px-2 py-4"> <img class="h-8 w-8" src="{% static 'myapp/images/logo.png' %}" alt="logo"> <span class="font-semibold text-xl"> Shop </span> </a> </div> <div class="items-center flex space-x-1"> <a href="#" class="py-4 px-2 font-semibold border-b-4 border-black ">Sell</a> <a href="#" class="py-4 px-2 font-semibold ">Sold</a> <a href="#" class="py-4 px-2 font-semibold ">Home</a> </div> </div> </div> </div> </nav> In this file tailwind classes for some reason do not work. Why is this happening??? file: contacts.html <div class=" p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 xl:grid-cols-3 lg:grid-cols-3 gap-3 "> {% for item in items %} <a href="{% url 'site:detail' item.id %}"> <div class=" px-10 py-10 rounded overflow-hidden shadow-lg"> <img src="{{item.images.url}} " alt="img"> {{item.name}} {{item.price}} <br> </div> </a> {% endfor %} </div> Why does tailwind work in one part of the code and not in another? Even though both files are in the same folder. You need to make tailwind work in the contacts.html file. -
i'm trying to acess my django project admin page(local) and i keep getting this trackback
ModuleNotFoundError at /admin/login/ No module named 'users.backends' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 5.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'users.backends' Exception Location: <frozen importlib._bootstrap>, line 1324, in _find_and_load_unlocked Raised during: django.contrib.admin.sites.login Python Executable: C:\Users\DELL\Documents\Jamor_tech\Jam_T\Jam_T\Scripts\python.exe Python Version: 3.12.3 Python Path: ['C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T\\Jam_T', 'C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T\\Jam_T\\Lib\\site-packages'] Server time: Sun, 29 Sep 2024 18:06:12 +0000. i tried "http://127.0.0.1:8000/admin" on my browser expecting my admin page so that i can test my superuser details as well as generally testing the whole project, -
Django ` [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory?` message when uploading large files
My dockerized Django app allows users to upload files(uploaded directly to my DigitalOcean Spaces). When testing it on my local device(and on my Heroku deployment) I can successfully upload small files without issue. However when uploading large files, e.g. 200+MB, I can get these error logs: [2024-09-29 19:00:51 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) web-1 | [2024-09-29 19:00:52 +0000] [1] [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory? web-1 | [2024-09-29 19:00:52 +0000] [29] [INFO] Booting worker with pid: 29 The error occurs about 30 seconds after I've tried uploading so I suspect it's gunicorn causing the timeout after not getting a response. I'm not sure what to do to resolve it. other than increasing the timeout period which I've been told is not recommended. Here is my code handling file upload: views.py: @csrf_protect def transcribe_submit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size session_id = str(uuid.uuid4()) request.session['session_id'] = session_id try: transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() ... except Exception as e: # Log the error and respond with a server error status print(f"Error occurred: {str(e)}") return HttpResponse(status=500) ... else: return HttpResponse(status=500) else: form = … -
Why does my Celery task not start on Heroku?
I currently have a dockerized django app deployed on Heroku. I've recently added celery with redis. The app works fine on my device but when I try to deploy on Heroku everything works fine up until the Celery task should be started. However nothing happens and I don't get any error logs from Heroku. I use celery-redis and followed their setup instructions but my task still does not start when I deploy to Heroku. Here is my code: heroku.yml: setup: addons: plan: heroku-postgresql plan: heroku-redis build: docker: web: Dockerfile celery: Dockerfile release: image: web command: python manage.py collectstatic --noinput run: web: gunicorn mysite.wsgi celery: celery -A mysite worker --loglevel=info views.py: from celery.result import AsyncResult task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) task.py: from celery import Celery app = Celery('transcribe')# @app.task def transcribe_file_task(path, audio_language, output_file_type, dest_dir, session_id): print(str("TASK: "+session_id)) #rest of code return output_file celery.py: from future import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery("mysite") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I ensured that my CELERY_BROKER_URL and CELERY_RESULT_BACKEND are getting the correct REDIS_URL from environment variables by having it printing it's value before the task is to be started. So I know that's not … -
Google Login with Django and React
I am trying to integrate google login with Django and React (Vite) but I keep getting an error. I have set up the credential on google cloud console, I use @react-oauth/google for the login in the frontend. The login in the frontend goes through but not the backend. I don't know what I am doing wrong. Below is the error and the code. The frontend works well but the backend has issues settings.py AUTH_USER_MODEL = "base.User" # Application definition INSTALLED_APPS = [ "django.contrib.sites", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # App "base", # Third party apps "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "dj_rest_auth.registration", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", "corsheaders", # Debug toolbar for development "debug_toolbar", ] SITE_ID = 1 MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "allauth.account.middleware.AccountMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] AUTHENTICATION_BACKENDS = [ "base.auth_backends.CaseInsensitiveModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] # Social login settings CALLBACK_URL = config("CALLBACK_URL") LOGIN_REDIRECT_URL = "/api/auth/google/callback/" SOCIALACCOUNT_LOGIN_ON_GET = True ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": config("CLIENT_ID"), "secret": config("CLIENT_SECRET"), "key": "", }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, "METHOD": "oauth2", # "REDIRECT_URI": "http://localhost:8000/api/auth/google/callback/", } } # Simple jwt config for dj-rest-auth SIMPLE_JWT = { "ROTATE_REFRESH_TOKENS": True, "ACCESS_TOKEN_LIFETIME": … -
502 Bad Gateway: Permission Denied for Gunicorn Socket
2024/09/29 14:04:13 [crit] 6631#6631: *1 connect() to unix:/home/ubuntu/myproject/Ecom_project/ecom_p/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 103.175.89.121, server: ecomweb-abhishadas.buzz, request: "GET / HTTP/1.1", upstream: "``http://unix``:/home/ubuntu/myproject/Ecom_project/ecom_p/gunicorn.sock:/", host: "www.ecomweb-abhishadas.buzz" What I Tried: Checked Socket Permissions: I ran the command ls -l /home/ubuntu/myproject/Ecom_project/ecom_p/gunicorn.sock to verify the permissions of the socket file. I noticed that the permissions did not allow the Nginx user (www-data) to access the socket. Changed Socket Permissions: I modified the permissions of the socket file using chmod to ensure that the Nginx user has the necessary permissions to access it. Example command: sudo chmod 660 /home/ubuntu/myproject/Ecom_project/ecom_p/gunicorn.sock Set Socket Ownership. I ensured that the socket file is owned by the user running Gunicorn (e.g., ubuntu or whatever user you specified). Example command: sudo chown ubuntu:www-data /home/ubuntu/myproject/Ecom_project/ecom_p/gunicorn.sock Restarted Services. I restarted both Nginx and Gunicorn to apply the changes. Commands used: sudo systemctl restart nginx sudo systemctl restart gunicorn (or the specific command you use to start Gunicorn). What I Was Expecting: I was expecting that after adjusting the permissions and ownership of the Gunicorn socket file, Nginx would be able to connect to Gunicorn without the permission denied error. This would allow my Django application to be served properly, resolving … -
BaseForm.__init__() got an unexpected keyword argument 'my_username'
once i made a simple login form in django i got this error i searched a lot but i found nothing i read many articles here and github enter image description here this is my form code and views code. i made it with html it worked but in django project i created file named it form.py wrote the code once trying to run server got this error i tried searching in the documention of django can any one help please -
In Django `import-export` lib how to pass row if values in few rows don't meet specific conditions?
I have a few dynamic fields (2) in ModelResource class. I need to export a row only if at least one of those fields has a value: +----+-------+-------+ | ID | col A | col B | +====+=======+=======+ | 1 | | value | # <-- exports +----+-------+-------+ | 2 | value | | # <-- exports +----+-------+-------+ | 3 | | | # <-- passes as no values in both columns +----+-------+-------+ Is there a way to achive this goal in import-export lib or I have to edit a tablib dataset ? P.S. Data exports to Excel if that matters. -
Why is there no answers for programming on android? [closed]
There is no answers for programmming on android. Why? I have tried to check everywhere but i only get anders for PC. -
Frontend and backend servers behind Nginx - CORS problem
Here is a newbie question about having two servers behind nginx. I have two applications, nextjs frontend, and django backend. Nextjs listens to the port 127.0.0.1:3000, and django serves its api on 127.0.0.1:8000/api. The two apps are behind nginx server, which itself listens at the port 38. The idea is to make the django backend completely inaccessible from the outside. How do I setup nginx configuration, so that django api sees the nextjs requests as coming from 127.0.0.1:3000, rather than 127.0.0.1:38? I have set up the django CORS_ALLOWED_ORIGINS to "http://127.0.0.1:3000" and would like to keep i that way. Here is one of the several nginx conf file variants that I tried (none worked) server { listen 38; location /api { proxy_pass http://127.0.0.1:8000; # Forward API requests to Django proxy_set_header Host $host; # Preserve the original Host header proxy_set_header X-Real-IP $remote_addr; # Pass the real IP of the client proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Pass the forwarded IP proxy_set_header X-Forwarded-Proto $scheme; # Pass the protocol (http or https) } location / { proxy_pass http://127.0.0.1:3000; # Forward all other requests to Next.js proxy_set_header Host $host; # Preserve the original Host header proxy_set_header X-Real-IP $remote_addr; # Pass the real IP of the client proxy_set_header … -
Redirection link is wrong after login
When I try to logout, I'm getting this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/logout/registration/login Using the URLconf defined in SHADOW.urls, Django tried these URL patterns, in this order: The current path, logout/registration/login, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. The problem is that after logging in the page isn't redirecting to the index page even though I have it already I have set the login and logout redirection URL in my settings.py. LOGIN_REDIRECT_URL = 'scanner/index/' LOGOUT_REDIRECT_URL = '/accounts/login/' LOGIN_URL = '/accounts/login/' I found something where I can get out of this by making the logout request as POST required but then the URL(http://127.0.0.1:8000/logout/) loads to a blank page. It might be because its trying to load the logout page but I don't want that. I don't understand why the request URL is http://127.0.0.1:8000/logout/registration/login when the redirection URL is different it should have been the empty path which is http://127.0.0.1:8000/ these are my views https://ctxt.io/2/AAC4cSUxEQ my URL patterns https://ctxt.io/2/AAC4BSIiFg -
How to create build of Djnago web app rest api project, and what are the tools which can be possible use to create build?
I have developed Django web app in which rest Api's are written using Django rest framework. I have used visual studio code for coding. Now I want to create build of that project. I am new to build tools. Please list build tools which can be used for Django web app and guide in creating build. I am new to Django as well as for build tools, I searched for build tools for Django, but I am not getting any relevant information, which I can understand and implement. -
How to make this div go to the bottom?
how can i make this div go to the botttom? here's the code <div class="container-fluid"> <div class="row customRows"> <div class="col col-md-3"> <div class="d-flex mb-4"> <img src="{% static '/img/cat.png' %}" alt="Logo" class="img-fluid w-25 align-self-center"> <h1 class="heading-4 align-self-center">Que vamos a estudiar hoy?</h1> </div> <ul class="m-0 p-0"> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2"> Inicio </p> </a> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2"> Chat </p> </a> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2"> Ingresa a tu clase </p> </a> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2"> Buscar clases </p> </a> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2"> Calendario </p> </a> </ul> <div class="text-center"> <img src="{% static '/img/laying.png' %}" alt="" class="w-75"> </div> <div class="profileContainer row p-2 mt-auto"> <div class="col-2"> <img src="{% static '/img/girl3.png' %}" class="w-100"> </div> <div class="col-10 my-auto"> <a href="#" class="text-decoration-none"> <p class="parrafo menuItem rounded-2 p-2 m-0"> Nombre Usuario </p> </a> </div> </div> </div> <div class="col col-md-9"></div> </div> the things that i've tried are mt-auto class from bootstrap, mb-auto from bootstrap (to check if the ul pushed the container to the bottom), marging-bottom auto in css, d-flex and flex-column with flex grow (this kinda worked but changed the distribution of the content). .menuItem { transition: background-color 0.3s … -
Can Django identify first-party app access
I have a Django app that authenticates using allauth and, for anything REST related, dj-rest-auth. I'm in the process of formalising an API My Django app uses the API endpoints generally via javascript fetch commands. It authenticates with Django's authentication system (with allauth). It doesn't use dj-rest-auth for authentication, it uses the built in Django auth system. My Discord bot uses the API as would be typical of a third-party app. It authenticates via dj-rest-auth, meaning it internally handles the refresh and session tokens as defined in dj-rest-auth's docs. Currently the API is completely open, which means anyone could use cURL to access the endpoints, some of which an anonymous user can access. Others, require an authenticated user, and this is done with the request header data: Authorization: Bearer, as what dj-rest-auth takes care of (this is what my Discord bot uses). I now want to expand on this by incorporating the Django Rest Framework API package so that API Keys are required to identify thirdparty client apps. For example, my Discord bot would use the Authorization: Api-Key header data to identify itself as an API client. It would be up to the thirdparties to make sure their API key … -
getting error as "home.models.Cart.DoesNotExist: Cart matching query does not exist."
Views.py code: def plus_cart(request): if request.method == "GET": pk = request.GET.get('prod_id') c = Cart.objects.get(pk=pk, user=request.user) c.quantity+=1 c.save(update_fields=['quantity']) user = request.user cart = Cart.objects.filter(user=user) amount = 0 for p in cart: value = p.quantity * p.product.dp amount = amount + value totalamount = amount + 40 data={ 'quantity':c.quantity, 'amount':amount, 'totalamount':totalamount, } return JsonResponse(data) in urls.py, following url is added: path('pluscart/', views.plus_cart), in the static folder, myscript.js has following code: $('.plus-cart').click(function(){ var id=$(this).attr("pid").toString(); var eml=this.parentNode.children[2] console.log("pid= ", id) $.ajax({ type:"GET", url:"/pluscart", data:{ prod_id:id }, success:function(data){ console.log("data= ", data); eml.innerText=data.quantity document.getElementById("amount").innerText=data.amount document.getElementById("totalamount").innerText=data.totalamount } }) }) while querying the database the python manage.py shell, user and cart_item with the required prod_id checked and found ok. but error is generated while executing the code. Please help. -
Python app Showing index of page on cPanel
Website When I opening my website, it showing index of page instead of showing thenpython application. Permission: 777 for passenger_wsgi file (Tried 755 also). This index of page showing a cgi_bin page, and htaccess file is also as expected as well. I don't understand what's going on here :") I tried but it keeps showing this page. -
LCP Issue in Django Project - Render Delay Caused by Backend-Generated Text Element
I'm currently working on a website built with Django and I'm having trouble with the Largest Contentful Paint (LCP). According to Google PageSpeed Insights, the LCP time is 5,070ms with a significant 88% render delay (4,470ms), and it identifies a <p> element as the LCP element. It seems that the issue is caused by dynamically generated text from the backend. The LCP element is being delayed, most likely due to render-blocking resources or inefficient processing of HTML above the fold. Here’s the snapshot from PageSpeed Insights: I’ve tried: Minifying and deferring non-critical JS. Removing unsued JS and CSS. Using font-display: swap; Ensuring images are optimized (though the LCP element is not an image). Also I tried to defer non critical css (even though the it is a critical and only used css file) by applying the following pattern from this article: <link rel="preload" href="{% static "css/city/city-critical.min.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "css/city/city-critical.min.css" %}"></noscript> Any methods or ideas on how to fix it? -
How to save data into two related tables in Django?
I'm new to Django and I'm following a tutorial to create a school system. I have a CustomUser that is related to three different tables by a OneToOneField(), when registering a user, depending on the type (HOD, teacher, student), I create two signals with @receiver to create an instance of the POST request and then save it in its respective table. Problem: When I try to save the data, I use a CustomUser object and call the create_user() class that I save in a user variable, but when I use that object to save other data from the table I need (Teachers in this case) the user is not created: def create_teachers(request): if auth_user(request) == True: # Do something for authenticated users. if request.method == 'GET': return render(request, 'create_teachers.html') else: try: user = CustomUser.objects.create_user( password='defaultPass', first_name=request.POST.get('first_name'), last_name=request.POST.get('last_name'), email=request.POST.get('email'), user_type=2, ) user.Teachers.address=request.POST.get('address') user.save() print('Professor created successfully') return redirect('/auth/create_teachers') except: print('Error creating teacher') return redirect('/auth/create_teachers') else: return redirect('../login') Error creating teacher [27/Sep/2024 13:46:14] "POST /auth/create_teachers HTTP/1.1" 302 0 [27/Sep/2024 13:46:14] "GET /auth/create_teachers HTTP/1.1" 200 34724 [27/Sep/2024 13:46:14] "GET /static/css/dist/styles.css?v=1727459174 HTTP/1.1" 200 54543 # admin.py class UserAdmin(BaseUserAdmin): ordering = ('email',) admin.site.register(CustomUser, UserAdmin) # managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email … -
Why does my Celery task not start on Heroku?
I currently have a dockerized django app deployed on Heroku. I've recently added celery with redis. The app works fine on my device but when I try to deploy on Heroku everything works fine up until the Celery task should be started. However nothing happens and I don't get any error logs from Heroku. I use celery-redis and followed their setup instructions but my task still does not start when I deploy to Heroku. Here is my code: heroku.yml: setup: addons: - plan: heroku-postgresql - plan: heroku-redis build: docker: web: Dockerfile celery: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn mysite.wsgi celery: celery -A mysite worker --loglevel=info views.py: from celery.result import AsyncResult task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) task.py: from celery import Celery app = Celery('transcribe')# @app.task def transcribe_file_task(path, audio_language, output_file_type, dest_dir, session_id): print(str("TASK: "+session_id)) #rest of code return output_file celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery("mysite") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I ensured that my CELERY_BROKER_URL and CELERY_RESULT_BACKEND are getting the correct REDIS_URL from environment variables by having it printing it's value before the task is to be started. So I … -
How to make a logout model that redirects the user to the homepage while keeping the language of the user. For example: /home/fr/ instead of/home/en/?
How to make a logout model that redirects the user to the homepage while keeping the language of the user class LogOut(Page): def serve(self, request): # Redirect to home page return HttpResponseRedirect('/home/') -
How to bundle all necessary dependencies in pyinstaller .exe file?
I have a typing game that is made using django and websockets ,I want to make ".exe file" to run this game on another pc that does not even have python installed !! I tried this code below and it worked only in my current working pc. Here is a Runner.py code that i used in the pyinstaller cmd import subprocess import time # Start the Django server subprocess.Popen(["python", "manage.py", "runserver"], shell=True) # Wait for the server to start time.sleep(5) # Open the webpage in Chrome chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe" # Adjust if necessary subprocess.Popen([chrome_path, "http://localhost:8000"]) # Adjust URL if necessary in the target pc only chrome opens but the server doesnt run thus python manage.py runserver is not working maybe cause the target pc doesnt even have python nor django installed ? and it cant find the manage.py file? so what im thinking is i need a way to bundle everything in a way that it workes on any device. Note : the pyinstaller cmd is pyinstaller --onefile --noconsole runner.py -
What would you say will be the best way to separate two different type of users to two different types of frontend/GUI?
So currently I am developing a project called manage+ using Django+React, I want to redirect them to different type of frontend?GUI based on their different type of roles, now what would you suggest I should do, do I make two completely different type of frontend, or any other idea or anything that you would suggest? I tried making two different frontend, and also did one logic which fetches the type of user from backend and then load the different frontend based on that user using some logic in frontend itself, but I think it is not very ethical or I should say it makes it slow I guess. -
how to show database data on a separate page
I am working on an activity tracker for my web development class and we're working with django. I'm trying to add a page that shows the activity details on a separate page by passing it's id into the url to display the activity info specific to that database object (similar to news articles on websites) I think the problem lies in my views page. I need help writing how to properly get the info from the database to pass over to the html form. The page loads fine with the id attached to the url but no info is showing views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from . models import Activity # Create your views here. def index(request: HttpRequest): activites = Activity.objects.all() return render(request, "activity/index.html", {"activites" : activites}) def new_activity(request: HttpRequest): if request.method == 'POST': params = request.POST activity = Activity( activity_name = params.get("activity_name") ) activity.save() return redirect("/") return render(request, "activity/new_activity.html") def activity(request: HttpRequest, id): id = Activity.objects.get(id=id) return render(request, "activity/activity.html") Here's what I have for the html page (open to renaming the data passed if necessary) activity.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>{{ activity.activity_name }}</h1> … -
Error 'CLR20r3' calling external aplication
I have a portal in Python 3.11 and Django 5.0.8 this portal in some point calls a external app developed in vb.net, this is the way i call the vb.net app subprocess.call('C:\\some\\Direction\\ExternalApp.exe', 'parameter1', 'parameter2', 'parameter3', 'parameter4', ...), i have tried the portal with IIS 10 on windows 11 and the python server and works fine, but when use in the IIS 10 on windows server 2022 standard gives me error, and using the python server on WS 2022 works fine, this is the error that shows me the event viewer: Aplicación: ExternaApp.exe Versión de Framework: v4.0.30319 Descripción: el proceso terminó debido a una excepción no controlada. Información de la excepción: System.IndexOutOfRangeException en System.Data.DataView.GetRow(Int32) en System.Data.DataView.get_Item(Int32) en ExternalApp.cls.function(Int32, Int32, Int32, System.String, System.String, System.String, System.String, System.String) en ExternalApp.DM1.Main() Nombre de la aplicación con errores: ExternalApp.exe, versión: 1.0.0.0, marca de tiempo: 0x66f5c058 Nombre del módulo con errores: KERNELBASE.dll, versión: 10.0.20348.2227, marca de tiempo: 0xe95c736c Código de excepción: 0xe0434352 Desplazamiento de errores: 0x000000000003f19c Identificador del proceso con errores: 0x3804 Hora de inicio de la aplicación con errores: 0x01db113917154b04 Ruta de acceso de la aplicación con errores: C:\some\direction\ExternalApp.exe Ruta de acceso del módulo con errores: C:\Windows\System32\KERNELBASE.dll Identificador del informe: c2dd5273-2d2d-4f89-9f3c-136d4f99f49a Nombre completo del paquete con … -
How to arbitrarily nest some data in a django rest framework serializer
An existing client is already sending data in a structure like… { "hive_metadata": {"name": "hive name"}, "bees": [{"name": "bee 1", "name": "bee 2", ...}] } For models like: class Hive(models.Model): name = models.CharField(max_length=32, help_text="name") class Bee(models.Model): name = models.CharField(max_length=32, help_text="name") hive = models.ForeignKey( Hive, help_text="The Hive associated with this Bee", on_delete=models.CASCADE ) The code that makes this possible manually iterates over the incoming data. I would like to rewrite it using a django rest framework serializer; however, the fact that hive_metadata is nested itself has stumped me so far. If I write class BeesSerializer(ModelSerializer): class Meta: model = models.Bee fields = ("name",) class PopulatedHiveSerializer(ModelSerializer): bees = BeesSerializer(many=True, source="bee_set") class Meta: model = models.Hive fields = ("name","bees",) would produce { "name": "hive name", "bees": [{"name": "bee 1", "name": "bee 2", ...}] } readily enough. I had hoped I could solve it with a reference to a sub-serializer, something like class HiveMetaDataSerializer(ModelSerializer): class Meta: model = models.Hive fields = ("name",) class PopulatedHiveSerializer(ModelSerializer): bees = BeesSerializer(many=True, source="bee_set") hive_metadata = HiveMetaDataSerializer(source=???) class Meta: model = models.Hive fields = ("hive_metadata","bees",) but I can't seem to figure out what to put in the "source" so that the same object is passed through the outer serializer into …