Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: order set queries
I have following 3 models class Product(models.Model): name = models.CharField( blank=False, max_length=256 ) class TaskGroup(models.Model): name = models.CharField( blank=False, max_length=256 ) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=False, blank=True ) class Task(models.Model): name = models.CharField( blank=False, max_length=256 ) task_group = models.ForeignKey( TaskGroup, on_delete=models.CASCADE, null=False, blank=True ) execute_at = models.DateField( blank=True null=True, ) I want to get task groups for a product and order the tasks for each task group by execute_at. I can get all the task groups and all the tasks for a product by product = Product.objects.first() task_groups = product.taskgroup_set.all() task_groups contains all the groups and all tasks for each group. How can I order the tasks of each groups by execute_at. -
Delete model and DB table in Django with migrations
I have two models: Clause and Template, they have been migrated locally, but I want to delete one of them. The question is: If I just delete it from models.py and admin.py, and run makemigration and migrate, will delete and the related DB table as well? -
Getting a field from another django model?
How can I get the field pto from emplyees app and use it in the permission app. employee/models.py class Employee(AbstractUser): department = models.ForeignKey(Department, on_delete=models.CASCADE,blank=True, null=True) pto = models.IntegerField(default=20) is_deleted = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) roles = models.ManyToManyField(Role, related_name='+') def __str__(self): return self.username permission/models.py class Permission(models.Model): STATUS = ( ('PENDING', 'PENDING'), ('DENIED', 'DENIED'), ('ACCEPTED', 'ACCEPTED') ) user = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='lorem') description = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) date = models.DateField() status = models.CharField(max_length=200, choices=STATUS, default=STATUS[0][0]) is_deleted = models.BooleanField(default=False) def __str__(self): return self.description sorry if a was not clear, thanks in advance -
If object exist move me here if not here, PYTHON>Django
i have little issue: I have created an organigram in which I have a list of managers and when I click on a manager the link takes me to a list of their sub employees, but some managers do not have any employees under them and then an empty list is displayed. I am looking for a solution where the link redirects to 1 of 2 links: 1. If "the manager has employees moves to the list", 2. if "manager has no employees moves to X(another employee details link)" Solution that looks in the database for sub employees if they are there then link 1, if not there then link 2. my models:Managers Managers2 my views:Manager views Manager2 views my urls:Urls my main site where link is:Main -
serialize nested objects in djangoresetframework
i am using django-mptt for implement nested categories. this is my model : class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") i have some nested objects like mobile --> samsung --> s_group and so on. i want to serialize all the children categories when return parent category something like this : { "name" : "mobile", "children" :{ "name" : "samsung", "children" { "name" : "s_group", "children" : { "name" : "something", "children" : {} } } } how can i implemnt this? -
django-bootstrap4 doesnt recognize forms passed to context
Im trying to pass two forms in to my view: @login_required() def register(request): registered = False if request.method == 'POST': user_form = UserCreateForm(data=request.POST) profile_form = ProfileCreationForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'logo' in request.FILES: profile.logo = request.FILES['logo'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserCreateForm() profile_form = ProfileCreationForm() return render(request, 'companies/registration.html', {'form': user_form, 'profile_form': profile_form, 'registered': registered}) Then in my html Im calling the two forms using django-bootstrap4: {% extends 'base.html' %} {% load bootstrap4 %} {% block content %} {% load static %} <div class="container"> {% if registered %} <p>Thank you for registering</p> {% else %} <div class="form-group mt-5"> <h3>Register</h3> <form method="POST"> {% csrf_token %} {% bootstrap_form user_form %} {% bootstrap_form profile_form %} <input class="btn btn-primary" type="submit" value="Register"> </form> </div> {% endif %} </div> {% endblock %} As a result I get the error: raise BootstrapError('Parameter "form" should contain a valid Django Form.') bootstrap4.exceptions.BootstrapError: Parameter "form" should contain a valid Django Form. [06/Apr/2021 13:57:47] "GET /companies/register/ HTTP/1.1" 500 162738 The same time if I pass in only one form and call it 'form' then no errors appear: from views: return render(request, 'companies/registration.html', {'form': user_form, 'profile_form': … -
Avoiding InconsistentMigrationHistory with explicit inserts in migrations
I have a little problem with the order of the migrations. The fact is that in my database there is a "Products" model whose migration is one of the first in the history list, call it 001_products. After this migration, others are executed that make inserts in this same table (some inserts necessary for the basic operation of the application), called migration 002_inserts_products. The problem appeared when modifying the "Products" model, call it 003_modify_products migration. The migration was applied after the inserts and made the tests fail (tests that generate a test database doing all the migrations), which followed this order: 001_products 002_inserts_products 003_modify_products The solution then was to add a dependency on migrations that made inserts in "Products" with respect to the subsequent migration that modified that table. That is, make 002_inserts_products dependent on 003_modify_products. However, this, which worked in the tests and locally (where the modification in "Products" had already been applied), does not work in production, since there the migration that has not been applied is the one that modifies the "Products" model ". That is, the panorama in production is: [X] 001_products [X] 002_inserts_products [ ] 003_modify_products When trying to do the new migration, the error … -
Django cropper.js is rotating the elongated portrait images in mobile view
Hi I have been following this tutorial for making cropper.js worked in my Django app. The issue is, that whenever I try to upload an image in mobile view the canvas rotates the image. Like this: Can anyone please point out what the issue is and how can I prevent this? -
How to Upgrade Amazon Elastic Beanstalk Linux 1 to Linux 2 for Django Application
I am trying to upgrade a Django application from AWS Elastic Beans Python 3.6 running on 64bit Amazon Linux/2.9.20 to Python 3.8 running on 64bit Amazon Linux 2/3.2.0. It runs locally. When I try and deploy to Elastic Beanstalk I'm getting the following error: Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/current/src/core/wsgi.py", line 14, in <module> Apr 6 10:30:48 ip-172-31-43-9 web: application = get_wsgi_application() Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application Apr 6 10:30:48 ip-172-31-43-9 web: django.setup(set_prefix=False) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/__init__.py", line 19, in setup Apr 6 10:30:48 ip-172-31-43-9 web: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ Apr 6 10:30:48 ip-172-31-43-9 web: self._setup(name) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup Apr 6 10:30:48 ip-172-31-43-9 web: self._wrapped = Settings(settings_module) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ Apr 6 10:30:48 ip-172-31-43-9 web: mod = importlib.import_module(self.SETTINGS_MODULE) Apr 6 10:30:48 ip-172-31-43-9 web: File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module Apr 6 10:30:48 ip-172-31-43-9 web: return _bootstrap._gcd_import(name[level:], package, level) Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Apr 6 10:30:48 … -
DRF OPTIONS request - include initial/default choices
I'm using options to populate select inputs in my project. Is there a way to include also information about default values? For this field: DELIVERY_METHOD__SHIPPING_ONLY = 'shipping_only' DELIVERY_METHOD__LOCAL_PICKUP_ONLY = 'local_pickup_only' DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP = 'shipping_and_local_pickup' DELIVERY_METHOD_CHOICES = ( (DELIVERY_METHOD__SHIPPING_ONLY, 'Shipping only'), (DELIVERY_METHOD__LOCAL_PICKUP_ONLY, 'Local pickup only'), (DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP, 'Shipping & local pickup'), ) delivery_method = models.CharField(max_length=32, choices=DELIVERY_METHOD_CHOICES, default=DELIVERY_METHOD__SHIPPING_ONLY) The OPTIONS actions.POST.delivery_method is this: "delivery_method": { "type": "choice", "required": false, "read_only": false, "label": "Delivery method", "choices": [ { "value": "shipping_only", "display_name": "Shipping only" }, { "value": "local_pickup_only", "display_name": "Local pickup only" }, { "value": "shipping_and_local_pickup", "display_name": "Shipping & local pickup" } ] }, But it should also say that Shipping only is the default one so I can prepopulate the input with this value. Is there a built-in way to do that? -
How to run a project in single docker container and run the installed dependencies of project in docker filesystem instead of using docker images?
I am new to docker I am noob and I have a full running application in docker consist of multiple containers responsible to run the project. I want to make the container image and gave it to the client but when I pushed my project to docker-hub it can only contain one container in the repository at a time. So, now I want to work with single container instead of using the multiple containers running MySQL and Redis as the dependencies of project. So, I installed redis and MySQL inside the docker file-system using bash of my container. But my project is not working without running my project I cannot start the redis and MySQL installed inside the container which is running on Debian Linux and when I run my project I can access the bash of my container and start the services but still my django app in the container is giving errors relevant to SQL. Can anyone tell me how to tackle this situation? -
Send Django-form to other server for data-handling
I have a Django app which is hosted on Google App Engine. One of the models consist of three fields class product_prices(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) last_price = models.FloatField(default=0) data = models.TextField(max_length=512) I want to do some database calls, based on the information entered, and then alter the data-field, the last-price based on the data returned from the database, e.g in my (pseudo) view below, I call MyDatabaseFunctionCall(form) to do those calculations. What I would prefer is, to have that calculation being on another server with some more CPU/RAM such that I don't slow down GAE hosting my application. #Current views.py on GAE def add_link_to_track(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyForm(request.POST,instance = instance) if form.is_valid(): #Create the dummy-model form.save() #Do the calculation in the back-ground thr = threading.Thread(target=MyDatabaseFunctionCall,args=(form,),daemon=True) #Alters the data thr.start() return redirect("my_site") else: form = MyForm() return render(request, "my_site/my_template.html",context=context) Can a form-instance e.g be pickled and thus send back-n-forth between servers in some way? Or is it better having a "temp-database" that I push the form information to uppon creation and then having the compute-server monitoring that database such that it can pull new forms, alter … -
AWS resend invite link after expiration
from the boto3 documentation i came to know we need to set the MessageAction="RESEND" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. def get_set_cognito(sender, instance, *args, **kwargs): self = instance if self.pk is None: client = boto3.client('cognito-idp', region_name=settings.AWS_DEFAULT_REGION) # try: # # Check if the user exists in Cognito # existing_user = client.admin_get_user(Username=self.user.email, # UserPoolId=settings.COGNITO_USER_POOL_ID) # except client.exceptions.UserNotFoundException: # pass try: # if not existing_user: response = client.admin_create_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email, ForceAliasCreation=True|False, MessageAction='RESEND', DesiredDeliveryMediums=['EMAIL'], UserAttributes=[ { 'Name': 'custom:backend_url', 'Value': settings.BACKEND_API_URL }, { 'Name': 'custom:backend_id', 'Value': settings.BACKEND_ID }, { 'Name': 'email_verified', 'Value': 'true' }, { 'Name': 'email', 'Value': self.user.email }, { 'Name': 'family_name', 'Value': self.last_name if self.last_name else ' ' }, { 'Name': 'given_name', 'Value': self.first_name if self.first_name else ' ' }, { 'Name': 'phone_number', 'Value': self.phone if self.phone else ' ' } ], ) self.user.username = response['User']['Username'] if(len(response['User']['Username']) < 3): logger.error("empty response from cognito for email - " + self.user.email) logger.error(response) self.user.delete() else: self.user.save() # else: # self.user.username = existing_user['Username'] # self.user.save() except client.exceptions.UsernameExistsException: # existing_user = client.admin_get_user(Username=self.user.email,UserPoolId=settings.COGNITO_USER_POOL_ID) existing_user = client.admin_get_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email ) self.user.username = existing_user['Username'] self.user.save() except Exception as e: logger.error( "there was an error trying to … -
is there way to add style to username field - django forms
is there way to add style to username field - django forms , i tried use self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) but it's not work why class UserForm(forms.ModelForm): password = forms.CharField(required=True,label=' pass',widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':' pass ','style': 'font-size:24px;text-align: center;'})) first_name = forms.CharField(required=True,label=' first name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' first name ','style': 'font-size:24px;text-align: center;'}) ) last_name= forms.CharField(required=True,label=' 2nd name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' 2nd name ','style': 'font-size:24px;text-align: center;'}) ) email= forms.EmailField(required=True,label=' email ',widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':' email ... youremail@email.com','style': 'font-size:24px;text-align: center;'}) ) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','email','password') def __init__(self, *args, **kwargs): super(UserForm,self).__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) -
What If I compile the py manage.py collectstatics?
What If I compile the py manage.py collectstatics? I am on my localhost. I have configured all the s3 url accourding to given url. We can see on last paragraph then it's telling run python manage.py collectstatic . My question is why we are doing this? Do we need to run this on every static or media changes? I tried to run this but it asking do you want to override this? Can I simply do yes? If I give yes then what will happen? I am not much aware in this topic collectstatics -
Getting wrong value when reading an xlsx file using openpyxl
i'm trying to read values from an xlsx file containing formulas using openpyxl, i noticed that for some cells i'm getting a wrong value. here's the XLSX exemple. the result i get. and the code: wb = openpyxl.load_workbook(excel_file, data_only=True) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["Feuil1"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: #cell.number_format='0.0########' print(cell.number_format) row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) -
How do i share my django models with a child process using python multiprocessing?
I am trying to pass my django models to another child process, for that i am using the following code from multiprocessing import Process from multiprocessing.managers import BaseManager from role.models import Role from group.models import Group from kafka import KafkaConsumer class KafkaProcessManager(BaseManager): pass def consume_events(kafka_ip_port, events_topic, Role, Group): # To consume latest messages and auto-commit offsets consumer = KafkaConsumer(events_topic, bootstrap_servers=[kafka_ip_port]) for message in consumer: print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition, message.offset, message.key, message.value)) #if (message["MODEL"] == "UserFeature" and message["TYPE"] == "DEACTIVATED"): group = Group.objects.get(id=1) group.description = "UPDATED AFTER CONSUMING EVENT THROUGH CHILD PROCESS" group.save() kafka_manager = KafkaProcessManager() kafka_manager.register('Role', Role) kafka_manager.register('Group', Group) kafka_manager.start() Role = kafka_manager.Role() consumer = Process(target=consume_events, args=(kafka_ip_port, events_topic, Role, Group, )) consumer.start() consumer.join() The intention is to do some processing/updating when a certain message (event) is receieved. But i am getting an error on line Role = kafka_manager.Role() AttributeError: Manager isn't accessible via Role instances. Can anyone guide me how to pass the model instances to the child process. Thanks is advance. -
Django REST framework POST without insert
I'm building a Django REST API which has access to our existing database with existing users. The purpose of this API is allowing the upcoming mobile application to make requests. I'm sending a post request to a view with custom authenticator to verify the sent account details. My existing model: class LogonAccount(models.Model): id = models.BigIntegerField(primary_key=True) email = models.TextField() two_step_enabled = models.BooleanField() password = models.TextField(blank=True, null=True) username = models.TextField(unique=True, blank=True, null=True) My View and Serializer class LogonAccountViewSet(viewsets.ModelViewSet): queryset = LogonAccount.objects.all().order_by('username') serializer_class = LogonAccountSerializer class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = LogonAccount fields = ('username', 'email') Sending a post request to this endpoint with username and password in its body keeps returning me a bad request (400) with: { "username": [ "logon account with this username already exists." ], "email": [ "This field is required." ] } Making the fields not required in the serializer just changes the error to database constraints (null value in column id) class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField(required=False) email = serializers.CharField(required=False) class Meta: model = LogonAccount fields = ('username', 'email') I'm not trying to insert data, just trying to validate it. What am I doing wrong or how do I stop it from trying to insert data? -
Converting djangos object.values dict into native datatype?
I'm trying to get specific fields from my database using the object.values() attribute, as such: stocks = Stock.objects.values("ticker", "stock", "exchange__exchange_code", "earnings_yield", "roic") The reason I'm not using Stock.objects.filter()... is because I only need a subset of the fields, and as far as I know, values() is the way to go. stocks[0] returns this: { 'ticker': 'ATRLJ-B', 'stock': 'Atrium Ljungberg AB (publ)', 'exchange__exchange_code': 'ST', 'earnings_yield': Decimal('0.0250'), 'roic': Decimal('0.0200') } How do I get earnings_yield and roic as regular floats? E.g, proper JSON formatted I tried clean = json.dumps(list(stocks), cls=DjangoJSONEncoder) stocks = json.loads(clean) But that returns the decimals as strings, not decimals -
How to call manager & helper classes that are used multiple times in Django/Python?
Say I have a manager class SomeManager that a view uses multiple times in multiple methods, what's the pythonic way to call the manager? In other languages, I would use a method in the view's parent class that in python would look something like ParentView(): some_manager_instance = None def some_manager(self): if not self.some_manager_instance: self.some_manager_instance = SomeManager() return self.some_manager_instance ChildView(ParentView): def do_something(self): self.some_manager().do_something() which any view's methods could then call, without having to recreate the manager so many times. Or, is it more pythonic to just set some_manager = SomeManger() on the views that actually need the manager? -
Alter Django 3+ database schema for SQL Server
By default Django creates database tables with schema [dbo] during migration. These links (Django database tables being created under incorrect schema & https://stackoverflow.com/a/47535618/3960991) present solutions to modifying the schema name in Django 2. These solutions produce errors during migration in Django 3. I have not been able to find any discussion of this issue since Django 3 was released in December 2017. -
TypeError: create_user() missing 2 required positional arguments: 'email' and 'password' in Django Rest Framework
I am trying to create a superuser with email and password only but I am getting the above error. After running py manage.py createsuperuser , it asks for admin and password only and I provide respective fields but after bypassing password validation with yes, it gives above error. class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, first_name, last_name, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None #email = models.EmailField(_('email address'), unique=True) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email -
Django signals not called when app is registered using package name but works with app config class
I was experiencing a problem where my signals were not getting called. I have an app called users and in it I have a model for Profile that extends the django User model and when a user object is saved, I need to create a corresponding profile for it for that I added a signals.py module in the users app, here's my signals file from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): instance.profile.save() And inside my settings.py INSTALLED_APPS I added my app like this INSTALLED_APPS = [ # other apps 'users', ] And my users/apps.py looks like this from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals After registration, the user object was getting created but no corresponding profile. I even put some debug statements in the signal receivers just to confirm my receivers were not getting called and yes the receivers were never getting called. I couldn't find a solution to this as all answers I found on SO showed similar configurations that worked. Out of curiosity I decided to … -
nginx gives 502 Bad Gateway with Django, Docker, gunicorn
I know that this type of question has already been asked numerous times, but the fact that everybody's config is different makes asking it again justified. I'm trying to make nginx work with Django and gunicorn, using Docker to containerize everything. Here's the Dockerfile: FROM python:3.7 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN pip install -r requirements.txt COPY . /app/ RUN chmod -R 777 . EXPOSE 8000 CMD [ "gunicorn", "-b", "0.0.0.0:8000", "computer_vision.wsgi" ] Here's nginx's default.conf: upstream django { server computer-vision:8000; } server { location /static { try_files $uri $uri/ @proxy_to_app; } location @proxy_to_app { proxy_pass http://django; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Here's docker_compose.yml: version: "3.7" services: computer-vision: build: . image: cv:cv ports: - 8000:8000 nginx: image: nginx ports: - 8080:80 volumes: - ./computer_vision/computer_vision_api/static:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf gunicorn runs successfully, but nginx gives a 502. Here's the console display: nginx_1 [error] 30#30: *4 connect() failed (111: Connection refused) while connecting to upstream, client: ip_address, server: , request: "GET / HTTP/1.1", upstream: "http://ip_address:8000/", host: "localhost:8080" The Dockerfile, default.conf and docker-compose.yml are all in the same directory. Questions: Is server inside upstream in default.conf … -
How to handle media files in production for django
somehow I have handled the media files by keeping the media_root under the static and then by collectstatic command it works in production if I set debug to True else it doesn't work. But neither I want to set debug to True nor I want to put media_root under the static directory. So, what's the solution now apart from AWS s3 because it sucks a lot when it comes to sign up even for free tier.