Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: invalid literal for int() with base 10
I'm struggling to understand why I have this error for the custom uuid text field. Data: { "contact_uuid": "49548747-48888043", "choices": "", "value": "1", "cardType": "TEXT", "step": 1, "optionId": "", "path": "/app/e120703e-2079-4e5f-8420-3924f9e0b9c8/page1/next", "title": "Welcome to my app" } View: The important bit here is the line that saves the data so you can gloss over the rest of the code. class NextDialog(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def post(self, request, *args, **kwargs): data = request.data contact_uuid = data["contact_uuid"] step = data["step"] value = data["value"] optionId = data["optionId"] path = get_path(data) request = build_rp_request(data) app_response = post_to_app(request, path) response_data = AppAssessment(contact_uuid, step, value, optionId) response_data.save() try: report_path = app_response["_links"]["report"]["href"] response = get_report(report_path) return Response(response, status=status.HTTP_200_OK) except KeyError: pass message = format_message(app_response) return Response(message, status=status.HTTP_200_OK) Model: class AppAssessment(models.Model): contact_uuid = models.CharField(max_length=255) step = models.IntegerField(null=True) optionId = models.IntegerField(null=True, blank=True) user_input = models.TextField(null=True, blank=True) title = models.TextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) def __str__(self): return self.contact_uuid When the response_data.save() line runs in the view, I get the following error: File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 972, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '49548747-48888043' -
How to Generate a unique Coupon Code In the Django Admin panel for bulk
#i have used this code in models.py #im getting errror of Gift is not defined and models are not shwoing in the Django admin panel# from django.db import models import secrets from django.db.models.signals import post_save class UniqueCodes(models.Model): """ Class to create human friendly gift/coupon codes. """ # Model field for our unique code code = models.CharField(max_length=8, blank=True, null=True, unique=True) @classmethod def post_create(cls, sender, instance, created, *args, **kwargs): """ Connected to the post_save signal of the UniqueCodes model. This is used to set the code once we have created the db instance and have access to the primary key (ID Field) """ # If new database record if created: # We have the primary key (ID Field) now so let's grab it id_string = str(instance.id) # Define our random string alphabet (notice I've omitted I,O,etc. as they can be confused for other characters) upper_alpha = "ABCDEFGHJKLMNPQRSTVWXYZ" # Create an 8 char random string from our alphabet random_str = "".join(secrets.choice(upper_alpha) for i in range(8)) # Append the ID to the end of the random string instance.code = (random_str + id_string)[-8:] # Save the class instance instance.save() def __str__(self): return "%s" % (self.code,) post_save.connect(Gift.post_create, sender=UniqueCodes) -
Internal server error 500 while using application
Please find below event viewer log,can anyone help me why am getting this error(sometimes) Environment details: Django framework IIS application Python 3/7 Faulting application name: python.exe, version: 3.7.3150.1013, time stamp: 0x5c9954fa Faulting module name: _ctypes.pyd, version: 3.7.3150.1013, time stamp: 0x5c9954c9 Exception code: 0xc0000005 Fault offset: 0x000000000000f365 Faulting process id: 0x1938 Faulting application start time: 0x01d839ca6dc31b14 Faulting application path: D:\qm_env\Scripts\python.exe Faulting module path: d:\python37\DLLs_ctypes.pyd Report Id: 8701a9d7-3cc9-4a91-b8c5-ff04fb2b2a59 Faulting package full name: Faulting package-relative application ID: -
Cannot assign "str" must be a "User" instance
I'm trying to make a post request to django rest api from reactjs but the traceback shows, ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000247410D3670>": "BuildingClearance.resident_number" must be a "User" instance. models.py class BuildingClearance(models.Model): resident_number = models.ForeignKey(to=User, to_field="resident_number", on_delete=models.CASCADE) request_number = models.AutoField(primary_key=True) maintenance_type = models.CharField(max_length=100, blank=False) approval = models.BooleanField(default=False) views.py class BuildingClearanceList(ListCreateAPIView): permission_classes = [AllowAny] serializer_class = BuildingClearanceSerializer queryset = BuildingClearance.objects.all() def perform_create(self, serializer): return serializer.save(resident_number=self.request.user) def get_queryset(self): return self.queryset.filter(resident_number=self.request.user) class BuildingClearanceView(RetrieveUpdateDestroyAPIView): serializer_class = BuildingClearanceSerializer queryset = BuildingClearance.objects.all() def perform_create(self, serializer): if self.request.user.is_authenticated: return serializer.save(resident_number=self.request.user) def get_queryset(self): return self.queryset.filter(resident_number=self.request.user) serializers.py class BuildingClearanceSerializer(ModelSerializer): class Meta: model=BuildingClearance exclude = ['resident_number'] If i set the permission_classes to [isAuthenticated], the error message will be 401 unauthorized (Authentication credentials were not provided) even though i included the right headers: services.js const API_URL = "http://127.0.0.1:8000/api/forms/"; buildingClearance(maintenance_type) { var token = JSON.parse(localStorage.getItem('user')).access; console.log(token) return axios .post(API_URL + "building/", { headers:{ Accept: 'application/json', Authorization: 'Bearer ' + token }, maintenance_type }) } -
django celery error: Unrecoverable error: AttributeError("'EntryPoint' object has no attribute 'module_name'")
I am perplexed,from a weird error which i have no idea as i am new to celery, this error occurs on just the setup phase, every thing is simply configured as written in the celery doc https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html the tracback is: (env) muhammad@huzaifa:~/Desktop/practice/app$ celery -A app worker -l INFO [2022-04-04 16:21:40,988: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' [2022-04-04 16:21:40,993: CRITICAL/MainProcess] Unrecoverable error: AttributeError("'EntryPoint' object has no attribute 'module_name'") Traceback (most recent call last): File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 1250, in backend return self._local.backend AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/bootsteps.py", line 112, in start self.on_start() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 136, in on_start self.emit_banner() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 170, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 232, in startup_info results=self.app.backend.as_uri(), File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 1252, in backend self._local.backend = new_backend = self._get_backend() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 955, in _get_backend backend, url = backends.by_url( File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/backends.py", line 69, in by_url return by_name(backend, loader), url File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/backends.py", line 47, in by_name aliases.update(load_extension_class_names(extension_namespace)) File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/utils/imports.py", line 146, in load_extension_class_names yield ep.name, ':'.join([ep.module_name, ep.attrs[0]]) AttributeError: 'EntryPoint' object has no attribute 'module_name' the init file … -
A Model is linked to two other models. How do I access the properties of that two other models in django
I am in a process of creating a Room Booking Management System using Django. I have faced an issue in accessing models. Here is my Room Model class Room(models.Model): name = models.CharField(max_length=30) date = models.DateField() defined_check_in_time = models.IntegerField() defined_check_out_time = models.IntegerField() booked = models.BooleanField(default = False) USERNAME_FIELD = 'name' class Meta: ordering = ['date', 'defined_check_in_time'] def __str__(self): return self.name def is_booked(self): return self.booked def set_booked(self): self.booked = True Here is my Booking Model class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return f'{self.user} has booked {self.room} from {self.room.defined_check_in_time} to {self.room.defined_check_out_time} on {self.room.date}' I have linked the User model and Room model in the Booking model using a foreign key when a user books a room. User model is defined in another file. I have not included that model code here. When a user books a room, the corresponding room object and user object is linked to the booking object. To display the bookings of the user, I need to query the Booking model using a User object. Here, my question is how i can access user and room object attributes inside the booking object? -
dj-rest-auth logout view returns `CSRF: Failed` while login view works
I'm integrating with dj-rest-auth for my rest api and testing via Postman right now. The login-view works just fine and returns the token, however the logout view returns "detail": "CSRF Failed: CSRF token missing." #urls.py from django.urls import path, include urlpatterns = [ path('auth/', include('dj_rest_auth.urls')), ] Both endpoints expect a POST request which I use accordingly. So why does the logout view bark? -
DRF and Knox Authentication: Demo accounts where user doesn't have to input credentials
I'm making an app with React as the front end and am handling authentication with knox. Everything is working fine but I require the ability for users to login to premade demo accounts without inputting any credentials. I can't figure out how to do this with Knox on the backend and I can't have the login info stored in my javascript. Any ideas how to accomplish this? Knox: class LoginAPI(KnoxLoginView): authentication_classes = [BasicLikeAuthentication] def get_post_response_data(self, request, token, instance): user = request.user data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token, 'user': user.username, 'role': user.roles.assigned_role } return data Front end for regular login: const handleSubmit = (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptions = { method: "POST", credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } fetch('http://127.0.0.1:8000/api/login/', requestOptions) .then(response => { if (response.status === 401) { setFailedLogin(true) } return response.json() }) .then(data => { localStorage.setItem('token', data['token']) }) .then(fetchCurrentUser) .then(() => { localStorage.getItem('role') == "Admin" ? navigate("/manage") : navigate("/maindash") }) .catch(error => console.log(error)) } -
Change CSS display property with javascript if recaptcha not checked in form?
I'm trying to write a javascript function that confirms a user has checked a Google recaptcha V2 box (using django-recaptcha). If they haven't checked the recaptcha box I'd like to display a piece of text reminding them to check before submitting the form. Here's what I've already tried but the button either submits and refreshes the page, or the hidden div just will not display. Javascript function checkForm(){ if(!document.getElementById("g-recaptcha-response").value){ $('.validate').show(); return false; }else{ document.getElementById("buttoncontact").type = "submit"; return true; } } HTML <div> {{form.captcha}} </div> <div class="captcha"> This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply. </div> <div class="validate" style="display: none;"> Please validate the captcha field before submitting. </div> <div> <button id="buttoncontact" type="submit" onclick="return checkForm();">Submit</button> </div> I've gotten this code to work with the alert function show below, however for user experience I'd much rather not have an alert window to pop up: function checkForm(){ if(!document.getElementById("g-recaptcha-response").value){ alert("Please validate the captcha field before submitting."); return false; }else{ document.getElementById("buttoncontact").type = "submit"; return true; } } -
Translating SQL nested query to Django ORM
I do not have much experience with the Django ORM. I have been tasked with creating a Django-based command that would execute a SQL query, but I have no clue how the nested application here would translate into the ORM notation.Is there a way to do it in a readable way, or is using the 'raw' statement a more reasonable approach? Any help would be much appreciated. update main_connection mc set test_case_count = 0, test_case_fail_count = 0, status_id = 3 where not mc.test_case_count = ( select count(*) from test_results_testcase trt where trt.connection_id = mc.id ) -
how to perform AND condition on many to many field django
i have two models class Sale(AuthorTimeStampedModel): product = models.ManyToManyField( Product, related_name='sale_product', null=True, blank=True) def __str__(self): return f"{self.id}" class Product(AuthorTimeStampedModel): id = models.IntegerField() now i want to apply query set to get all sales which have product_id 1 and 2 i am able to find Q function but it will result or condition but i want and condition -
How to modify a field's json in Django Rest Framework
There's this model: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') savers = models.ManyToManyField('User', blank=True, null=True, related_name='saved_posts') likes = models.IntegerField(default=0) And its Rest serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' There is a field named timestamp in the model. I used to use a custom serializer function inside the model class so it would return the timestamp as: 'timestamp': self.timestamp.strftime('%b %d %Y, %I:%M %p'). How can I do so using Rest? -
Zappa S3 Django Media Upload Times Out
I am trying to configure Zappa and Django to be able to upload media files but I am getting a weird permission error that is not specific enough for me to debug. When I go to the Django admin and upload a file with a few kbs to a model I get a: {"message": "Endpoint request timed out"} After further examination with zappa dev tail [1649077754253] [DEBUG] 2022-04-04T13:09:14.253Z b43408d4-f54d-4187-ab31-af6caf6dcddd Certificate path: /var/task/certifi/cacert.pem [1649077754254] [DEBUG] 2022-04-04T13:09:14.254Z b43408d4-f54d-4187-ab31-af6caf6dcddd Starting new HTTPS connection (1): bucket-static-media.s3.us-east-2.amazonaws.com:443 [1649077783696] 2022-04-04T13:09:43.695Z b43408d4-f54d-4187-ab31-af6caf6dcddd Task timed out after 30.03 seconds So the task times out I am making the assumption that it is some missconfigured permissions between the S3 and the Lambda. However I am not able to figure out what is wrong. If I look at the ZappaLambdaExecutionRole permission: It has a policy called zappa-permissions that has S3 permissions for all actions for all resources. The VPC linked to the Lambda Function is: vpc-b7e14cdc (XXX.XX.0.0/16) | Default Subnets: subnet-1ed00575 (XXX.XX.0.0/20) | us-east-2a subnet-f2cfcc88 (XXX.XX.16.0/20) | us-east-2b subnet-4cc2a900 (XXX.XX.32.0/20) | us-east-2c For the security group: Inbound Rules sgr-033b1c122d9c8fd4b – HTTPS TCP 443 Outbound Rules All I even created a VPC Endpoint to S3 global that connects to the security … -
Databse error while running Django with MongoDB
I'm trying to run my Django project and when I want to load the product to the homepage I encounter this problem : DatabaseError at / No exception message supplied Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1 Exception Type: DatabaseError Exception Location: E:\EKart\env\lib\site-packages\djongo\cursor.py, line 59, in execute Python Executable: E:\EKart\env\Scripts\python.exe Python Version: 3.10.2 Python Path: ['E:\\EKart', 'D:\\Python\\python310.zip', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python', 'E:\\EKart\\env', 'E:\\EKart\\env\\lib\\site-packages'] Server time: Mon, 04 Apr 2022 15:02:50 +0000 -
fetch record form table and print in views.py django
I am creating a webpage in Django, Where I'm printing some lines using a table from DB. I need to fetch user click and perform seprate action on each button dynamically. Here is my home.html <div> <table style="width:90%"> {% for request_ in request_index %} <tr> <form method="POST" action="{% url 'Request_for_DB_1' %}" enctype="multipart/form-data"> {% csrf_token %} <td><b> Would you like {{ request_.id }} to give {{ request_.user_name }} permission? </b></td> <td>&nbsp; </td> <td><input style="background-color:#CFCFCF; color:blue" type="submit" value="Yes" name={{ request_.id }}></td> <td><input style="background-color:#CFCFCF; color:blue" type="submit" value="No" name={{ request_.id }}></td> </form> </tr> {% endfor %} </table> </div> Here is Views.py def Request_for_DB_1(request): request_index = Permission_Request.objects.all() user_id = request_index.id current_user = request.POST.get('name') if user_id == current_user: clicked_user = "Condition is Correct... " else: clicked_user = "Condition is Wrong... " messages.info (request, clicked_user ) return redirect('/') By this view I am getting current_user = None always and this error 'QuerySet' object has no attribute 'id' The image of my table and tbale name is "Permission_Request" Kindly guide me how to fix this issue. -
Factory boy creation of an object with several default values (reverse foreign key)
I am using django 3.2 and factory boy 3.2.1 and try to create a factory of a plugin model which automatically creates 2 suitable configuration items with it: class PluginConfiguration(Configuration): plugin = models.ForeignKey( ProductPlugin, null=False, blank=False, on_delete=models.CASCADE, related_name="configurations", ) key = models.CharField(max_length=100,) value = models.CharField(max_length=255,) category = models.PositiveIntegerField(choices=Category.choices, default=Category.GENERAL,) class PluginConfigurationFactory(factory.django.DjangoModelFactory): class Meta: model = PluginConfiguration plugin = factory.SubFactory(ProductPluginFactory) key = factory.fuzzy.FuzzyText(length=20) value = factory.fuzzy.FuzzyText(length=20) category = PluginConfiguration.Category.GENERAL class ProductPluginFactory(factory.django.DjangoModelFactory): class Meta: model = ProductPlugin name = "MyPlugin" type = ProductPlugin.Type.APP password_required = False @factory.post_generation def configurations(obj, create, extracted, **kwargs): if not create: return if extracted: for n in range(extracted): PluginConfigurationFactory(plugin=obj) else: PluginConfigurationFactory( plugin=obj, key="base_name", value="cobra", category=PluginConfiguration.Category.GENERAL, ) PluginConfigurationFactory( plugin=obj, key="appId", value="MyApp", category=PluginConfiguration.Category.GENERAL, ) Extracted in this case should simply create a certain amount of config items. The problem is, that if I try to access plugin.configurations.all() I get an error message > configs = plugin.configurations.all() E AttributeError: 'PostGeneration' object has no attribute 'all' The factory is called this way plugin = ProductPluginFactory() configs = plugin.configurations.all() As this is not a simple attribute but an relation (RelationManager) the error is correct, but how would I do what I want then? Thanks & Regards Matt -
Add lat,lon pairs to an openlayers map in Django
I have a django platform that I have a created with the following: Upload/ handle an upload of a CSV file List of items that can be checked/ unchecked Handle an OpenLayers map A section to view a chart using Highcharts My question is how do I: Handle an uploaded CSV file with lat,lon, id so that once it is uploaded, the lat,lon points are automatically loaded on the openlayers map To view a timeseries chart based on the data queried from some database for each of the lat,lon points that is clicked by the user. Here is a sample csv file dataset: [lat,lon,ids] [0,30,1], [-1,31,2], [-3,32.3,3]} items you can check or uncheck to view <button>food price</button> <button>kilograms</button> timeseries data point 1 food price - [12, 15,18] kilograms - [30,41,45] point 2 food price - [10, 11,19] kilograms - [13,14,24] point 3 food price - [24, 65,88] kilograms - [31,41,45] Your help will be much appreciated -
Django Error: ModuleNotFoundError: No module named 'allauth'
I've follow the documentation in "django-allauth" But I got these errors: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' -
I encountered this problem when running a django server
I encountered this problem when running a django server This ptoto shows the problem -
How to import Django models in a script started with Popen()
My question is very similar with this one. The difference in my case is that the python script I want to start is in another Django app. That means the script on which I want to access my models (listener1.py), is not independent from my project. This is my project structure: my_project ├── my_app1 #This app contains models,views etc. │ ├── models.py │ └── apps.py │ └── ... ├── logic_app #This app contains several unrelated python scripts │ └── ManagerScript.py │ └── listener1.py │ └── ... In my apps.py: class MyAppConfig(AppConfig): name = 'my_app1' def ready(self): #Once app is ready, start the following script as a thread thread = Thread(target=ManagerScript.main) thread.start() In ManagerScript.py: #This thread is responsible for starting listener1.py as a Subprocess #(because this is a thread I can successfully import my Models here) #from my_app1 import models #This would work! tmp = ['python3','path/to/listener1.py'] Popen(tmp, preexec_fn=os.setpgrp) In listener1.py: from my_app1 import models #Does not work! ... My question is, considering the fact that the subprocess listener1.py is in logic_app folder, how could I import my Models in listener1.py script without using Django Management Commands? (Because using them would require to change my current project structure) -
How to get only related objects in django serializer with manyToMany?
class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = "__all__" class EmployeeSerializer(serializers.ModelSerializer): bookings_st = BookingSerializer(many=True, read_only=True) class Meta: model = Employee fields = "__all__" class ProjectSerializer(serializers.ModelSerializer): employees = EmployeeSerializer(read_only=True, many=True) class Meta: model = Project fields = "__all__" class Employee(models.Model): name = models.CharField(max_length=127) lastname = models.CharField(max_length=127) class Project(models.Model): title = models.CharField(max_length=127) employees = models.ManyToManyField(Employee, related_name='employees') class Booking(models.Model): start = models.DateField() end = models.DateField() employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='bookings_st') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='bookings_st') I get nested object, but how to get in Emploee only related to both (project and employee) bookings? Now I just get all bookings that this employee has. I mean that structure: project_1: emploee_1: [bookings_that_belong_to_THIS_PROJECT] -
Django: If form doesn't have information set value to
If value in interval is not selected, i would like to use default one ( 1d ) the value of intervals is not check properly if is there -
Django AttributeError: 'str' object has no attribute 'tag' [closed]
I'm new to programming. I have errors that I don't understand. I have a problem with "include". Can u help me please enter image description here -
Password Resetting view displays the django framework template even after adding template name in my urls.py
url path('reset_password/', auth_views.PasswordResetView.as_view(template_name = "registration/reset_password.html"), name ='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name = "registration/password_reset_sent.html"), name ='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name = "registration/password_reset_form.html"), name ='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name = "registration/password_reset_done.html"), name ='password_reset_complete') it only works for this path('reset_password/', auth_views.PasswordResetView.as_view(template_name="registration/reset_password.html"), name='reset_password'), -
Docker-compose executes django twice
I am running in windows 10, and trying to set up a project via docker-compose and django. When I run docker-compose run app django-admin startproject app_settings . I get the following error CommandError: /app /manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. Or when I do this docker-compose run app python manage.py startapp core I get the following error CommandError: 'core' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. Seems like the command is maybe executed twice? Not sure why? Docker file FROM python:3.9-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install RUN apt-get install -y \ libpq-dev \ gcc \ && apt-get clean COPY ./requirements.txt . RUN pip install -r requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app Docker-compose version: "3.9" compute: container_name: compute build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/app:/app ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db