Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add paginator and filter in your website?
I'm doing a project in which I need to display cars and the user is allowed to filter their queries based on price, make, model etc. Earlier today the filter was not working but the Paginator was, but now, the filter is working and the paginator is not. I've been stuck on this the whole day and I don't know what else to do. This is my code: views.py def posts(request): cars = Userpost.objects.all() myFilter = UserpostFilter(request.GET, queryset=cars) cars = myFilter.qs p = Paginator(Userpost.objects.all(), 2) page = request.GET.get('page') cars_list = p.get_page(page) nums = "a" * cars_list.paginator.num_pages context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums} return render(request, 'store/userposts.html', context) userposts.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class = 'row'> <div class = 'col'> <div class = 'card card-body'> <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type = "submit">Search</button> </form> </div> </div> </div> <div class="row"> {% for car in cars %} <div class="col-lg-4"> <img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}"> <div class="box-element product"> <h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6> <hr> <a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a> <h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> <nav aria-label="Page navigation"> <ul class="pagination"> {% if cars_list.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1" aria-label="Previous"> <span … -
postgres setup error: "movie_dev" dosen't exist in TDD with Django, DRF and Docker
I tried "re-build image, run container and then apply migration" approach in the course (Test-Driven Development with Django, Django REST Framework, and Docker), but not work -
Django call save method passing related instance
Following on from this question, which I was unable to resolve, I've decided to try implementing a save method on the Asset class. After the Asset is created, the Trade instance needs to save the Asset that has just been created, and update additional fields from variables. I think that post_save will be the best method to use. In addition to this a related model on the Trade instance also needs to be updated. The instances are created using a Celery Task. How can the Trade instance be passed to the post_save method of the Asset class? Or is there a better way to implement the updating of related models? -
Celery unable to use redis
Trying to start Celery first time but issues error as below, i have installed redis and its starting fine , but still somehow django seems to have issues with it , File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/atif/Documents/celery_test/celery-env/lib/python3.8/site-packages/kombu/transport/redis.py", line 263, in <module> class PrefixedStrictRedis(GlobalKeyPrefixMixin, redis.Redis): AttributeError: 'NoneType' object has no attribute 'Redis' Celery.py from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_test.settings') app = Celery('celery_test',) app.config_from_object('django.conf:settings') # Load task modules from all registered Django apps. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Settings #celery stuff --------------- BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' celery_module/tasks.py from celery import Celery app = Celery('tasks',) @app.task def add(x, y): return x + y -
Django - Set ManyToMany attribute with empty list and serialize
I have this code below that sets relations tagged_users and hash_tags in a Post. It takes in the Post body and parses it for hashtags (Any word starting with a #) or a tagged_user (Any word starting with an @). Sometimes the post will contain neither, which causes an error at this line request.data['tagged_users'] = tagged_users. How do I resolve this so that it can be okay that it gives an empty list? view.py def request_to_post_data(request): post_text = request.data['body'] hash_tags_list = extract_hashtags(post_text) hash_tags = [HashTag.objects.get_or_create( hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags tagged_users_list = extract_usernames(post_text) tagged_users = list() for username in tagged_users_list: try: tagged_users.append(User.objects.get(username=username).uuid) except User.DoesNotExist: pass request.data['tagged_users'] = tagged_users serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): post_obj = serializer.save() create_image_models_with_post(request=request, post_obj=post_obj) create_video_models_with_post(request=request, post_obj=post_obj) return serializer serializer.py class PostSerializer(serializers.ModelSerializer): hash_tags = HashTagSerializer(many=True, read_only=True) class Meta: model = Post fields = ('creator', 'body', 'uuid', 'created', 'type', 'updated_at', 'hash_tags', 'tagged_users') models.py class Post(models.Model): # ulid does ordered uuid creation uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) hash_tags = models.ManyToManyField(HashTag) tagged_users = models.ManyToManyField(User) -
Setting up and calling a group of celery tasks with individual countdown
Using: Django==2.2.24, Python=3.6, celery==4.3.0 This is what I am currently doing: from celery import group the_group_of_tasks = group( some_task.s(an_object.the_data_dict) for an_object in AnObject.objects.all() ) the_group_of_tasks.delay() What I want to do: The group documentation: celery docs link I would like to spread the the_group_of_tasks individual some_task calls over some time range. Best if I can use the countdown feature, and spread the tasks over a variable number of seconds (like an hour, 3600 seconds). The distribution will be done to a random seconds integer between zero and 3600, imagine it can easily be calculated once I have the range. I think that I can add the countdown arg, with a random number generator within my range such that it will be "packaged" and ready to be executed in the group with the individual task preparation? some_task.s(an_object.the_data_dict, countdown=some_generator_call) Would that work? In case it helps, I am adding the code snippets for delay(), apply_async(), and Task.s(). Thank you! class Task(object): def apply_async(self, args=None, kwargs=None, task_id=None, producer=None, link=None, link_error=None, shadow=None, **options): """ Apply tasks asynchronously by sending a message. Arguments: args (Tuple): The positional arguments to pass on to the task. kwargs (Dict): The keyword arguments to pass on to the task. countdown … -
Django - Can I safely put information about is_staff in user model required fields to fetch them easily?
The problem is that I've tried to fetch info about user in react and the only fields that get returned from backend are the fields that are put in the required fields: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Provide an email!') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_staff'] def get_full_name(self): return self.name def __str__(self): return self.email Is it safe to do it like this or do I have to create separate api endpoint to return this information (I hope it is not necessary)? -
fixture not found using Factoryboy SubFactory
I'm getting an error building factories with subfactories to test django models. With models: class Space(ExportModelOperationsMixin('space'), models.Model): name = models.CharField(max_length=128, default='Default') class ShoppingListEntry(models.Model): food = models.ForeignKey(Food) space = models.ForeignKey(Space) class Food(models.Model): name = models.CharField(max_length=128) description = models.TextField(default='', blank=True) space = models.ForeignKey(Space) and fixtures: class SpaceFactory(factory.django.DjangoModelFactory): name = factory.LazyAttribute(lambda x: faker.word()) class FoodFactory(factory.django.DjangoModelFactory): name = factory.LazyAttribute(lambda x: faker.sentence(nb_words=3)) description = factory.LazyAttribute(lambda x: faker.sentence(nb_words=10)) space = factory.SubFactory(SpaceFactory) class ShoppingListEntryFactory(factory.django.DjangoModelFactory): food = factory.SubFactory(FoodFactory, space=factory.SelfAttribute('..space')) space = factory.SubFactory(SpaceFactory) and test def test_list_space(shopping_list_entry): assert 1 == 1 throws the following error Failed with Error: [undefined]failed on setup with def test_list_space(sle_1): file <string>, line 2: source code not available file <string>, line 2: source code not available E fixture 'food__name' not found I'm struggling to figure out how to troubleshoot this. -
Dash datatable wont render on page in django-plotly-dash
I am creating a web application using django_plotly_dash, a module combining Django, Plotly, and Dash into one package. I am having an issue where I can trying to load some dash datatables that are part of the dash app, but they never end up rendering on the page. The page is stuck on "Loading..." like so: As you can see, the middle of the page (starting from Home Page) is where the dash datatables are supposed to load, but the screen is stuck on "Loading..." from the log output after starting the app, it seems it has something to do with Django not locating the right static files. Here is the output below: Watching for file changes with StatReloader Performing system checks... C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_core_components package is deprecated. Please replace `import dash_core_components as dcc` with `from dash import dcc` return _bootstrap._gcd_import(name[level:], package, level) C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_html_components package is deprecated. Please replace `import dash_html_components as html` with `from dash import html` return _bootstrap._gcd_import(name[level:], package, level) C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format … -
Error running WSGI application, ModuleNotFoundError: No module named 'decouple' -- but module is installed
I've error with is "Error running WSGI application, ModuleNotFoundError: No module named 'decouple'" but i do have installed module. On the local version everything works fine with no errors, but when i put everything into pythonanywhere this erros starts to occur. requirements.txt asgiref==3.4.1 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.7 cryptography==35.0.0 defusedxml==0.7.1 Django==3.2.8 django-extensions==3.1.5 idna==3.3 oauthlib==3.1.1 Pillow==8.4.0 pycparser==2.21 PyJWT==2.3.0 pyOpenSSL==21.0.0 python-decouple==3.5 python3-openid==3.2.0 pytz==2021.3 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 sqlparse==0.4.2 urllib3==1.26.7 Werkzeug==2.0.2 manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookmarks.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() settings.py import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = ['mysite.com']#, 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django_extensions', ] MIDDLEWARE … -
Calling a function from another html template
So I have a base.html template and a review_result.html template that extends the base.html template. The base.html template has a script tag with lots of function. I am going to move a function called format from a script tag in the review_result.html to the base.html file. How do I then call the format function in review_result.html from base.html? -
Creating Django application inside of the project directory hierarchy?
In django rest framework quick start it creates the application inside of parent project directory instead of the top-level hierarchy for the sake of preventing conflicts with other packages. I'm asking is there any other benefit to this approach or on the other hand it will add overhead to the performance because of extra nesting? -
How to create users using Faker in Django Rest Framework
I am trying to create a fake user using faker and although the user instance is created I can't log in with its credentials. This is what my faker command looks like: from django.core.management.base import BaseCommand from faker import Faker from users.models import NewUser import random class Command(BaseCommand): help = "Command Information" def handle(self, *args, **kwargs): fake = Faker(["tl_PH"]) fname = fake.unique.first_name() lname = fake.unique.last_name() uname = "%s%s%d" % (fname.lower(), lname.lower(), random.randint(1000, 9999)) email = fake.unique.ascii_safe_email() password = "QaxSf96H" about = fake.sentence() newuser = NewUser.objects.create_user( first_name=fname, last_name=lname, username=uname, email=email, password=password, about=about ) newuser.save() -
Django - Error: NoReverseMatch at /post/.../ . Reverse for 'post_remove' not found
I'm working on my project "my-first-blog" and I'm totally stuck right now. I'm creating a blog with information about me for my portfolio. I've followed the Django tutorial and checked the code a hundred times but obviously there is something I'm missing. I'm creaing Delete Post. I'm getting an error when click on Title one of the blog: "Reverse for 'post_remove' not found. 'post_remove' is not a valid view function or pattern name." Can anybody see what I'm missing? Here you can see the full code https://github.com/valeriamilshtein/my-first-blog post_remove.html {% extends 'blog/base.html' %} {% block content %} <h1>Delete Post</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Delete</button> </form> {% endblock %} post_detail.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> <a class="btn btn-default" href="{% url 'post_remove' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaks }}</p> </div> {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), url(r'^post/(?P<pk>[0-9]+)/remove/$', views.post_remove, name='post_remove'), ] views.py from django.shortcuts import render … -
django custome aggregate function in MySQL
Trying to create custom aggregate function to calculate median price in my tables, my code look like this: from django.db.models import Aggregate, FloatField class Median(Aggregate): function = "percentile_cont" output_field = FloatField() template = "%(function)s(%(expressions)s)" but if i run this in my query i get 1305, 'FUNCTION DATABASE.percentile_cont does not exist') Some one can help me with this? I use MySQL server, not mariadb -
How do I use retrieve database data using a Django GET Form?
I am having a bit of trouble understanding how forms work in Django. I would like to retrieve information from my database and display it in a dropdown menu. When the user selects one of the items and submits their choice, the following page should display the contents of that item. In my example I have 'Workouts' that contain 'Exercises'. After selecting a Workout, the Exercises of that Workout should be displayed. The error I am receiving is this: NoReverseMatch at /routines/ Reverse for 'routine' with arguments '('',)' not found. 1 pattern(s) tried: ['routines/(?P<workout_id>[0-9]+)/$'] And here is where I believe the issue lays: routines.html <form action="{% url 'routine_workouts_app:routine' workout.id %}" method="get"> {% csrf_token %} {{ form.as_p }} <button name="submit">Make Workout</button> </form> I am having an issue with the action of the form. The error says that it can't find the routine.html template (which I have double checked and it is spelt correct and exists). I think this is because whatever I'm doing with 'workout.id' is incorrect but I don't know why. Below, I will show the corresponding url and view. If more information, such as the form.py file, is needed I will provide. views.py def routines(request): #as it is, there … -
How to see the common runserver log from django in heroku?
I am running a Django app on Heroku, and I am getting an error that I am not getting on my local machine. I am getting a 500 error. Normally, I just see the log Django outputs on the CMD, but I can't see it in Heroku. How can I do this? BTW, it is not a dependency cause I just pip freeze > requirements.txt. Thanks! -
compress with pyminizip and return to response
I am trying to compress data with pyminizip and return the data as response in a Django project as follows def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() pyminizip.compress(file_path, "members", response, "pass", int(1)) return response getting this error ValueError at /get_csv_file/ expected arguments are compress(srcfile, prefix, zipfile, password, compress_level) -
Problem passing dictionary to API via requests.post()
As noted below, I am trying to pass the dictionary data to the API. def create_flow_and_phases(request): data = { "name": "name_example", "description":"description_example", "category": 2, "precedents": [2,3], "users": [1], "phases": [{ "name": "phase_name", "description": "description name", "sequence_number": 1, "precedents": [1] }] } # Making a POST request to save flow_and_phases url = API_HOST + "/api/flows/save_flow_and_phases/" answer = requests.post(url, data=data, headers={'Authorization': 'Token ' + request.session['user_token']}) if not answer.ok: raise Exception("An error occurred while creating flow.") Below, you can see that the dictionary data format is the same one passed in Insomnia to the API and that it works perfectly. { "name": "Testando criação de fluxo pelo Insomnia", "description": "Fluxo teste simulando informações de trato e colheita de café na fazendo fictícia Quipo", "category": 2, "precedents": [2, 3], "users": [1], "phases": [ { "name": "Trato anual", "description": "Descrição teste fase 1.", "sequence_number": 1, "precedents": [] }, { "name": "Trato anual 2", "description": "Descrição teste fase 2.", "sequence_number": 2, "precedents": [1] } ] } The backend receives data as below flow_data = dict(data) # data is passed as parameter But when I go to run the debub, the data referring to phases are not passed to the API as shown in the screenshot below … -
Nginx is not passing Authentication to gunicorn socket
So I've basically set up my basic backend. Locally the api runs like butter but whenever I deploy the application to production, the API responds always with: "detail": "Authentication credentials were not provided." I think nginx is not passing the header correctly to my socket running gunicorn. But I don't know how I would pass the Header to the socket. The Authorization is a basic JWT Token, so: AUthorization: Bearer bla-blubb-i-am-a-token-420-69 This is my nginx setup: server { listen 80; server_name dev.website.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/platform/backend/static; } auth_basic "Admin Login"; auth_basic_user_file /etc/nginx/.htpasswd; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } What am I missing? -
How to.limit a users conten upload in django
Hello guys I want to restrict user, my I am working on a project in django where I have a producer model so I want to restrict the producer from uploading contents based on the particular package they're currently running on... Let's say if they subscribe to a pro package they can't upload more that 5 contents.. -
How to make a table only visible to a specific user in Django
So, I was studying Django and started doing some projects to fixate what I learned. I'm building a contact book like website and want to make each user have a unique Contacts table. I've tried putting this on models.py: class UserContatos(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Contato(models.Model): nome = models.CharField(max_length=255) sobrenome = models.CharField(max_length=255, blank=True) telefone = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField( default=timezone.now) descricao = models.TextField(blank=True) categoria = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) foto = models.ImageField(blank=True, upload_to='fotos/%y/%m/%d') def __str__(self): return self.nome contatos = Contato() class ContatoForm(forms.ModelForm): class Meta: model = UserContatos.Contato exclude = ('',) When I use this form to create a contact, it doesn't "go to the user". -
Export MUI components or style to use outside of React app
I'm facing a use case I'm not familiar with. I'm currently using MUI for a React application, but the authentication part is handled on another server, a Django application that includes Django OIDC Provider lib and which mostly consists in a sign in form that redirects the user to the React client upon sign in. The ultimate goal would be to have the same look and feel across both applications to provide a better user experience, I'm wondering what is the best solution for this: embed a full React application into the Django project and share the MUI theme across both application, seems to be the best choice for consistency but will be costly in term of development time and bundle size of the authentication app (basically loading React + MUI just for one page) trying to mimic the MUI components (mostly text fields, checkbox, buttons) with a pure CSS solution like https://github.com/finnhvman/matter which looks very nice, but it will take time to reproduce the main React app MUI theme, it will be harder to maintain and it will be hard to provide the exact same interactivity somehow find a way to export pure CSS with MUI theme style or … -
Django - Storing total API request from user, Limit and Filter it [Django Ninja]
I'm new to django, i'm currently working with API using Django Ninja Rest Framework. in this example, users will have a unique APIKey each time i create new APIKey from this model and attach it to selected user. this is my APIKey model : ### NOTE - This is just for testing, Not a real model, see the link below class APIKey(models.Model): key = models.CharField(max_length=64) # i know this should be unique, just for demo :) user = models.ForeignKey(get_user_model(), related_name='free_key', on_delete=models.CASCADE) label = models.CharField(max_length=40) revoked = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField(null=True, blank=True) This model is just for testing purposes, I actually use this for my project and modify it. So, My API endpoints need an API key for authentication (the API key that i have created that correspond to a specific user), so i implement and follow the steps here and it works normally My questions are : Each user has a unique API key. How to count and store the total request from a user each time user makes a request to an endpoint ? Should i add request_total field to my APIKey model or create a new Model ? Should i use custom middleware? or should … -
Django + nginx (with docker): erratic /admin redirects
So, I have a project that features a Docker deployment of a website with Nginx, Django served with Gunicorn + static files, and a Vue.js frontend (compiles to static files). The problem: When I try to access Django's admin interface, at http://localhost:8100/admin, I am redirected to https://localhost/admin/, which obviously fails. What I really want: First, for this to work. But I don't want to hardcode a website name (because it's an open source project), I don't want to force SSL, because I have a server where I'm going to deploy this behind another reverse proxy so that the website will be some subdomain on my server, under my certificates. So I want for both the Nginx and the Django layer to be as "dumb" as possible. To help debugging: docker-compose.yaml: version: "3" services: reverse-proxy: image: nginx:stable ports: - 8100:80 volumes: - frontend_data:/frontend/ - backend_data:/backend/ - ./nginx:/etc/nginx/conf.d depends_on: - backend frontend: # .... backend: build: context: ./backend dockerfile: Dockerfile entrypoint: ./entrypoint.sh stop_signal: SIGINT depends_on: - db volumes: - backend_data:/backend/ db: image: postgres:13-bullseye volumes: - postgres_data:/var/lib/postgresql/data/ volumes: # ... Nginx's config: upstream backend_server { server backend:8000; } server { listen 80; location /api { proxy_pass http://backend_server/api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; …