Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i handle multiple files (photos/videos) in single post Django template?
i want to upload multiple file like (photos&videos) in a single post like Facebook. i don't know how can i handle or show photo or videos in template side? anybody know how to arrange in template side? models.py class Article(models.Model): title = models.CharField(max_length=300,) file_data = models.FileField(upload_to='stories', blank=True, null=True) def __str__(self): return self.title def extension(self): name, extension = os.path.splitext(self.file_data.name) return extension forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] {% for object in newss %} <div class=" card"> {% if object.file_data %} <img src="{{object.file_data.url}}" alt="article" height="400"> {% endif %} {% if object.file_data %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{object.file_data.url}}#t=0.9" /> </video> {% endif %} </div> -
Failed to create virtual environment directory in cmd
Unable to create venv using python 3x; python -m venv myclub Error: Command '['C:\Users\Sibasankar Panigrahi\myclub\Scripts\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. -
Is this example of model object property usage unique to a logged-in session in django?
I know django optimises with some model instance re-use. So - the question is really - is the value of 'imprints' shown below unique to a logged-in session in django? Lets say I have a django deployment in which, with this model. Class Thing(models.Model): example_field = models.UUIDField(default=uuid.uuid4, editable=False) imprints = None # placeholder for imprints to be added dynamically def add_imprints(self, cc): """ Adds an imprints object associated with this instance for passed cc to this instance. """ self.imprints = cc.imprint_set.get(entity=self) using the ORM, an instance of this Thing model in the db is pulled up in a view, say with. object = Thing.objects.get(pk=thing_id) a value is then assigned to the imprints field which is intended just as an addition to the instance so that when it is passed to another function that added information is there - like this object.add_imprints(cc) To emphasise - the imprints value is only used to pass information with the instance of Thing during the processing of a view and through some related functions, there is no need for further persistence and it must be unique to the session. Normally there is no problem with this kind of practice - however there may be a … -
How to store multiple userids in same model?
I'm fairly new to Django and attempting to store a model which will hold transaction information for a purchase between 2 users; a buyer and seller. I therefore want to store 2 UserIDs: class Transaction(models.Model): transactionid = models.AutoField(primary_key=True) # USERID OF SELLER # USER ID OF BUYER orderid = models.ForeignKey('Order', db_column='orderid', on_delete=models.SET_NULL, blank=True, null=True) status = models.CharField(choices=PAYMENT_STATUS, default='pending', max_length=50) timestamp = models.DateTimeField(auto_now_add=True) I want to use the following foreign key: seller = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) however, to my understanding, this will only store the current logged in user which means I wouldn't be able to set both? Is there a better way to do this rather than modifying the model twice (esentially from both accounts)? Any reccomendations or advice appreciated, thank you! -
How to create a django-admin import / export who impacts multiples models?
I need to create a way to import / export data using django-admin in a way the user uploads an excel sheet and the content of this excel impacts 3 different models. I already saw https://django-import-export.readthedocs.io/ but it appears to impact only one model. So how is the best approach to accomplish this? -
Can I use global variables in Django?
I am solving a problem with Django, and the best way, how I think, is using global variables. For example, I need a variable page. When one user sends a request to the fifth page on my site, page=5. But when the second user watches the third page, page should be 3, but for the first user it must be still 5. So for different users, one variable must has different value in one time. I want to make page a global variable and change its value in function. Are there some risks? What can you advise me? -
Authentication credentials were not provided when sending request from React JS axios
I'm building a simple API, but right now I'm having some issues with the back-end. I always used the Django-rest-framework serializers, but now I'm trying to code a function-based view. My back-end server uses knox token authentication as a default, I have this set up in the Django settings (below) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ) } So the thing is that when the POST request is sent from the postman, the server identifies the user which calls the request, but when the request is sent from React JS the server couldn't find the user. This is my views.py function-based view: @csrf_exempt @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def hello_world(request): print(request.data) print(request.headers) print('user', request.user.username) This is what I get when sending the request from POSTMAN - {'report': 'testas'} {'Content-Length': '28', 'Content-Type': 'application/json', 'Authorization': 'Token 024f51b3f210082302ceb1fff29eff3fcefd50437c6909ca7d6647a1ce1d66bb', 'User-Agent': 'PostmanRuntime/7.26.8', 'Accept': '*/*', 'Postman-Token': '5e9be4f1-cbf5-4f8f-bf7c-f44761c30798', 'Host': '192.168.0.30:8000', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive'} user 3nematix And this comes from React JS : {'headers': {'Content-Type': 'application/json', 'Authorization': 'Token d8bce38c58d07ade11446147cab60ac7795813232cc44d93e9d0da46bd16384e'}} {'Content-Length': '136', 'Content-Type': 'application/json;charset=UTF-8', 'Host': '192.168.0.30:8000', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Origin': 'http://192.168.0.30:8000', 'Referer': 'http://192.168.0.30:8000/reports/view', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9'} user How can I fix … -
Make LEFT JOIN query in ORM
Hello everyone i want to write this query in ORM help please: SELECT *, COALESCE(widgets_userwidget.sort,0) as sort,COALESCE(widgets_userwidget.column,1) as column FROM widgets_widgetcatalog LEFT JOIN widgets_userwidget ON (widgets_widgetcatalog.uid=widgets_userwidget.uid) and widgets_userwidget.user_id=%s' % self.request.user.id I make this query using raw but he doesn't display all fields but in pgadmin this query display all fields. Serializers class WidgetCatalogSerializer(serializers.ModelSerializer): class Meta: model = models.WidgetCatalog fields = "__all__" class WidgetSerializer(serializers.ModelSerializer): widget = WidgetCatalogSerializer(read_only=True) class Meta: model = models.UserWidget fields = "__all__" -
Django choose in what location images are loaded in model's save method
Here's my save method for model with field image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True): def save(self, *args, **kwargs): if self.image: self.image = compress(self.image) if self.second_image: self.second_image = compress(self.second_image) if self.third_image: self.third_image = compress(self.third_image) if self.fourth_image: self.fourth_image = compress(self.fourth_image) super().save(*args, **kwargs) It works fine and compresses all images but changes image's directory every time when I click save in django admin. It makes all images' paths be like: before edited and saved: products/2020/11/05/img.jpeg after: products/2020/11/05/products/2020/11/05/img.jpeg click save one more time: products/2020/11/05/products/2020/11/05/products/2020/11/05/img.jpeg And then I get this error: SuspiciousFileOperation at /admin/shop/product/6/change/ Storage can not find an available filename for "products\2020\11\05\products\2020\11\05\products\2020\...... .jpeg". Please make sure that the corresponding file field allows sufficient "max_length". How can I fix this problem? I think I need to choose location where saved images would be stored. Django doesn't let me use absolute path in upload_to field so I have no idea. -
Django pagination in html template
i want to use pagination , but i can not do it in html. views.py def blog_list(request): articles = Blogmodel.objects.all() page = request.GET.get('page', 1) paginator = Paginator(articles, 20) try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) args = {'articles':articles,'page':page} return render(request,'blog.html',args) html <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> can anyone help me , how to do this in html ? -
Unable to apply I18n with Django/Docker
I have develop a Django app with Docker it works but I want to internationalize (i18n) my app I connect to my container docker exec -it my_container_1 sh I try to run python manage.py makemessages -l fr but got an error When conatiner is built, requirements.txt is applyed and python-gettext is installed I am newbie with Django with docker and probably i missunderstand. requirements.txt Django==2.2.5 psycopg2-binary==2.8.5 django-bootstrap4==1.0.1 django-crispy-forms==1.7.2 django-debug-toolbar==2.0 django-extensions==2.2.9 django-maintenance-mode==0.15.0 django-partial-date==1.2.2 django-safedelete==0.5.2 django-simple-history==2.7.3 django-widget-tweaks==1.4.5 Pillow==6.2.2 python-gettext==4.0 <-- ****************************** pytz==2019.2 reportlab==3.5.32 selenium==3.141.0 six==1.12.0 soupsieve==1.9.3 sqlparse==0.3.0 urllib3==1.25.6 xlwt==1.3.0 settings.py MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) LOCALE_PATHS = [ os.path.join(BASE_DIR,'locale'), ] Dockerfile # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN pip3 install psycopg2 psycopg2-binary # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt COPY entrypoint.sh . # Copy the project's files … -
How to count occurrences from db in django
I have simple table in SQLite with id, process and step in process id. I need to display how many steps have every process. I have something like this but it doesn't work as I need: for steps in StepsInProcesses.objects.all(): activ_count = activ_count + proc.steps.count() -
How to load static images in a function not in view
I am using a django template to generate pdf via feeding it a context object from the function but not the view, it works fine in case of view, but I am not able to load the local static images on the template from the function. but this is possible in view because there I can tell which base path to use. But I not able to do the same in the function. As you can see I can how I am getting the base url from the view. Here I can get because I have requests object but in function I do not have any requests object. So images are not loading. html = HTML(string=html_string, base_url=request.build_absolute_uri('/')) This is how I am trying to do in the function: html_string = render_to_string('experiences/voucher.html', data) html = HTML(string=html_string, base_url=settings.STATIC_ROOT) result = html.write_pdf("file_new.pdf", stylesheets=[css],optimize_images=True) I would like to know how can I tell, where are my images so that images can be rendered on the pdf. -
ProgrammingError column Users_student.school does not exist in django
I've been struggling with this issue for hours now. I have a model in my app which goes like this class Student(models.Model): school = models.CharField(max_length=100, null=True, blank=True) field_of_study = models.CharField(max_length=100, null=True, blank=True) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='Student') courses = models.ManyToManyField('StudentDashboard.Course', related_name="student_courses") And whenever I try to view details of this class through django admin panel, I face the error ProgrammingError column Users_student.school And if I comment school, that happens for field_of_study. And if that is commented too, It works fine. But I actually do need those 2 fields so I can't just comment them and go on. Anyone knows a solution to this? Thanks in advance! -
Make docker automatically run collecstatic and migrate in Django
I have a following question. I have dockerized Django project and instead of manually run collectstatic and migrate each and every time I would like to docker do it for me. Is it possible to make Docker automatically run: python manage.py collectstatic --noinput python manage.py migrate every time when image is created? Or alternatively before container is started… My Dockerfile: FROM python:3.8.6-alpine LABEL project="short_urls" ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system --ignore-pipfile COPY short_urls /code/ Docker-Compose.yaml version: '3.8' volumes: redis_data: services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - target: 8000 published: 8000 protocol: tcp mode: host depends_on: - redis restart: always redis: image: redis:6.0.9-alpine command: redis-server ports: - target: 6379 published: 6380 protocol: tcp mode: host volumes: - redis_data:/data restart: always environment: - REDIS_REPLICATION_MODE=master celery: build: . command: celery -A short_urls worker --loglevel=INFO -E restart: always environment: - C_FORCE_ROOT=1 volumes: - .:/code links: - redis depends_on: - web - redis hostname: celery-main celery-beat: build: . command: celery -A short_urls beat --loglevel=INFO --pidfile= restart: always volumes: - .:/code depends_on: - web - redis hostname: celery-beat flower: image: mher/flower environment: - CELERY_BROKER_URL=redis://redis:6379/3 - … -
AWS Elastic Beanstalk Django application health check problem
I am having a very similar problem to the one described here. As that question wasn't answered and there are some differences between my problem and the one described there I decided to ask a new question. I managed to deploy my Django backend API to the AWS Elastic Beanstalk Amazon Linux 2 Python 3.7 platform. However, the health status of the EB instance is "Severe". It shows the message: Following services are not running: release. The overall health status is "Degraded" and the message is Impaired services on all instances. Sometimes a message saying that all responses are 4xx appears. This message comes and goes. The weird thing is that I have 2 load balancers configured (one for http and the other one for https) and both have a health check path url of a valid url in the application. The only relevant logs I could find are the following: daemon.log F, [2020-11-05T00:07:40.486088 #15846] FATAL -- : /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:432:in `block in setup_signals': SIGTERM (SignalException) from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `join' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:172:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/cli.rb:80:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:112:in `block in <top (required)>' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `chdir' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `<top (required)>' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `load' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `<main>' web.stdout.log (...) Nov 5 09:26:18 … -
How to avoid "AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model'" in Django Ajax form submit
I have been trying to post records in related models in my Django app using Ajax. In order to update a pair of parent/child models, I am using the following view and the records are getting saved in the respective models. However, I keep getting the following error: AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model'" The following is the set up: views.py class MatListCreateView(LoginRequiredMixin, CreateView): template_name = "..." model = MatHdrList form_class = CreateMatHdrListForm def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) mat_bom_list = CreateBomMatListFormset return self.render_to_response( self.get_context_data(form=form, mat_bom_list=mat_bom_list) ) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) mat_bom_list = CreateBomMatListFormset(self.request.POST) if self.request.is_ajax and self.request.method == "POST": if form.is_valid() and mat_bom_list.is_valid(): form.instance.created_by = self.request.user self.object = form.save() mat_bom_list.instance = self.object mat_bom_list.save() ser_instance = serializers.serialize('json', [ form, mat_bom_list, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": "Whoops"}, status=400) Template (jQuery ajax part) $('#materialListForm').submit(function(e) { e.preventDefault(); var serializedData = $(this).serialize(); console.log(serializedData); // var url1 = "{% url 'matl_list' %}"; $.ajax({ url: "{% url 'material_list_create' %}", type: 'POST', data: serializedData, success: function() { console.log('Data Saved'); // window.location = url1; }, error: function (response, status, error) { console.log('Problem encountered'); alert(response.responseText); } … -
Django ORM binary exact
Suppose I have a MySQL database with a _ci (case insensitive) collation with a table like this: |ID | name | -------------- |0 | John | Being case insensitive, if I query either way: SELECT * FROM table1 WHERE name = "john" or SELECT * FROM table1 WHERE name = "John" Would return the element. Django obviously acts the same way: MyObject.objects.get(name="john") Would return the instance. In MySQL I can query like this to force case sensitivity: SELECT * FROM table1 WHERE BINARY name = "john" That would return me nothing My question is: How to replicate the Binary query operator using the Django ORM? -
Python manage.py migrate doesn't create tables
The problem is that the python manage.py migrate fails due to the absence of tables in the database, but actually, it should create them. And now in more detail: For several days now I have been trying to solve the problem, so maybe I forgot something from what I did before. I originally had one model class Product(models.Model): code = models.CharField(max_length=50) quantity = models.PositiveIntegerField(default=1) name = models.CharField(max_length=255) slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name',)) technology = models.CharField(max_length=255) status = models.CharField(max_length=255, default='Exists') description = models.TextField() Then I needed to make a mptt model from this model to make a product tree and I changed the code like this: class Product(MPTTModel): code = models.CharField(max_length=50) quantity = models.PositiveIntegerField(default=1) name = models.CharField(max_length=255) slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name',)) technology = models.CharField(max_length=255) status = models.CharField(max_length=255, default='Exists') description = models.TextField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['code'] And the problems started ... The migrations did not want to be applied due to the missing parent _id column. I tried a lot of things then, in the end the following helped me: I manually created the columns parent_id, lft, rght, level, tree_id. And it all worked. Then I decided that for my task … -
Еhere was an error while adding url to test
When I transfer to the test url, an error pops up: Reverse for 'movie' not found. 'movie' is not a valid view function or pattern name. Here is my self test: class BooksApiTestCase(APITestCase): def setUp(self): self.movie_1 = Movie.objects.create(title="terminator", year="1990", rating="5",url="retminator") self.movie_2 = Movie.objects.create(title="robocop", year="1991", rating="4",url="robocop") self.movie_3 = Movie.objects.create(title="rembo", year="1992", rating="3",url='rembo') def test_get(self): url = reverse('movie') print(url) response = self.client.get(url) serializer_data = MovieListSerializer([self.movie_1, self.movie_2, self.movie_3], many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(serializer_data, response.data) Here is my self url: urlpatterns = format_suffix_patterns([ path("movie/", views.MovieViewSet.as_view({'get': 'list'})), -
Django: Saving uploaded file in specific directory
I want to save files that the user uploads in the project directory 'media/documents/(their user id)/filename.pdf'. I tried doing this: def user_directory_path(request, filename): return 'user_{0}/{1}'.format(request.user.id, filename) But I get this error: I am not sure what to do, I am a bit of a django noob. I appreciate any help! My models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser def user_directory_path(request, filename): return 'user_{0}/{1}'.format(request.user.id, filename) class Contract(models.Model): id = models.AutoField(primary_key = True) title = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=user_directory_path, default = 'settings.MEDIA_ROOT/documents/default.pdf') class Meta: ordering = ['-date_created'] def __str__(self): return self.title class Employer(AbstractBaseUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) company_name = models.CharField(max_length=50) contracts_made = models.ForeignKey(Contract, on_delete=models.CASCADE, default=1) date_joined = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_joined'] def __str__(self): full_name = str(self.first_name) + " " + str(self.last_name) return full_name class Employee(AbstractBaseUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_joined = models.DateTimeField(auto_now_add=True) agreed = models.ForeignKey(Contract, on_delete=models.CASCADE, default=1) class Meta: ordering = ['date_joined'] def __str__(self): full_name = str(self.first_name) + " " + str(self.last_name) return full_name Views.py: from django.shortcuts import render, redirect from .forms import UploadFileForm def HomePageView(request): return render(request, 'home.html') def model_form_upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: … -
Django and Python Room Booking System
I am new to Django and programming in general so this is my first ever web app and experience with Django. My idea was to create a basic meeting room booking system. The system should allow the user to: -login -click a room and make a reservation (select date, time) -amend bookings -cancel bookings -send an email notification confirming reservation -not allow users to block a slot that is already reserved I was wondering if anyone could give me any advice on how to approach making something along these lines as my research shows I will also need a 'virtual environment' which I have never used before. Any advice or assistance at all would be appreciated! Thanks -
Send a whatsapp message with django
I am building a django e-commerce webapp with django.My client wants users to order the products directly on whatsapp and facebook by recieving an automatic message that says I want to order {{ productname }} product name will be the name of the product the users want to order. I have looked into some twillo tutorials and i can't seem to understand how to go about it. The e-commerce website has already been deployed with heroku. I would be happy if i'm offered some help about how to do this. -
Django: Late switch to Custom User Model always hurts?
The official Django documentation "highly recommends" implementing a custom user model and William S. Vincent says in "Django for Professionals": If you have not started with a custom user model from the very first migrate command you run, then you’re in for a world of hurt because User is tightly interwoven with the rest of Django internally. It is challenging to switch over to a custom user model mid-project. Unfortunately, I saw these recommendations too late and now I wonder, if this pain is always the case or only if you already make use of users somehow. In my Django project, there is only one single user and none of my models are related to users in any kind (which I am planning to change soon). Is there any hope that it wouldn't get that terrible? This extensive guide, for example, has the following assumptions: You have an existing project without a custom user model. You're using Django's migrations, and all migrations are up-to-date (and have been applied to the production database). You have an existing set of users that you need to keep, and any number of models that point to Django's built-in User model. Actually, I do not … -
Django Docker Setup Issue, Any one can check the mistake
version: '3.7' services: backend: build: ./app command: sh -c "cd project python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 depends_on: - db network_mode: host frontend: build: ./app ports: - 80:80 command: sh -c "npm run start:production" db: image: postgres:12.0-alpine ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER= - POSTGRES_PASSWORD= - POSTGRES_DB= volumes: postgres_data: