Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image not shown in debug for false in django
I want to run always in debug=false in django. However, it works only when i turned to debug to true. Otherwise not. In setting.py DEBUG = False also, in setting.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In main urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('mysite.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have directory of media, static, staticfiles in the directory where manage py is located. If i put code exactly in apache will my code works. P.S In development also i want to fix debug as false always. -
passing websocket messages from django consumers.py to html, then respond back to backend
The problem i'm having is The only way i can find to pass messages from consumers.py which recieves the message to index.html where its needed is with this line. async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) this sends the message to index.html AND back to my backend... i dont want it to bounce the message back to my backend. how can i send a response back to my backend from index.html because i need to send info on what the user has entered into an in? here is an example of how the system currently works how websockets currently work and heres how i want them to work how i want websockets to work how can i stop bouncing the message back to my backend and still pass the message onto my html, then respond from my html back to my backend? ################ below is the code js in my index html const colorSocket = new WebSocket( "ws://" + window.location.host + "/ws/endpoint/chat/" ); colorSocket.onopen = function() { console.log("Connected! (" + this.readyState + ")"); }; colorSocket.onmessage = function(event) { let data = JSON.parse(event.data); console.log(data.message); // etc........... } consumers.py import json import random from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class … -
Django template: Set same data in tables cell matching to header
I have below view.py c0 = date.today().replace(day=16) c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) datadump = data.objects.filter(user=request.user,ret_prd__gte=datetime.now() - relativedelta(months=5)).order_by('type','user','-ret_prd') return render(request,'rethome.html',{'datadump':datadump,'c0':c0,'c1':c1,'c2':c2,'c3':c3,'c4':c4,'c5':c5}) And below template code: {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> <table> <tr> <th>user</th><th>{{c0|date:'M Y'}}</th><th>{{c1|date:'M Y'}}</th><th>{{c2|date:'M Y'}}</th><th>{{c3|date:'M Y'}}</th><th>{{c4|date:'M Y'}}</th><th>{{c5|date:'M Y'}}</th> </tr> {% regroup type.list by user as userlist %} {% for user in userlist %} <tr><td>{{user.grouper}}</td> {% for data in user.list %} <td>{{user.ret_prd}}</td> {% endfor %} </tr> {% endfor %} </table> {% endfor %} I am getting below result: Is there any way I can show for each user row cells under same column heading? -
I created a new Django project but I did not get a new one. Although I create new ones, it gives me one of my previous projects
enter image description hereenter image description here These two images were not the same project but they were giving me the same project. They were totally new projects. But when I run the project they did not return me a new Django project as usual Working on project. Once remembered create virtual environment and try to create. But I think I, I could not create virtual env properly. After that I am able create new project on django. All new projects will be created the same project as above. -
How to initialize a custom model field for testing?
I've got a custom model field class VaultField(CharField): which is used to store values in Vault. Used like so: class MyClass: secret = VaultField(max_length=200, blank=True) The custom field is using self.model.__name__. My plan was to unit test this field by initializing it and calling the methods (from_db_value, to_python, etc.): field = VaultField(blank=True) field.to_python() But because the field is using self.model it's erroring on: AttributeError: 'VaultField' object has no attribute 'model' How do I get a model into the VaultField? This does not work: VaultField(max_length=200, blank=True, model=MyModel) -
How to get Redis cache info from requests_cache
I'm using requests_cache library with Redis and i want to know how to get info from redis cache. My task is to send info from 3rd party API json in Redis with celery every 5 minutes and get info from redis in my view. How can i do that? celery.py @app.task def get_project_budget(): backend = requests_cache.RedisCache(host=config('REDIS_HOST'), port=config('REDIS_PORT'), password=config('REDIS_PASSWORD'), ttl_offset=259200) session = requests_cache.CachedSession('project_cache', backend=backend, stale_if_error=True, expire_after=360) url = 'http://3rd_party_api.com' response = session.get(url) views.py import requests_cache class ProjectList(ListView): def get_queryset(self): # How can i call Redis cache there by name queryset = [] return queryset -
How do i get the value from returned JSON object?
I am trying to implement like function on my site, so when user likes the post,like button changes to unlike button and vice versa. So i wrote a function in my django app side that returns True/False if post is liked/unliked. I get this response: {like: true} How do i get just this true value without anything else? -
Django regroup a regrouped data not working
I have below D table: type month user First 2023-05-01 1 second 2023-04-01 1 second 2023-05-01 1 First 2023-03-01 1 second 2023-02-01 1 First 2023-02-01 1 second 2023-02-01 1 In view: datadump = db.objects.filter(user=request.user) In template I am trying to achive something like this: **type** User - list of all months I have tried below code and I am able to group by type but not able to group by user again. {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> {% regroup type.list by user as userlist %} {% for user in userlist %} <h4>{{user.grouper}}</h4> {% endfor %} {% endfor %} If I try above code I am getting user list multiple time, instead of grouping user. -
JavaScript Separator
I want to receive data from DJANGO and change HTML VALUE according to the data with JAVASCRIPT. BUT JAVASCRIPT not work. I'll send you what I've made up. I don't know what's wrong ##django view def message(msg): time.sleep(1) return f'{msg} ' def get_data(): status_code =['AB','CD','EF','GH','IJ'] for i in status_code: time.sleep(0.5) print(i) yield message(i) def test_stream(request): stream = get_data() # stream = db_restore_test() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response def jobs(request): return render(request, 'jobs/index.html') #html (javascript) const arr = oEvent.target.responseText.split(' ') log(arr.reverse()[1]) const data = arr.reverse()[1] if (data == 'AB'){ document.getElementById('step1_status').innerHTML = '시작'; log('1') } else if (data == 'CD'){ document.getElementById('step1_status').innerHTML = '완료'; document.getElementById('step2_status').innerHTML = '시작'; log('2') } else if (data == 'EF'){ document.getElementById('step2_status').innerHTML = '완료'; document.getElementById('step3_status').innerHTML = '시작'; log('3') } else if (data == 'GH'){ document.getElementById('step3_status').innerHTML = '완료'; document.getElementById('step4_status').innerHTML = '시작'; log('4') } else if (data == 'IJ'){ document.getElementById('step4_status').innerHTML = '완료'; log('5') } } WEB Console I dont understand why result only '2'. -
Date fixed but variable month and year in python
I have below code: from datetime import date, datetime, timedelta from dateutil.relativedelta import relativedelta c0 = date.today() c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) Now date today is 2023/06/14, however what I am trying to achieve is that no matter what date it is, I should get 16 as day, and actual current month and year. I have tried adding int to current date but since current date is not fixed, I am not able to get 16 as day. Please suggest a way where I can convert below to a date: day = 16 month = current month year = current year date = year/month/day -
return '<SimpleProducer batch=%s>' % self.async while using KafkaProducer
Here's run.py from app import create_app if __name__ == '__main__': app = create_app() app.run(host='0.0.0.0', port=8000, debug=True) Here's the /app/app/__init__.py from flask import Flask from flask_cors import CORS from app.config import Config from threading import Thread from app.consumer.kafka_consumer import consume_messages def create_app(): app = Flask(__name__) app.config.from_object(Config) app.config['SQLALCHEMY_DATABASE_URI'] = Config.MYSQL_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False CORS(app) consumer_thread = Thread(target=consume_messages) consumer_thread.start() # Register blueprints from app.controller.segmentation_controller import segmentation_bp app.register_blueprint(segmentation_bp) return app Here's the /app/app/consumer/kafka_consumer.py from kafka import KafkaConsumer from app.config import Config from app.service.segmentation_service import SegmentationService def consume_messages(): segmentation_service = SegmentationService() consumer = KafkaConsumer( Config.KAFKA_TOPIC, bootstrap_servers=['localhost:9092'], auto_offset_reset='latest', # Start reading from the latest available offset enable_auto_commit=True, group_id='my-group', value_deserializer=lambda x: x.decode('utf-8'), ) for message in consumer: segmentation_service.process_messages(message) Here's the error message 2023-06-14 11:44:43 Traceback (most recent call last): 2023-06-14 11:44:43 File "run.py", line 1, in <module> 2023-06-14 11:44:43 from app import create_app 2023-06-14 11:44:43 File "/app/app/__init__.py", line 5, in <module> 2023-06-14 11:44:43 from app.consumer.kafka_consumer import consume_messages 2023-06-14 11:44:43 File "/app/app/consumer/kafka_consumer.py", line 1, in <module> 2023-06-14 11:44:43 from kafka import KafkaConsumer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/__init__.py", line 23, in <module> 2023-06-14 11:44:43 from kafka.producer import KafkaProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/__init__.py", line 4, in <module> 2023-06-14 11:44:43 from .simple import SimpleProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/simple.py", line 54 2023-06-14 11:44:43 … -
django terminology for the two project files
In django, what is the terminology for the two project files created with the same name? Chat gpt says it is Project Directory \ Project Configuration Files. Is this correct? tried googling, but nothing. Thank you in advance! -
Django combine 2 querysets without changing the original order
def get_queryset(self): normal_posts = Post.objects.filter(field1=‘value1’).order_by('another_field_1’) featured_posts = Post.objects.filter(field2=‘value2’).order_by(‘another_field_2') all_posts = (normal_posts | featured_posts) #does not preserve the order return all_posts I'm using DjangoFilterBackend and along with filterset_class for paginated query results. Hence not able to use below. normal_ads.union(featured_ads) #django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. I tried using from itertools import chain also, however its not much helpful as its returning a list and not query set. Please suggest. -
AWS Route 53 Routing for Django Application - ALLOWED HOSTS
I am deploying a django application to AWS elastic beanstalk. I’m having troubles getting a Route 53 hosted domain record to route traffic appropriately, and I think it’s a problem on the application side and not AWS. I have a ticket open with AWS, and in their first response their thinking was that it was probably application problem, but they are still investigating. Was hoping someone here could help me on the Django side. I have a hosted zone, “example.com” in Route 53. Within the hosted zone I have 4 records, 2 are the NS and SOA records that come with each hosted zone by default. And I created 2 additional “A” records, that are alias’ to my elastic beanstalk environment. These two records are named “example.com” and “www.example.com”. In my django application I have added my elastic beanstalk CNAME, “example.com”, and “www.example.com” to the ALLOWED_HOSTS, as follows: '''ALLOWED_HOSTS = [‘env-example.eba-emvtkupp.us-west-1.elasticbeanstalk.com’, ‘example.com’, ‘www.example.com’, ‘https://example.com’, ‘https://www.example.com’,]''' Note - i added the https versions of the urls as well…im not sure if this is actually necessary. When i deploy the application to elastic beanstalk everything is normal. I try to access example.com in a browser and it works. I try to access … -
Django - How to filter out row that are same in some fields and differ in others?
i have a model in django like this class Article(models.Model): column_one = ForeignKey() column_two = ForeignKey() column_three = ForeignKey(null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["column_one", "column_two"], condition=Q(column_three=None), name='article_unique_if_no_column_three'), models.UniqueConstraint( fields=["column_one", "column_two", "column_three"], condition=~Q(column_three=None), name='article_unique_if_column_three'), ] How can i filter so that i get all the articles but if there are two that have the same data except the column_three it chose the one with column_three not null and exclude the one with column_three=None thanks in advance -
Running crond as root user when server is going to be running as non-root django container
I'm currently dockerizing my app and am trying to get cron jobs working. For context I am creating my job using the python-crontab module. I would like to run the container as a non-root user (as I believe is best practice) however I am struggling to get the cron task to run. This is the relevant part of my current dockerfile: ######### # FINAL # ######### #Pull base image FROM python:3.9.15-alpine3.16 #Create directory for app user RUN mkdir -p /home/user #create app user RUN addgroup -S app && adduser -S useradmin -G app #create directories ENV HOME=/home/user ENV APP_HOME=/home/user/userapp RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME #install dependencies RUN apk update && apk add libpq COPY --from=builder /user/wheels /wheels RUN pip install --no-cache /wheels/* # copy entrypoint.sh COPY entrypoint.sh $APP_HOME # copy project COPY . $APP_HOME RUN python /$APP_HOME/user/cron.py RUN crontab -l > /home/user/crontab.txt RUN crond -f -L /dev/stdout # chown all the files to the app user RUN chown -R user:app $APP_HOME # change to app user USER useradmin # run entrypoint.sh ENTRYPOINT ["/home/user/userapp/entrypoint.sh"] The line RUN crond -f -L /dev/stdout is the only way so far I have found to get the cron jobs … -
How do migration operations (eg. AddField) detect if you're applying or reverting a migration?
A good example is django.db.migrations.AddField. Let's say I've created a simple migration such as: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.AddField( model_name="foo", name="bar", field=models.TextField(blank=True, null=True), ), ] Running the migration would result in the bar field being added, and reverting to a previous migration would result in the bar field being removed. However when I look under the hood of the AddField class, I don't see the logic for detecting the direction of the applied migration. class AddField(FieldOperation): field: Field[Any, Any] = ... preserve_default: bool = ... def __init__( self, model_name: str, name: str, field: Field[Any, Any], preserve_default: bool = ..., ) -> None: ... I need to create a similar function for collected data that can apply/revert changes based on changes made to the model the data is based on. This function would be used inside migrations in a similar way to AddField, and needs to detect whether the user is applying or reverting a migration. -
Why do I get a different schema when I run generateschema on the command line compared to obtaining it via the api using Django SchemaGenerator?
I am using the Django Rest Framework SchemaGenerator to create a schema for my API. However, I get different results depending on whether I generate a static schema using python manage.py generateschema compared to when I request a dynamic schema through the API endpoint configured as urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), re_path(r'^auth/', include('api.djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('schema/', get_schema_view( title="Morty", description="API to access Morty", version="1.0.0" ), name='morty-schema'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Using the static method I get a complete schema with all the API endpoints. The schema returned from the endpoint in the dynamic method has a number of endpoints missing. The set of endpoints given in the dynamic schema is /auth/users/activation/ /auth/users/resend_activation/ /auth/users/reset_password/ /auth/users/reset_username/ /auth/users/reset_username_confirm/ /auth/token/login/ which is missing the following endpoints that are present in the full static schema /auth/users/ /auth/users/me/ /auth/users/{id}/ /auth/users/reset_password_confirm/ /auth/users/reset_username_confirm/ /auth/users/set_password/ /auth/users/set_username/ /auth/token/logout/ I am using Djoser to get the endpoints and associated views. I thought, perhaps, that the dynamic schema was affected by authorization, but I tried logging in using the /login/ endpoint prior to requesting the schema and got the same results. I feel like I must be missing something obvious. -
Django - not displaying the images (as urls)
I'm following a ytb video, step by step and everything works fine except for the images. I uploaded the link adresses through django admin, but they are not displaying. models.py: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer (models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() index.html: {% extends 'base.html' %} {% block content%} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }} RON</p> <a href="#" class="btn btn-primary">Adauga in cosul tau</a> </div> </div> </div> {% endfor %} </div> {% endblock %} views.py: from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('Produse noi') The code is the same as in the video. I tried to ask chat gpt if there's something that doesn't seem right but he didn't find anything. I tried to change the name from "image_url" to anything else but didn't work, as expected. -
Where to set a custom middleware's path in "MIDDLEWARE" in "settings.py" in Django?
I created the middleware simple_middleware() in middleware/sample.py following the doc as shown below. *I'm learning Middleware: django-project |-core | └-settings.py |-middleware | |-__init__.py | └-sample.py # Here |-app1 └-app2 # "middleware/sample.py def simple_middleware(get_response): print("Only once the server starts") def middleware(request): print("Before a view is called") response = get_response(request) print("After a view is called") return response return middleware But, I don't know where to set the custom middleware's path in MIDDLEWARE in settings.py as shown below. The 1st, the last or anywhere in MIDDLEWARE?: # "core/settings.py" MIDDLEWARE = [ # "middleware.sample.simple_middleware" # The 1st? "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", # "middleware.sample.simple_middleware" # Anywhere? "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", # "middleware.sample.simple_middleware" # The last? ] Actually, I know that the doc says below in Activating middleware but I want to know exactly where to set it: The order in MIDDLEWARE matters because a middleware can depend on other middleware. So, where should I set the custom middleware's path in MIDDLEWARE in settings.py? -
how to specify response for specific request methods for API action in django
I have an API action in django which accepts GET and POST requests where each of them will have a distinct response schema. If a request is of method "GET" we will return a list, if it is "POST" we will return only the created entity... from drf_spectacular.utils import extend_schema class SessionsViewSet(viewsets.ModelViewSet): ... @extend_schema( parameters=[query_params["extra_query_param"]], responses={ "GET": serializers.ExampleSerializer(many=True), "POST": serializers.ExampleSerializer(many=False), }, ) @action( detail=True, url_path="example", methods=["GET", "POST"], filter_backends=[], ) def example(self, request, pk, *args, **kwargs): match request.method: case "GET": queryset = MyModel.objects.filter(session_pk_id=pk) page = self.paginate_queryset(queryset) serializer = get_serializer(page, many=True) return self.get_paginated_response(serializer.data) case "POST": serializer = get_serializer(data=request.data, many=False ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_201_CREATED, ) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) case _: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) The problem is that now I am not sure how to define this rule so that the swagger auto-schema will detect and present as such. How can I explicitly state that a response schema or serializer belongs to a specific request method? -
Failing to understand django get_absolute_url
I have this model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=600) isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre) language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) And this view: class BookDetail(DetailView): model = Book It will connect me to the template as well called (book_detail.html). My question is, do I need to also specify in the app's urls.py the url path in this case? path('book/<int:pk>/',views.BookDetail.as_view(),name='book_detail') I thought that if I used get_absolute_url(self) I wouldn't need to do that but I am finding some resources where it says it is necessary. I find it confusing since to me it feels like duplicating the code. Thanks! -
Updating status of one field based on multiple conditions from other fields
I have a class 'Contract' in which I want to set a status based on the fulfillment of certain conditions. The status is used for making lists and table of contracts based on their status. For now, I'm thinking the best solution is to split the code into two parts: Conditions that need to be met before updating an object, and conditions for automatic updates. The first example would be where the user would change the status of a contract from 'PLANNED' to an active contract. In order to do this, the field 'award_date' would have to be filled in before the other possible fields 'signature_date', and 'start_date'. Possible statuses can be 'AWARDED_UNACTIVE' ('signature_date' with a empty or future 'start_date), 'UNSIGNED_ACTIVE' ('start_date' without 'signature_date'). Another example would be that one can only set the status to 'TERMINATED' if the the contract has an active status (planned or expired contracts can not be terminated). The second example would be if a contract has been active ('start_date' is before today) and the date passes 'end_date'. In these cases I would like 'status' to change to 'EXPIRED' without needing a manual update. How would I go about to make this? I'm still a … -
Function-Based Middleware vs Class-Based Middleware in Django
I read the doc, then I could understand that we can define a function-based middleware and a class-based middleware in Django as shown below but I could not understand the difference between them. *I'm learning Middleware: Function-Based Middleware: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. return response return middleware Class-Based Middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response My questions: What is the difference between a function-based middleware and a class-based middleware in Django? Which should I use basically? -
docker nginx django ALLOWED_HOSTS not allowing requests through
I am deploying an api that doesn't require database or gunicorn to be used. With following configurations I am setting up the api: nginx.conf upstream django { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } nginx Dockerfile # Base image for building the Django application FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d ALLOWED_HOSTS django settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] Dockerfile # Base image for building the Django application FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY . /code/ EXPOSE 8000 EXPOSE 80 CMD python manage.py runserver 0.0.0.0:8000 --noreload docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile volumes: - .:/code nginx: build: ./nginx ports: - 80:80 depends_on: - web The purpose is to create an api which will only be called by other client like a Python based client. I am testing this from my local machine but not working. Adding * wildcard works but is too risky. So, what changes should I make for following two cases: 1. To be able to call from my local python client. 2. To be …