Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to download a file from S3 in django view?
The django view function downloads the files: def download(request): with open('path','rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name_edi return response This function downloads the files. But I want to download the files from S3. How to find the path of the S3 File so that this function works? -
How to create dynamic database per tenant for multitenant application in Django
I building an app which need to have separate database per customer using Django . In my backend , I want to develop this. I will access my database through API. but I can not find any good solution for it. I can not find yet any Django package for it. -
How to preview image before uploading in django
I am trying to preview image before uploading it to the html page. I am using django. This is my model class Product(models.Model): image = models.ImageField(upload_to='uploads/') thumbnail = models.ImageField(upload_to='uploads/') class Meta: ordering = ['-date_added'] this is my form.py class ProductForm(ModelForm): class Meta: model = Product fields = ['image'] and this is my html page <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.image.errors }} <br> <label for="{{ form.image.id_for_label }}"><br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;Image: &nbsp;</label> {{ form.image }} </div> <div class="field"> <div class="control" style="margin-bottom: 3%"> <button class="btn btn-theme" style="float:right;">SUBMIT</button> </div> </div> </form> I am able to upload and display the image in the html page but i want it so that before i upload i can see the image i am trying to upload. How can i do that? -
ProgrammingError at / not enough arguments for format string
I'm a Django beginner I'm trying to access a table which is already present in mysql database. for that I used - "python manage.py inspectdb" to get the model info as shown below` from django.db import models class Datatable(models.Model): def str(self): return self.ssid family = models.TextField(blank=True, null=True) validcopies = models.BigIntegerField(blank=True, null=True) location = models.TextField(blank=True, null=True) pool = models.TextField(blank=True, null=True) volume = models.TextField(blank=True, null=True) ssid = models.BigIntegerField(blank=True, null=True) cloneid = models.BigIntegerField(blank=True, null=True) savetime = models.DateTimeField(blank=True, null=True) clonetime = models.DateTimeField(blank=True, null=True) clretent = models.DateTimeField(blank=True, null=True) sumflags = models.TextField(blank=True, null=True) clflags = models.FloatField(blank=True, null=True) totalsize = models.BigIntegerField(blank=True, null=True) sumsize = models.TextField(blank=True, null=True) level = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) client = models.TextField(blank=True, null=True) vmname = models.TextField(blank=True, null=True) nfiles = models.BigIntegerField(blank=True, null=True) group = models.TextField(blank=True, null=True) backup_copy_cloneid = models.BigIntegerField(db_column='backup-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes1 = models.BigIntegerField(db_column='scanned-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes1 = models.BigIntegerField(db_column='post-seg-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. transferred_size_bytes1 = models.BigIntegerField(db_column='transferred-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. clone_copy_cloneid = models.BigIntegerField(db_column='clone-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes2 = models.BigIntegerField(db_column='scanned-size-bytes2', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes2 = models.BigIntegerField(db_column='post-seg-bytes2', blank=True, null=True) … -
django views can't access webkitformboundary
i'm trying to send data with ajax to django views here's my js code messageSENDER.onsubmit = () => { formdata = new FormData(messageSENDER); $.ajax({ headers: {"X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,}, method: 'POST', processData: false, ContentType: false, data: formdata, url : '/send/message/', success: function(m){ messageSENDER.reset() } }) } in the view function this is the data i get <QueryDict: {'------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name': ['"csrfmiddlewaretoken"\r\n\r\n7bsMDcWw2yme8P4FC7cEVnkrOuYLR22HFiyrxv9yTOE8rZzZkLta8DvKuf4SNMjt\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="partnerPK"\r\n\r\n2\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="content"\r\n\r\nmessage content\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="files"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a--\r\n']}> so how to access it's data the view is working just fine with normal html form and postman but not with ajax def CreateMessage(request): pk = request.POST.get('partnerPK') text = request.POST.get('content') partner = User.objects.get(pk=pk) m = Message.objects.create(content=text, receiver = partner, sender=request.user) when i try to print any of the data it says either None or gives empty array -
Rejecting form post after is_valid
I'm attempting to overwrite the RegistrationView that is part of django registration redux. https://github.com/macropin/django-registration/blob/master/registration/backends/default/views.py Essentially, I want to implement logic that prevents the registration from happening if some condition is present. Checking for this condition requires access to the request. I'm thinking that I might be able to subclass the register function within this Class based view. def register(self, form): #START OF MY CODE result = test_for_condition(self.request) if result == False: messages.error(self.request, "Registration cannot be completed.", extra_tags='errortag') return redirect('/access/register') #END OF MY CODE site = get_current_site(self.request) if hasattr(form, 'save'): new_user_instance = form.save(commit=False) else: new_user_instance = (UserModel().objects .create_user(**form.cleaned_data)) new_user = self.registration_profile.objects.create_inactive_user( new_user=new_user_instance, site=site, send_email=self.SEND_ACTIVATION_EMAIL, request=self.request, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) return new_user What is the correct way to do this using class based views? I've worked almost exclusively with function based views so far. Thanks! -
Problems getting while hosting django app on heroku
Hey there i have just hosted my Django app on Heroku and i faced theses two problem : "Failed to detect app matching no buildpack" Procfile declares types -> (none) and when i run heroku logs --tail i get this 2013-08-31T21:00:25.085053+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path=/favicon.ico host=cristowip.herokuapp.com fwd="189.137.81.39" dyno= connect= service= status=503 bytes= -
Application error - Deploying Django App on Heroku
I am trying to deploy My app on heroku. it is deployed successfully but when I am starting my app with provided link it is showing, Application error An error occurred in the application and your page could not be served. If you are the application owner This is logs which got after triggering heroku logs --app thefitlifegym command :- 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "/app/Gymnasium/wsgi.py", line 11, in <module> 2021-11-16T05:30:49.743963+00:00 app[web.1]: from notifications.config import get_notification_count, run_notifier 2021-11-16T05:30:49.743963+00:00 app[web.1]: File "/app/notifications/config.py", line 2, in <module> 2021-11-16T05:30:49.743963+00:00 app[web.1]: from members.models import Member 2021-11-16T05:30:49.743963+00:00 app[web.1]: File "/app/members/models.py", line 43, in <module> 2021-11-16T05:30:49.743964+00:00 app[web.1]: class Member(models.Model): 2021-11-16T05:30:49.743964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ 2021-11-16T05:30:49.743964+00:00 app[web.1]: app_config = apps.get_containing_app_config(module) 2021-11-16T05:30:49.743965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config 2021-11-16T05:30:49.743965+00:00 app[web.1]: self.check_apps_ready() 2021-11-16T05:30:49.743965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready 2021-11-16T05:30:49.743965+00:00 app[web.1]: settings.INSTALLED_APPS 2021-11-16T05:30:49.743966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ 2021-11-16T05:30:49.743966+00:00 app[web.1]: self._setup(name) 2021-11-16T05:30:49.743966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 64, in _setup 2021-11-16T05:30:49.743966+00:00 app[web.1]: raise ImproperlyConfigured( 2021-11-16T05:30:49.743968+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before … -
How to properly design my models for stock manage?
I am seeking for some guidance here. System will have three depart. Owner, ControlUnit, Shop Every depart will have there own stocks. And also shop may request order for stocks with ControlUnit and ControlUnit may request with Owner. Every depart will have there own damaged stock list also. I am thinking of this approach class Owner(models.Model): name = models.CharField() class ControlUnit(models.Model) owner = models.ForeignKey(Owner) name = models.CharField() class Shop(): cu = models.ForeignKey(ControlUnit) name = models.CharField() class CUStock(model.Model): cu_id = models.ForeignKey(ControlUnit) name = models.CharField() price = models.CharField() qty = models.PositiveIntegerField() class CUDamageStock(): cu_stock = models.ForeginKey(CUStock) qty = models.PositiveIntegerField() class CUOffer(): cu_stock = models.ForeignKey(CUstock) offer = models.DecimalField() class CUOrder(): cu_stock = models.ForeignKey(CUStock) qty = models.PositiveIntegerField() order_by_user = models.ForeignKey(User) Similary there will be another 3 table for Owner and Shop. -
Django can't ordering model object to ascending or descending
I am getting this error when trying ordering my model object. my console error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: contact.Contact: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). System check identified 1 issue (0 silenced). here is my model: class Contact(MPTTModel): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') name = models.CharField(max_length=250) email = models.EmailField(max_length=500) subject = models.CharField(max_length=2000,blank=True,null=True) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) class Meta: ordering = ('-created_at') where I am doing mistake ? -
How to reload a module in django?
I created a file named search_alg_parallel.py. Then I wanted reload this module from another module(another .py file). The problem is that I couldn't directly import the file with the import search_alg_parallel command, so I couldn't use the reload functionality. How can I solve this problem? I thinks this problem relates to django not python. -
What AWS Service I need for Docker Containers and team work
Right now I work as trainee in small IT Company I have a task to write a documentaion for other trainee "How upload our tg bot on AWS" & "How use Docker Containers in AWS" I don't have problems with Docker, because I have a lot of experience with it before, but I never work with AWS. It has a lot of service and I lost in them all What I need? Run a telegram-bot & Django server in Docker container Be able to have all trainee able to run their container Comfortable service to control containers Or if be simple, we need a AWS service to run a Docker Container which Run a telegram-bot and Django Server The question is: What service I need to work with? -
Excel export using loop in Django
I am working a project, which have some information about Customer. I am exporting Excel file using xlwt library. I have a booking list: [<Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>] My export function: def export_shimpent_xls(request,id): response = HttpResponse(content_type='application/ms-excel') shipment = Shipment.objects.get(pk=id) file_name = "shipment_list_of_"+str(shipment.shimpment_number)+".xls" response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Shipment Booking List') bookings_list = shipment.booking_list #taking existing booking list which is already added in shipment bookings = [] if bookings_list: for booking in bookings_list: data = Booking.objects.get(booking_reference=booking) bookings.append(data) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Ref Number', 'Name', 'Destination', 'Mobile Number', 'Weight','Carton','Payment Mode','Remark','Delivery Status',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() #issue is there, how can i itterate the bookings to get all value list? rows = Booking.objects.get(booking_reference=bookings).values_list('booking_reference', 'receiver_name', 'receiver_city', 'receiver_phone', 'gross_weight', 'total_carton', 'payment_method', 'comment', 'booking_status') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response I am having stuck on iteration for my bookings variable to get all value list in rows. How can i do that? Please? -
clicking on Anchor link does not jump down to the section of webpage
I have a blog website built using Django and Wagtail, where the blog article URL is http://example.com/posts/blog01 that blog has a few comments, and in HTML template file, each comment is given an id, <div id="c{{comment.id}}"> this is a comment for the blog article </div> But when I navigate to http://example.com/posts/blog01/#c12, it does not jump down to the comment whose id is 12, instead it just displays the blog article, and I have to scroll down to the specific comment. anything wrong for my setup ? -
SMTPDataError Django
I get this error (450, b'The given data was invalid. The from.email must be verified.') Everything was working fine before i changed the email configuration settings. Here is the settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mailersend.net' EMAIL_PORT = '587' EMAIL_HOST_USER = 'name@domain.com' EMAIL_HOST_PASSWORD = '***' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER Does anyone know why this error occurs and how to fix it? -
Does Javascript template Strings work inside Django templates?
I'm trying to dynamically change image source in javascript inside a Django templates file as follows image.src = `{{ static('images/Principle_Icon/Principle${index+1}.svg')}}`; console.log(`{{ static('images/Principle_Icon/Principle${index+1}.svg')}}`) but this doesn't seem to work since this is what I'm getting /static/images/Principle_Icon/Principle%24%7Bindex%2B1%7D.svg should I expect the javascript template string to work inside django templates? -
Social auth with mutation in Django
I'm trying to make social authentication for graphql, I'm using mutation to achieve but when i'm using qraph graph mutation I'll get below error: here is my mutation: mutation SocialAuth($provider: String!, $accessToken: String!) { socialAuth(provider: $provider, accessToken:"$accessToken") { social { uid extraData } } } and here is the error: { "error": { "errors": [ { "message": "Variable \"$accessToken\" is never used in operation \"SocialAuth\".", "locations": [ { "line": 1, "column": 41 } ], "extensions": { "exception": { "code": "GraphQLError", "stacktrace": [ "graphql.error.base.GraphQLError: Variable \"$accessToken\" is never used in operation \"SocialAuth\"." ] } } } ] } } already I have added everything that should be add in settings.py followed social-auth-app-django documentation. -
French locale is breaking button function
The problem Buttons are not functioning properly if a user is viewing the site in French locale. Background Info I am using {% trans %} tag to translate button text directly in my Django template. Inside of my script tags, I am also using {% trans %} tags to add translation after a button action is triggered (onclick): let show_correction = '{% trans "Show native corrections" %}';. In French locale it becomes: let show_correction='Afficher les corrections d'autres locuteurs natifs';. I think the issue is happening specifically in d'autres. My Guess Maybe the function is terminating earlier because of the apostrophe? How in the world can I fix this? -
Filter objects from a table based on ManyToMany field
I am working on a messaging app. The models are as follows. class ChatRoom(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE room_name = models.CharField(max_length=100, null=True, blank=True) participants = models.ManyToManyField(User) class Meta: db_table = TABLE_PREFIX + "chat_room" class Message(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE chat_room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) message = models.TextField() sent_by = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(default=django.utils.timezone.now) class Meta: db_table = TABLE_PREFIX + "chat_message" I have to filter ChatRoom object which contains a list of users. Eg: On sending data like this to the api { "participants": [2,3] } It should return a ChatRoom object which contains both user '2' and user '3' as participants. I had tried filtering it with room = ChatRoom.objects.filter(participants__in=serializer.validated_data['participants']) but it returns a list of room objects with user '1' and user '2'. I had also tried using get() but it returns an error. What am I doing wrong and how can i do it right? Thanks for looking into my problem. Hope you have a solution. -
502 Bad Gateway for NGINX USWGI and Django app
I am having issues running this locally. I have two containers in my app. The Django app and the nginx server. Below are the config files and dockerfiles. I am getting a 502 on the localhost:8000 and the error message is 2021/11/16 01:18:29 [error] 23#23: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.30.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://127.0.0.1:8888", host: "localhost:8000", referrer: "http://localhost:8000/" docker-compose.yml version: "3.9" services: web: build: . container_name: test_deploy_web hostname: blindspot command: uwsgi --ini uwsgi.ini volumes: - .:/app/ - staticfiles:/app/static/ nginx: build: ./nginx container_name: test_deploy_nginx volumes: - staticfiles:/app/static/ ports: - 8000:80 depends_on: - web volumes: staticfiles: app dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app RUN python manage.py collectstatic --noinput nginx dockerfile FROM nginx:latest COPY nginx.conf /etc/nginx/nginx.conf COPY my_nginx.conf /etc/nginx/sites-available/ RUN mkdir -p /etc/nginx/sites-enabled/\ && ln -s /etc/nginx/sites-available/my_nginx.conf /etc/nginx/sites-enabled/\ && rm /etc/nginx/conf.d/default.conf CMD ["nginx", "-g", "daemon off;"] my_nginx.conf # the upstream component nginx needs to connect to upstream blindspot { server 127.0.0.1:8888; #server unix:/app/app.sock; # for a file socket } # configuration of the server server { # the port your site will … -
django docker micro postgres server error :django could not translate host name "db" to address: Name or service not known
I know there is a similar question here. How do you perform Django database migrations when using Docker-Compose? But all no answer from that question solved my issue: I built a django project ,it works good at local env ,and also good if I let docker to connect my local db by setting host to: host.docker.internal But when I tired to convert the whole project to docker micro postgres server,after run: docker-compose build error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Here is my setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': '5432', } } dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py load_patient_data COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db db: image : postgres environment: POSTGRES_HOST_AUTH_METHOD: trust -
Django: Filter on related model's field not being equal to a specific value
Given these models: from django.db import models class Foo(models.Model): pass # table with only one column, i.e. a primary key 'id' of type integer class Bar(models.Model): value = models.TextField() foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bars') How to create a filter which returns all Foos related to at least one Bar with a non-zero value? I am aware that it is possible to at first select the non-zero Bars and then return the Foos related to them. But I am specifically looking for a solution which obtains the relevant Foos in a QuerySet directly. The reason is that it it could then easily be applied to relationships which are nested to a deeper level. What does not work It is straightforward to create a QuerySet which returns all Foos related to at least one Bar with a zero value: Foo.objects.filter(bars__value="zero") However, due to the lack of the "not equal" operator in Django's filter methods, it is impossible to do something like this: Foo.objects.filter(bars__value__not_equal="zero") # Unsupported lookup 'not_equal' for TextField Using exclude: Foo.objects.exclude(bars__value="zero") does not produce the desired output because it excludes all Foos which relate to at least one Bar with a zero value. So, if a Foo is related to two … -
How can I request an already logged in user to confirm password to enter a specific page in django?
I'm working on a django application. The application has a dashboard. How can i make it so that everytime the user wants to access the dashboard, he/she has to confirm their identity, with the same password they use to log into the same application? Thank you -
Extract keys from a Django JsonField when it is an Array using KeyTransform
When I have data like this, which represent the periodicity JsonField from the model Series: {'id': 20597, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-30', 'start_date': '2020-12-11'}]} {'id': 20596, 'periodicity': [{'period': 'weekly', 'end_date': '2021-03-05', 'start_date': '2021-03-05'}]} {'id': 20595, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-24', 'start_date': '2020-12-11'}]} {'id': 20593, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-24', 'start_date': '2020-01-27'}]} {'id': 18090, 'periodicity': [{'period': 'daily', 'end_date': '2021-06-04', 'start_date': '2012-01-03'}, {'period': 'weekly', 'end_date': '2021-08-30', 'start_date': '2020-12-14'}]} {'id': 18089, 'periodicity': [{'period': 'daily', 'end_date': '2021-06-04', 'start_date': '2012-01-03'}, {'period': 'weekly', 'end_date': '2021-08-30', 'start_date': '2020-12-14'}]} The problem as you can see, the JsonField is an Array of dict. I would like to extract all the end_date keys, even just as text. It seems like KeyTransform or KeyTextTransfom is not working when I do: Series.objects.annotate(end_date=KeyTransform("end_date", "periodicity")).values("id", "end_date", "periodicity") How can I get that? I want to get the oldest end_date from the array by the way. Impossible to find the solution using PostgreSQL or Django. -
django docker micro postgres server error:django could not translate host name "db" to address: Name or service not known
I built a django project ,it works good at local env ,and also good if I let docker to connect my local db by setting host to: host.docker.internal But when I tired to convert the whole project to docker micro postgres server,after run: docker-compose build error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Here is my setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': '5432', } } dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py load_patient_data COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db db: image : postgres environment: POSTGRES_HOST_AUTH_METHOD: trust