Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django IIS Deployment - HTTP Error 404.0 - Not Found
I need explanation on how to deploy Django Application on Windows IIS Server. I am struggling to follow the following tutorial I have a project which looks like this : [My_App] --> [My_App_Venv] --> [abcd] |-> manage.py |-> [abcd] |-> settings.py |-> [static] |-> ... [ example ] is used to represent folders I Need to understand how I should setup my IIS website : What should be FastCGI Application settings Full Path : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe Arguments : C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Environment Variables : 1. DJANGO_SETTINGS_MODULE : abcd.settings (I think this is ok) 2. PYTHONPATH : C:\xxxxx\My_App (I am not sure about this) 3. WSGI_HANDLER : abcd.wsgi.application (I think this is ok) Create and Configure a New IIS Web Site what should be the physical Path ? C:\xxxxx\My_App ? C:\xxxxx\My_App\abcd ? C:\xxxxx\My_App\abcd\abcd ? Configure the mapping module ## (which i assume is correct) Request path: * Module: FastCgiModule Executable : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe|C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Name : Django Handler output Hope someone can help to understand what I am doing wrong, I might use wrong path somewhere. Note : When I do By hand : cd C:/xxxxx/My_App/My_App_Venv .\\scripts\Activate cd.. cd abcd python manage.py runserver The website is well displayed on : http://127.0.0.1:8000/ -
jQuery loading animation not showing
I am attempting to follow the answer here to create a loading animation using jQuery: https://stackoverflow.com/a/1964871/23334971 Unfortunately, no loading animation shows for me and I'm not sure why. I am using Python/django for my server-side script. I'm not sure how to produce a minimal working example because the server side code takes a good few seconds to run. Maybe just replace it with a delay? I'm a complete noob so there's probably something obvious wrong with my code: This is my HTML: {% load static %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="{% static 'calculator/script.js' %}"></script> <link rel="stylesheet" href="{% static 'stylesheet.css' %}"> </head> <body> <article> <form id="calculatorForm"> <label for="num1">Numbers</label> <input type="number" name="number1" id="number1"> <input type="number" name="number2" id="number2"><br /> <button type="submit" role="button">Calculate</button><br /><br /> </form> <div class="modal"></div> <div id="result"></div> </article> </body> </html> stylesheet.css: (just copied and pasted from the linked stackoverflow answer) .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .8 ) url('https://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; } /* When the body has the loading class, we turn the scrollbar off with overflow:hidden */ body.loading .modal { overflow: hidden; } /* Anytime the body has the loading class, … -
how to present in Jinja2 notation groupedby dataframe to html template in Django
In Django view I have function where I got dataframe from QuerySet. def owner_observation_count(request): form = ReportForm(request.GET) context = {} if form.is_valid(): organisation = form.cleaned_data['organisation'] department_for_report = form.cleaned_data['department_for_report'] employee_total = Observation.objects.values('owner__last_name','owner__first_name', 'date_created__year','date_created__month').annotate(owner_count_2=Count('owner_id')) if organisation: employee_total = employee_total.filter(users_organization=organisation) if department_for_report: employee_total = employee_total.filter(users_department=department_for_report) employee_total_pd = pd.DataFrame.from_dict(employee_total) employee_total_pd["Emploeey"] = employee_total_pd["owner__last_name"].str.cat(' ' + employee_total_pd["owner__first_name"].str.get(0) + '.') employee_total_pd = employee_total_pd.drop('owner__last_name', axis=1) employee_total_pd = employee_total_pd.drop('owner__first_name', axis=1) emp_columns = {'date_created__year': 'Year', 'date_created__month': 'Month', 'owner_count_2': 'Qty'} employee_total_pd.rename(columns=emp_columns, inplace=True) which gives the result | Year | Month | Qty | Employee | |------|-------|-----|------------| | 2023 | 6 | 2 |Kefer A. | | 2023 | 9 | 1 |Napylov S. | | 2023 | 6 | 2 |Grosheva N. | | 2023 | 9 | 3 |Sapego G. | | 2023 | 8 | 3 |Danilin S. | | 2023 | 8 | 2 |Alekseeva L.| | 2023 | 8 | 2 |Smirnova E. | | 2023 | 7 | 1 |SHaripov R. | | 2023 | 9 | 14 |Lyalina L. | | 2024 | 8 | 2 |Husainov S. | | 2024 | 8 | 3 |Kachanova T.| | 2024 | 8 | 6 |Chistova V. | | 2024 | 6 | 1 |Vishnyakov M| | … -
Cant pass data to Chart.js with Django
Im using bootstrap template for my website and have problem to pass data from view in django to html to chart.js I tried to pass data like any other variable but it didnt worked. I cant see data I have 2 charts one (pie) with predefined data set and second (doughnut) i want to pass data from view, neither shows after render. What do i do wrong? View.py ctx = { "tournament": tournament, "pairing": pairing, "players_points": players_points, "army_points": army_points, "teamB": teamB, "form": form, "green": green, "yellow": yellow, "red": red, "green_p": green_p, "yellow_p": yellow_p, "red_p": red_p, "total": total, # "chart_data": chart_data, "chart_data": json.dumps(chart_data), } return render(request, "pairing5v5.html", ctx) html <div class="container-fluid pt-4 px-4"> <div class="row g-4"> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Pie Chart</h6> <canvas id="pie-chart" width="500" height="500"></canvas> </div> </div> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Doughnut Chart - {{ chart_data|safe }}</h6> <canvas id="doughnut-chart"></canvas> </div> </div> </div> </div> main.js // Pie Chart var ctx5 = $("#pie-chart").get(0).getContext("2d"); var myChart5 = new Chart(ctx5, { type: "pie", data: { labels: ["Italy", "France", "Spain", "USA", "Argentina"], datasets: [{ backgroundColor: [ "rgba(235, 22, 22, .7)", "rgba(235, 22, 22, .6)", "rgba(235, 22, 22, .5)", "rgba(235, 22, 22, .4)", "rgba(235, 22, 22, … -
Django (removal of .auth and .django tables that are created after migrate command)
I have these 10 tables in Django (6-Auth tables and 4 Django tables) I am not using these files in my production project, I thought of removing them but read that its not a good practice to remove. I am dealing with some million records(GET and POST operations), Will these tables effect my code performance in the long run? I have Tried removing these tables but all of them are interlinked with foreign keys. -
Is this proper way to handle all CRUD operations in a single view (endpoint) using HTMX?
I'm new to using HTMX with Django and I'm seeking guidance. I'm in the process of redesigning a large CRUD application, aiming to integrate HTMX for improved interactions. Given the complexity of the app and its interactions with the database across various models, I want to ensure I start off on the right foot by adopting HTMX best practices early on. I've seen in many tutorials that everyone follows the common practice of creating separate views and URL paths for each database transaction (such as create, edit, delete, update). As I think that this could result in a significant amount of additional code and time investment, I would prefer to put all of the application logic in just one view (or endpoint), for each model. Can you please suggest me if this is the right flow and right way to do it: def movie(request, template_name="movies.html"): movies = Movie.objects.all() movie_form = MovieForm(request.POST or None) if request.method == 'POST': action = request.POST.get('action') # 1) CREATE if action == 'add_movie': if movie_form.is_valid(): movie_form.save() content = render(request, 'partials/movie-table.html', {'movies': movies}) return HttpResponse(content, status=201, headers={ 'HX-Trigger': json.dumps({'create': movie_form.cleaned_data['name']})} ) else: content = render(request, 'error.html', {'error': movie_form.errors}) return HttpResponse(content, status=202) # 2) DELETE elif action == … -
Django Rest Framework basic set of APIs around authentication
I'm a django newby and I'm looking to expose basic services like: forgotten password, password change. I would expect to have those services for free but looking here and there it looks like we have to do them by hand, is that correct? Is there any explanation for that? -
I have been trying to runserver for my code but I keep getting this error
your text I'm trying to create a website using django but each time I runserver i keep getting this error message: TemplateDoesNotExist at / base.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.0.2 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\template\backends\django.py, line 84, in reraise Raised during: main.views.home Python Executable: C:\Users\Admin\KredibleConstructionWebsite\venv\Scripts\python.exe Python Version: 3.10.11 Python Path: ['C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\python310.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\Admin\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\Users\Admin\KredibleConstructionWebsite\venv', 'C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages'] Server time: Tue, 20 Feb 2024 09:17:47 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) Error during template rendering In template C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\main\home.html, error at line 3 your text what can I do to resolve this cos I have corrected the base.html file mutliple times and even changed the directory to templates\main\bas.html but it is not working -
POST http://localhost:8000/login/ 401 (Unauthorized)
I'm working on a React Typescript and Django application, but can't get the authification to work. I have spent hour upon hours on it, but can't fin a solution. Any help would be much appriciated. App.tsx import { useEffect, useState } from "react"; import { Home } from "./Home"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import { Login } from "./Login"; import Navbar from "./components/Navbar"; import axios from "axios"; export interface Movie { id: number; title: string; genre: string; year: number; } function App() { const [movies, setMovies] = useState<Movie[]>([]); const getMovies = async (): Promise<Movie[]> => { try{ const { data } = await axios.get<Movie[]>('http://localhost:8000/api/movies') setMovies(data) console.log(data) return data }catch (error){ console.error("error",error); return [] } } useEffect(() => { getMovies(); },[]) return ( <main className="bg-slate-500 p-60 min-h-screen"> <Router> <Navbar /> <Routes> <Route path="/login" element={<Login />} /> <Route path="/" element={<Home movies={movies} />} /> </Routes> </Router> </main> ) } export default App; Login.tsx import axios, { AxiosResponse } from "axios"; interface User { email: string; password: string; } async function logIn(e: React.FormEvent<HTMLFormElement>) { e.preventDefault(); console.log("Logging in"); try { const user: User = { email: "e@a.com", password: "hei" } const response: AxiosResponse = await axios.post('http://localhost:8000/login/', user, { withCredentials: … -
Python extension in VSCode cannot see virtual python
I working on a Django project. The problem I have is in the screenshot below: could not resolved from source I used "python3 -m venv env" to setup the virtual environment. I also installed Django with the "env" activated. Pip freeze confirms the installation: requirements VSCode cannot see virtual python Below is what I tried to fix this: Reinstalled VSCode Reinstalled the Python extension Manually selected the interpretor with the path "env/bin/python" using "Enter interpretor path..." The problems will not resolve. I've tried other questions that suggest to simply select to the right interpretor in the virtual environment folder. Didn't work. I noticed, when I created a virtual environment and activated it from the terminal in VSCode, VSCode did not automatically trigger the suggestion to use it. It's as if VSCode cannot see it at all. The packages in virtual environment clearly show Django was installed: Django installed Strangely, the same problem shows in Pycharm too. -
pyodbc, mssql-django Referencing row values by names in Django
In a test script, I can reference row values by name and the returned row type is "<class 'pyodbc.Row'>" import pyodbc SERVER = '' DATABASE = '' USERNAME = '' PASSWORD = '' connectionString = f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={SERVER};DATABASE={DATABASE};UID={USERNAME};PWD={PASSWORD}' connection = pyodbc.connect(connectionString) SQL_QUERY = "SELECT * FROM fund_performance" cursor = connection.cursor() cursor.execute(SQL_QUERY) records = cursor.fetchall() for r in records: print(type(r)) print(f"{r.fund}\t{r.nav}") However when I try the same code in a Django app, the row type is a tuple, and therefore I cannot reference the values by name. I am using mssql-django to connect, and same virtual environment for both and this is my django db config: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'db.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', }, }, } Is there a connection config that forces it to return a row object? or is there another way to return objects not tuples. -
Implementing Multiple Login/Signup Systems in Django for Different User Types
I'm working on a Django project (Food delivery app) where I need to implement multiple login/signup systems for three types of users (in single project): customers, sellers, and drivers. Each user type has its own set of models, such as Customer, Seller, Driver, along with related meta models like Seller Group / permissions / roles etc. Additionally, there are separate permission systems for each type. My goal is to have different login/signup methods for each user type. For example: Customers log in/sign up using mobile OTP. Sellers log in/sign up using a business email and password. I've organized my project into separate apps for each user type (customers, sellers, drivers), and I have custom user models.py defined in each app (AbstractUser, UserManager, PermissionMixins etc). But as per my knowledge, while using custom auth, I have to define AUTH_USER_MODEL in settings.py. where I can mention only one model. How can I implement these different login/signup methods and ensure that the authentication and authorization processes are tailored to each user type? Are there Django packages or best practices for handling such scenarios? Any guidance, code examples, or recommended resources would be greatly appreciated. Thanks in advance! -
How to use multiple database with Django and SQLAlchemy
Description: I have a Django application that currently stores data for multiple brands in a single database. Each brand's data, including user details and relevant information, is stored in separate tables within this database. However, I now have a requirement to migrate the application to use separate databases for each brand. Current Setup: One database containing tables for multiple brands. User details and relevant data for each brand stored in separate tables within this database. Desired Setup: Separate databases for each brand. User details and relevant data for each brand stored in their respective databases. Tools Used: Django for web framework. SQLAlchemy for database ORM. Alembic for database migrations. Key Questions: How can I configure Django to use separate databases for each brand? What changes do I need to make to SQLAlchemy models to support this new database structure? How should I handle database migrations using Alembic to ensure seamless transition to the new setup? Are there any best practices or potential pitfalls I should be aware of during this migration process? Currently, I'm following the simple technique to connect the single Database. engine = create_engine(<Database URL>) session = scoped_session(sessionmaker(bind=engine, autocommit=True)) Base.metadata.create_all(engine) Any guidance, examples, or resources would be greatly … -
Django translation issue for Marathi language
I have to translate the string in django, for table pagination “0 of %(cnt)s selected” in Marathi language . I am switch but when I am selected the thing from table it will automatically change into english. This not happen for hindi translation, Hindi translation works but the for the Marathi translation it's automatically change into english language how can solve this issue. I have taken this msgid from django admin locale file. When I am select anything from the table the pagination “0 of %(cnt)s selected” is in Marathi language. If I am selected anything from table it will not change automatically into english language. -
Error when removing/unregistering Groups: "django.contrib.admin.sites.NotRegistered: The model Group is not registered"
Note: I'm posting this question for completeness/more documentation. The error itself does not have a specific question asked about it, but there are answers if you look just one step further for it: Answer 1 & Answer 2. However, the answers are lacking depth so I'm hoping to provide some additional value by answering this question with more depth. If not appropriate, please feel free to comment and I'll remove. Context: I already had written some Django code for an app I'm building, but decided to follow this tutorial along and when I was trying to remove the Groups table from the Admin page, I stumbled upon this error: django.contrib.admin.sites.NotRegistered: The model Group is not registered and an initial Google search did not help quite well, but a search in SO's Django tag page lead me to this answer and everything was solved. I tried creating a new Django project and replicating the steps of the tutorial above but still got the same error. -
fill an admin panel field and then retrive it and use to fill another field
I have this admin.py code: class ElectionAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) print(obj.province) if obj: if form.base_fields['province']: form.base_fields['city'].queryset = City.objects.filter(province_id=form.base_fields['province']) else: form.base_fields['city'].queryset = City.objects.none() else: form.base_fields['city'].queryset = City.objects.none() return form and this models.py codes: class Province(models.Model): name = models.CharField(max_length=70, unique=True, null=True, blank=True,) class City(models.Model): province = models.ForeignKey("election.Province", on_delete=models.CASCADE) name = models.CharField(max_length=70, unique=True, null=True, blank=True,) class Election(models.Model): province = models.ForeignKey("election.Province", on_delete=models.SET_NULL, null=True, blank=True,) city = models.ForeignKey("election.City", on_delete=models.SET_NULL, null=True, blank=True,) how to change the get_form function in admin panel to fill province field and then retrieve it and use to fill city field (just show cities that belong to that province) with that get_form function I get this as output: None None -
How to add descriptive attribute when using ManyToManyField in django?
I am just trying to learn django. Sorry if this is a silly question. https://docs.djangoproject.com/en/5.0/topics/db/examples/many_to_many/ I was reading this documentation on ManyToManyField, it talks about two models Articles and Publishers. ` from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ["title"] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ["headline"] def __str__(self): return self.headline` Articles has a ManyToManyField 'publishers'. In the document it says the association table is created by django. Now how do I add descriptive attributes for example 'published date'? I have read this documentation. I want to know if there is a way to add descriptive attribute when using ManyToManyField. -
how to set CSRF cookie in nextjs for django
I'm new to Nextjs and I'm working on a frontend for my Django app here's my route.js that calls the django endpoint import { NextResponse } from 'next/server'; import axios from 'axios'; //import { cookies } from 'next/headers'; export async function POST(req: Request) { const { imageData } = req.body; try { //Django backend const response = await axios.post( 'http://localhost:8000/souci/capture/', { imageData } ); return NextResponse.json({response}); } catch (error) { console.error('Error sending image data to Django:', error); return NextResponse.json({ success: false, error: 'Failed to send image data to Django' }); } } export async function GET(req: Request) { //return } I'm currently getting this error on my Django console WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): /souci/capture/ [20/Feb/2024 04:55:44] "POST /souci/capture/ HTTP/1.1" 403 2870 how do I set the csrftoken in the POST function? I've tried a couple things include settings axios defaults axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" creating a cookie (though not sure how to add this to the POST request) cookies().set('csrftoken', 'souci', { maxAge: 60 * 60 * 24, //one day in seconds httpOnly: true, // prevent client-side access sameSite: 'strict', }); -
Error in connecting websockets when i push the code to server
I have implemented the Django Channel for the real time messages between Group users. It is working fine on the local system but when i push this to server, I am getting the error WebSocket connection to 'ws://nailsent.developmentrecords.com/ws/chat/13/' failed: Error during WebSocket handshake: Unexpected response code: 404 (anonymous) @ 13:465 This is my script <script> const currentDate = new Date(); // Get the month abbreviation const month = new Intl.DateTimeFormat('en-US', { month: 'short' }).format(currentDate); const day = currentDate.getDate(); const year = currentDate.getFullYear(); let hours = currentDate.getHours(); const ampm = hours >= 12 ? 'p.m.' : 'a.m.'; hours = hours % 12 || 12; // Convert 24-hour to 12-hour format // Get the minutes const minutes = currentDate.getMinutes(); // Combine all parts into the desired format const formattedTime = `${month}. ${day}, ${year}, ${hours}:${minutes} ${ampm}`; const card = document.querySelector('.card-body'); const sendMessageInput = document.getElementById('sendMessageInput'); const sendButton = document.getElementById('sendButton'); const group_id = "{{ group_id }}"; const userImg = "{{user_image}}" const username = "{{request.user.username}}"; const chatSocket = new WebSocket(`wss://${window.location.host}/ws/chat/${group_id}/`); chatSocket.onopen = function (event) { console.log('WebSocket connection established.'); }; document.addEventListener("keydown", (e)=>{ if (e.keyCode === 13){ sendMessage(); } }) // Event listener for send button click sendButton.addEventListener('click', sendMessage); scrollToBottom(); // Event listener for incoming messages if ("Notification" … -
How to run Django api's asynchronously
I have a long-running API in Django. When this long-running API is invoked by user1, the other APIs get blocked for user1 until that long-running API call gets resolved. But at the same time for other users, those APIs work well. class CreateOrderAPIView(APIView): def post(self, request): # Creates order # Some third-party services are invoked (Takes so long) return Response(order_data, status=201) Example Now, when the above API is called by user1, the other API calls get blocked for user1 until the long-running call is completed. However, the other users can invoke the APIs at the same time. I don't want to go with the celery/redis approach for my long-running tasks for now. Is there a way to resolve this issue? -
CSFR error when trying to use the django function send_email
I'm trying to send an email from Django running on AWSAppRunner resource. I know the email is the error since I have been testing it with and without it. It works when I comment the send_email function, and it does not work when I uncomment that function. I get a CSFR Error " Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - null does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in another browser tab or hitting the back button after a login, you may need to reload the page … -
guide me with learning Django 2024 version with resources
Certainly! Here's a suggestion you can post on Stack Overflow: "I've been following a 2023 Django tutorial series on YouTube but encountered persistent errors despite trying various troubleshooting methods. Could anyone recommend comprehensive learning resources or provide a roadmap for mastering Django? Any assistance would be greatly appreciated." -
launch.json unit-tests Django
I have made tests in Django, and configured launch.json to run from in vscode, but when I make an error in the tests, I get a red error warning. I would like to have an error in the tests, logging only in the console, as it happens in PyCharm, can this be done? My launch.json "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true }, { "name": "Cats Tests", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "test", "cats.tests" ], "django": true, } ] I also ran into the problem that my launch.json "type": "debugpy", kinda has "python", but when I write it, vscode says return as it was -
creating a virtual environment and file part onvscode
pipenv install django is not creating a virtual environment for me ,i am trying to create a virtual environment via my cmd on my windows , with the command "pipenv intall django", it install django but dont create the enironment , what should i do? and my file part seem not to be working pipenv intall django was supposed to download django and create an environment but it didnt ..... and copying and pasting a file part on my vscode it says invalid interpreter ....commmand used was "pipenv --venv..." got the file part and append bin\python but it didnt work -
Django / DRF: AttributeError: '__proxy__' object has no attribute '_delegate_text'
I am using Django==5.0.1 and djangorestframework==3.14.0 I have created a Django model that uses gettext_lazy for the verbose field name. However, when I try to serialize it using drf serializers.ModelSerializer and try to repr it, i get an AttributeError: 'proxy' object has no attribute '_delegate_text'. It seems that django.utils.functional used to have a class attribute cls._delegate_text that no longer exists. However, the smart_repr function in rest_framework.utils.representation is still trying to access it. Is this only relevant for the repr() function or would it effect my app otherwise? Does anyone know how to solve this issue? My model: from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): email = models.EmailField(_("email address"), unique=True) .... class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ["email", "first_name", "last_name"] read_only_fields = ["email", "first_name", "last_name"] DRF smart_repr: def smart_repr(value): if isinstance(value, models.Manager): return manager_repr(value) if isinstance(value, Promise) and value._delegate_text: value = force_str(value) value = repr(value) # Representations like u'help text' # should simply be presented as 'help text' if value.startswith("u'") and value.endswith("'"): return value[1:] # Representations like # <django.core.validators.RegexValidator object at 0x1047af050> # Should be presented as # <django.core.validators.RegexValidator object> return re.sub(' at 0x[0-9A-Fa-f]{4,32}>', '>', value) error code: serializer = CustomUserSerializer() print(repr(serializer)) Traceback (most recent call last): …