Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[Driver Manager]Can't open lib '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1'
When I run $ python manage.py inspectdb --database=mssql_database I have the following error django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1' : file not found (0) (SQLDriverConnect)") but the file libmsodbcsql-17.9.so.1.1 is there. $ cat /etc/odbcinst.ini [ODBC] Trace=Yes TraceFile=/tmp/odbc.log [FreeTDS] Description=TDS driver (Sybase/MS SQL) Driver=libtdsodbc.so Setup=libtdsS.so CPTimeout= CPReuse= UsageCount=2 [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1 UsageCount=1 $ odbcinst -j unixODBC 2.3.7 odbcinst: symbol lookup error: odbcinst: undefined symbol: odbcinst_system_file_name -
Upload a file in a folder whose value is selected through a list of choices
I have the following Script model : from django.db import models import os def getListOfFiles(dirName): listOfFile = os.listdir(dirName) allFiles = list() for entry in listOfFile: fullPath = os.path.join(dirName, entry) if os.path.isdir(fullPath): allFiles.append((fullPath, entry)) return allFiles class Script(models.Model): script_name = models.CharField(max_length=200, blank=True) folder = models.CharField(choices=getListOfFiles('media/scripts'), max_length=200) file = models.FileField(upload_to=f'scripts/{folder}') def __str__(self): return self.script_name I want to upload the script to the value of the attribute folder selected by the user through a list of choices. With the upload_to=f'scripts/{folder}' it tries to upload it to media\scripts\<django.db.models.fields.CharField> which is obviously not what I want. I saw a bunch of people using a get_folder_display() function but is doesn't seem to work in models, or I did it wrong. How can I get the value of folder selected by the user ? -
code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level
code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level.code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level. Here is My model.py using the Django-rest framework. I want to update aailable_seats(class Flight) after passenger details(No .of passengers) details added. import email from pyexpat import model from django.db import models GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) # Create your models here. class Airport(models.Model): Airport_name=models.CharField(max_length=100) country=models.CharField(max_length=100) def __str__(self): return self.Airport_name class Flight(models.Model): # f_id = models.UUIDField(primary_key=True) # a_id = models.UUIDField() flight_number = models.CharField(max_length=100,unique=True) depart_date_time = models.DateTimeField(auto_now_add=True) arrival_date_time = models.DateTimeField(auto_now_add=True) origin = models.CharField(max_length=100, blank=True, default='') destination = models.CharField(max_length=100, blank=True, default='') price = models.IntegerField() airline_name = models.CharField(max_length=100, blank=True, default='') total_seats = models.IntegerField() available_seats = models.IntegerField() #code = models.TextField() airport=models.ForeignKey(Airport,on_delete=models.CASCADE) def __str__(self): return str(self.flight_number) # def user_count(self): # return "Available Seats: " + self.available_seats.count + "Total Seats: " + self.total_seats.count class User(models.Model): name = models.CharField(max_length=100,blank=True, default='') contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100,blank=True, default='') email = models.EmailField(max_length=254) password = models.CharField(max_length=100,blank=True, default='') state=models.CharField(max_length=100,blank=True, default='') city=models.CharField(max_length=100,blank=True, default='') country=models.CharField(max_length=100,blank=True, default='') pincode= models.IntegerField() dob = models.DateField() … -
In GeoDjango, use GeoModelAdmin as a StackedInline in the Django Admin
I am trying to use the GeoModelAdmin as a StackedInline in the Django Admin panel. I have seen these two similar questions: GeoDjango: Can I use OSMGeoAdmin in an Inline in the User Admin? django admin inlines with GeoModelAdmin The answer that recommends inheriting from both GeoModelAdmin and StackedInline almost works. The following code: models.py: class SomeGeometry(gis_models.Model): geometry = gis_models.GeometryField(blank=False, null=False) some_model = models.ForeignKey("somemodel", blank=False, null=False, on_delete=models.CASCADE, related_name="geometries") class SomeModel(models.Model): name = models.CharField(max_length=255) admin.py: class SomeGeometryAdminInline(gis_admin.GeoModelAdmin, admin.StackedInline): model = SomeGeometry extra = 0 fields = ( "geometry", ) def __init__(self, parent_model, admin_site): # InlineModelAdmin.__init__ self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) # BaseModelAdmin.__init__ overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): fields = ("name",) inlines = (SomeGeometryAdminInline, ) Correctly shows an editable geometry widget. But there is no "add another model" link at the bottom of the inline formset. Any hints as to how to get that link back? -
Django Rest Framework import OpenAPI spec from other service to generate Schema
My system consists of multiple services that generate their own OpenAPI specifications. For one endpoint in my Django service I want the input schema to be of a type that is specified at another service, is there somehow a way to retrieve/import/reference to a type that is part of another service? (Currently just using the schemas from DRF but thinking of using drf-spectacular) In the end I want the services to dynamically generate full OpenAPI specs (and sometimes those can be based on each other) -
CreateView show blank - Django
I did as "docs.djangoproject.com" says, add Templates in setting.py file, base.html file works ok, then created my accounts app then views, after that urls and main app urls.py file. everything works ok, without any errors, but the signup and login page doesn't show anything! could anyone help me? accounts[app] > models.py: accounts[app] > models.py accounts[app] > views.py: accounts[app] > views.py accounts[app] > urls.py: accounts[app] > urls.py accounts[app] > forms.py: accounts[app] > forms.py -
Iam Passing an value when iam redirecting the template in django
Iam New to Django.. I created Login Page and i submited that page it goes to another page i want that particular username in another page so iam passing that name when iam redirecting the page but it does'nt worked for me... urls.py from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('dash/',views.Dash,name='Dash'), ] Dash.html <div class="flex-grow-1"> <span class="fw-semibold d-block">{{name}}</span> </div> views.py def Login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: request.session['user'] = username auth.login(request,user) return redirect('/dash',{name:user}) This is my code why iam not getting the name ? Please anyone help me -
django admin not displaying styles
i would like to deploy django in a kubernetes cluster but now i am struggling with the django admin static files. As you can see in the screenshot below, the browser receives the static files for the admin page correctly but not display it. What is a reason for this behavior and how can i fix it? I try it multiple times with debug on and off and in incognito window. -
Initial state in react redux are upadating after hard refresh instead on button click
I am trying to build a login page that uses simple JWT of django rest framework for authentication and react js as frontend and redux for state management. i am storing the user info in local storage and the initial state is updated from the local storage . I want to update the initial state on button click but it only updates after hard refresh . All the files used are below: UserReducer.js import axios from 'axios' import { USER_LOGIN_SUCCESS , USER_LOGIN_REQUEST , USER_LOGIN_FAIL , USER_LOGOUT , } from '../constants/userConstants' export const login = (email , password ) => async(dispatch) => { try{ dispatch({ type: USER_LOGIN_REQUEST }) const sdata = { headers: { 'Content-type': 'application/json' } } const {data} = await axios.post('/api/users/login/' , { 'username': email , 'password': password} , sdata ) localStorage.setItem('userInfo' , JSON.stringify(data)) dispatch({ type:USER_LOGIN_SUCCESS , payload:data }) dispatch({ type: USER_LOGOUT, payload: {} }) }catch(error){ dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } Store.js import {createStore , combineReducers , applyMiddleware} from 'redux' import thunk from 'redux-thunk' import {composeWithDevTools} from 'redux-devtools-extension' import {productListReducer} from './reducers/productReducers' import { productDetailsReducer } from './reducers/productReducers' import { cartItemReducer} from './reducers/cartReducers' import { userLoginReducer } from './reducers/userReducers' const … -
django download a file filtered from a list of files
I'm working on a website where I have multiple excel files uploaded by users and stored in the DB, then a user chooses a file's name and date from a dropdown list and this specific file should be downloaded to him. right now I can get the File object that he requested but can't download it correctly. This is my Models.py class File(models.Model): file_name = models.TextField(max_length=1000, default='myFile') created_at = models.DateTimeField( default=datetime.datetime.now().replace(microsecond=0)) file = models.FileField() file_class = models.CharField( max_length=20, default='') def __str__(self): return self.file_name This is the part where I store the file in Views.py: modelFile = File() now = datetime.datetime.now().replace(microsecond=0) file_class = request.POST['select_course'] Fname = request.POST['file_name'] myFile = convertToBinaryData(uploaded_fileName) xlfile = ContentFile(myFile) modelFile.file.save(Fname, xlfile) modelFile.file_class = file_class modelFile.created_at = now modelFile.file_name = Fname modelFile.save() And here is where I retrieve and download the file in Views.py : def viewTrial(request): if request.method == "POST": chosen_filename = request.POST['select_trial'] chosen_date = request.POST['select_trial2'] date = pd.to_datetime( chosen_date, infer_datetime_format=True).strftime('%Y-%m-%d %H:%M') FileToView = File.objects.filter(created_at__contains=date).filter( file_name__contains=chosen_filename) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=%s' % chosen_filename+".xls" return response else: return render(request, "model/trials.html", {}) this code downloads an excel file with only the file name written in it, I've seen multiple questions here regarding this issue and the downloading, … -
Adding Legacy sqlite3 db to Django model with no primary key
I am adding a legacy sqlite3 db with 6 tables. 3 of those tables have a primary key field and I am able to access the data via the admin panel... all good However, the other 3 do not have a primary key column which is giving me an error no such column: table1.id when i try to access the table via the admin panel. I have found the sqlite3 adds a hidden rowid to all tables so I am able to access the rowid by using select rowid * from table1 So I tried adding the rowid as a field in the table1 Model like this: class table1(models.Model): rowid = models.IntegerField(primary_key=True, editable=False) order_id = models.ForeignKey(Demand, null=True, on_delete= models.SET_NULL) product_id = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField(default=1) Now when i try running ./manage.py makemigrations I run into an issue saying: It is impossible to add a non-nullable field 'rowid' to table1 without specifying a default. This is because the database needs something to populate existing rows But from my understanding, the database already has the rows populated.. so i'm not sure whats happening. Any help is appreciated! The only thing i've found online that relates to this is a … -
In Django, how can I select multiple list_filter elements
I have one model called CLUB, and another called DIVISION. Club has a manytomany field with division. The point is that I want in the admin panel where I see the clubs to be able to filter by more than one division. I have been looking for but nothing seems to work, there is a old library but is deprecated. Thanks! -
How to get always get last record
class PettyCashListAPIView(ListAPIView): pagination_class = CustomPagination permission_classes = [IsAuthenticated,] serializer_class = serializers.PettyCashSerializer def get_queryset(self): data = center_models.PettyCash.objects.filter(allowance_to=self.request.user.paneluser) return data Lenght of data has more than one. But I want to return only the latest record. PettyCash model has created_at DateTimeField. I tried latest('created_at), last() but getting PettyCash has not len() error. Any Help. Thank you !! -
How to change swagger logo and text in the top bar in django app?
I have included swagger the following way in the Django app schema_view = get_schema_view( openapi.Info( title="Calculate", default_version="v1", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("", schema_view.with_ui("swagger", cache_timeout=0), name="swagger"), How can I change the top bar logo and text? from "Swagger - supported by SMARTBEAR" to "Smart Calculator" -
how to access django bash in portainer?
I am able to access the django docker using the following in the cloud console docker exec -it backend bash How can I do the equivalent in Portainer GUI? It is just stuck in Exec into container as default user using command bash -
Check cell value, recalculate and overwrite xlwt
Trying to achieve the following: Loop through a list with this type of objects: #1 Cost: 12 Unit: per month Amount: 3 users #2 Cost: 32 Unit: per quarter Amount: 2 users etc And make a forecast xls export based on this for each month: Jan - 100 (312 + 322) Feb - 36 (312) March - 36 (312) Apr - 100 (312 + 322) etc My implementation of this was as follows: for po in queryset.select_related( 'quote__relatie', 'entity', 'delivery_address', 'requester', 'approver',): row_num += 1 ws.write(row_num, 0, str(po.costcode), font_style) ws.write(row_num, 1, str(po), font_style) ws.write(row_num, 2, str(po.quote.relatie), font_style) ws.write(row_num, 2, str(po.project), font_style) for cl in po.inkooppost_set.all(): data = {} if cl.eenheid.recurrent: for pc in range(cl.aantal): if cl.invoice_date: invoice_date = (cl.invoice_date + datetime.timedelta( days=(pc * cl.eenheid.frequency))) #find columnnumber r = relativedelta(invoice_date, month.order_date) col_num = (r.years*12) + r.months + 3 #check whether another cost has been inferred and update cell print(col_num) if data.get(col_num): data.update({col_num: data.get(col_num) + cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs}) ws.write(row_num, col_num, data[col_num], font_style) else: invoice_date = cl.invoice_date r = relativedelta(invoice_date, month.order_date) print(r) col_num = (r.years *12) + r.months + 3 print(data.get(col_num)) if data.get(col_num): data.update({col_num: data.get(col_num)+ cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs * cl.aantal}) ws.write(row_num, col_num, (cl.eenheidprijs * cl.aantal), font_style) Using a dict to build … -
Error while generating FCM token using django
This is error that i am getting in my javascript console An error occurred while retrieving token. DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. at https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js:1:25606 I am trying to send push notification from firebase but getting error. any one plz help me. i am trying to generate FCM token in javascript console but getting error here is my index.html file where i am getting import error index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-analytics.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js"></script> {% comment %} <script src="/static/js/firebase-messaging-sw.js"> {% endcomment %} <script> var firebaseConfig = { apiKey: "AIzaSyAcV-zkELH2kC2ylNcqfxcAF9LLmyJW3n8", authDomain: "fir-push-notification-ca088.firebaseapp.com", databaseURL: "https://fir-push-notification-ca088-default-rtdb.firebaseio.com", projectId: "fir-push-notification-ca088", storageBucket: "fir-push-notification-ca088.appspot.com", messagingSenderId: "123105123891", appId: "1:123105123891:web:59c426864dd7b8c35ecd46", measurementId: "G-NEZ3NC2GYL" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); const messaging = firebase.messaging(); console.log(messaging.getToken()) messaging.getToken({ vapidKey: 'AAAAHKmjHjM:APA91bEWX1Mrp6HIfjx6Y4n2chW2GpfB3GzrwQp1T1KQ3i5a_4mVnEhEa_hd95c-N9ZADi8fTUobdhlvs5d0b1JMrYWE_sJ1KjsdnXLMg4rxOAFPem4nxpazNtimZEb2PGKtHZAB9sKX' }).then((currentToken) => { if (currentToken) { console.log(currentToken) } else { console.log('No registration token available. Request permission to generate one.'); } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); }); messaging .requestPermission() .then(function () { console.log("Notification permission granted."); return messaging.getToken() }) .catch(function (err) { console.log("Unable to get permission to notify.", err); }); messaging.onMessage((payload) => { console.log('Message received. … -
Get sub One To Many relation from specific model in django
I have two models User and Sale, each sale has a buyer and a seller. I would like to get all buyers (also Users) from a specific user my_user. class User(models.Model): name = models.CharField(max_length=250, default='', blank=True) # more fields.... class Sale (models.Model): buyer = models.ForeignKey( User, blank=False, null=False, related_name='purchases', on_delete=models.CASCADE, ) seller = models.ForeignKey( User, blank=False, null=False, related_name='sales', on_delete=models.CASCADE, ) # more fields.... This works fine: User.objects.filter(purchases__seller = my_user) But I would like to know if there is a way to do it by using the my_user object directly. Something like this my_user.sales.buyer Thanks in advance guys -
What should i do to learn django-ninja
I am a beginner in programming, I'm trying to learn Django-ninja but I'm confused, what should I learn first, I know some basics of python. Will I need to learn Django first? I will be thankful if anyone have a map learn that leads to Django-ninja -
How to backup user files before pulling repository in jenkins
I have a django project which is deployed in a docker container. I created a pipeline in jenkins triggered via github webhooks. Everyting works fine but I have some user files in project directory which I want to backup before jenkins pull the repository. Is there a way to add a pre build step to my pipeline script or avoid deleting files when running git pull command ? -
django redirect to form view and autofill with previously entered values
I have following scenario. User fills out a form If the user clicks the "continue" button and the form is valid the user will be redirected to a summary view In the summary view the user checks the input again. He can either continue or go back. If he continues the data will be saved in the database, if he goes back he can edit the form. Since in step 4 the user is at the view summary I have to redirect him to the home view. I don´t want the user to fill out the entire form again, the previously entered data should be autofilled if he goes back. Something special: I am using django-tagify2 for one input in the form to get tags rather then text. If the user goes back the tags should be rendered correctly in the tagify specific form. So here are my files: home.html {% extends "messenger/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="message-container"> <form method="POST" autocomplete="off"> {% csrf_token %} {{ form|crispy }} <button name="sendmessage" class="btn btn-outline-info" type="submit">Continue</button> </form> </div> {% endblock content %} summary.html {% extends "messenger/base.html" %} {% block content %} <h4>Zusammenfassung</h4> <p><b>Empfänger: </b>{{ receiver }}</p> <br> <p><b>Betreff: … -
Upload file to server temporarily to process it from django
I am developing a website in django which will convert one file type to another. Main core logic of conversion is done in python, but now as for website, the file needs to be uploaded temporarily on the server, so that server can do the conversion and produce new file to be downloaded. How is this to be accomplished? -
How can I serialize one to many models in Django Rest?
So I have two models Invoice and Items. Invoices can have many Items. Here's how they are defined: class Invoice(models.Model): customer_name = models.CharField(max_length = 200, verbose_name='Customer Name') customer_phone = models.IntegerField(null = True, blank = True, verbose_name='Customer Phone') customer_address = models.TextField(null = True, blank = True, verbose_name='Customer Address') invoice_id = models.UUIDField(primary_key = True, unique = True, default=uuid.uuid4, verbose_name='Invoice ID') invoice_date = models.DateField(auto_now_add=True, verbose_name='Invoice Date') def __str__(self): return self.customer_name + ' - ' + str(self.invoice_id) class Meta: verbose_name = 'Invoice' verbose_name_plural = 'Invoices' class Items(models.Model): invoice = models.ForeignKey(Invoice, on_delete = models.CASCADE, related_name='invoice') item_name = models.CharField(max_length = 200, null = False) item_quantity = models.IntegerField() item_price = models.IntegerField() item_id = models.AutoField(primary_key=True) def __str__(self): return self.item_name class Meta: verbose_name = 'Items' verbose_name_plural = 'Items' I want to implement two API endpoints, one to get the list of invoices, and another to get a specific invoice with its items. For example, /api/ will return all invoices [ { "customer_name": "John Doe", "customer_phone": 111666, "customer_address": "Palo Alto, California", "invoice_id": "a8aeb5a8-5498-40fd-9b4f-bb09a7057c71", "invoice_date": "2022-05-04" }, { "customer_name": "Cassian Green", "customer_phone": 111000, "customer_address": "2112 Illinois Avenue", "invoice_id": "7d7b7878-3ffc-4dd2-a60a-fa207c147860", "invoice_date": "2022-05-04" }, { "customer_name": "Chelsea Davis", "customer_phone": 666777, "customer_address": "2260 Coplin Avenue", "invoice_id": "3dda2054-49d7-49dc-9eba-ddc0fdacfd3b", "invoice_date": "2022-05-04" }, { "customer_name": "Derek Elliott", … -
access variable in template from views.py - Django
This is my first time messing with django and I am having trouble passing variables from a view function to a template html file. views.py def index(request): try: ms_identity_web.acquire_token_silently() authZ = f'Bearer {ms_identity_web.id_data._access_token}' graph_user_picture = requests.get(settings.USERPHOTO, headers={"Authorization": authZ}) file = open("Sample/static/user_iamge"+str(ms_identity_web.id_data.username).split(" ")[0]+".png", "wb") file.write(graph_user_picture.content) file.close() clamdata = context_processors.context(request) print(clamdata["claims_to_display"]["preferred_username"]) userdata = requests.get(settings.ENDPOINT+"/"+clamdata["claims_to_display"]["preferred_username"], headers={"Authorization": authZ}).json() print(userdata) return render(request, "flow/index.html", userdata) except Exception as e: print(e) return render(request, "flow/start.html") and I am trying to send userdata over to index.html like so: <div class="ms-Persona-details"> <div class="ms-Persona-primaryText">{{ userdata["displayName"] }}</div> <div class="ms-Persona-secondaryText">{{ userdata["jobTitle"] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["businessPhones"][0] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["userPrincipalName"] }}</div> </div> However, I am getting either no variables showing up on the screen or I get an error like this: Could not parse the remainder: '["displayName"]' from 'userdata["displayName"]' I assume I am missing something basic in index.html to pass variables from the views.py to the index.html file -
I use Django with PostgreSQL on docker compose, but django-test can't access database
I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: context: . container_name: web restart: unless-stopped tty: true working_dir: /opt/apps volumes: - .:/opt/apps/ - .pgpass:/root/.pgpass - .pg_service.conf:/root/.pg_service.conf entrypoint: "./entrypoint.sh" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres container_name: db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - ${DB_PORT}:5432 volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: networks: django-tutorial: compose .env file DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 .pg_service.conf [DB] host=db user=postgres dbname=django_tutorial port=5432 .pgpass db:5432:postgres:postgres:postgres When docker-compose up -d is executed with the above configuration and python manage.py migrate is executed, the migration is performed no problems and the database is accessible. However, when I try to run the test as in python manage.py test polls, I get the following error. (The test is the same as the code in the link at the beginning of this article.) Do I need any additional configuration for the test DB? docker compose exec web python manage.py test polls ✔ 15:20:03 Found 1 test(s). Creating test …