Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Exception Value: The 'image' attribute has no file associated with it
Hi everyone I'm trying to create an auction system with Django. But when I go to the item profile, Django sends me an error: Exception Value: The 'image' attribute has no file associated with it. auction.html {% extends "base.html" %} {% block content %} {% load static %} <div class="page-header"> <h1>OPEN AUCTIONS</h1> </div> <div class="container"> <div class="row"> {% for item in auction %} <div class="col-sm-4"> <div class="card border-secondary" style="width: 25rem;"> <div class="card-header"> Auction {{item.id}} </div> <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> <div class="card-body"> <h3 class="card-title" style="text-align:center" >{{ item.object }}</h3> <p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br> End: {{ item.close_date }}</p> <form method="POST"> {% csrf_token %} <input type="number" name='auct_id' value={{item.id}} readonly> <button type="submit" class="btn btn-primary btn-sm">Go</button> </form> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this: view.py @login_required(login_url="login") def auction(request): if request.user.is_superuser: messages.error( request, "super user can access to admin/ and new_auction page only" ) return redirect("new_auction") auction = Auction.objects.filter(active=True) for data in auction: check = check_data(data.close_date) if check is False: data.active = False data.save() check_winner( request, data.id ) check_prof = check_profile( request ) if check_prof is … -
How to deploy django application with celery and celery beat in digitalocean droplet?
Hello developers i nedd to deploy django application with celery and celery beat in digitalocean droplet. where celery worker and celery beat will execute simulteneoulsy. for celery worker: celery -A <project_name>.celery worker --pool=solo -l INFO for celery beat: celery -A <project_name> beatb -l INFO afterward it will run. -
Django ImageField not updating database if i click submit button, but does it if i click enter key
The problem is The problem is that after filling a form without an image and clicking on the submit button, django does nothing and the default image does not get displayed, but if i click the Enter key on my keyboard it works, it shows the default image Can someone please tell me why this is happening, and what is the solution for it I tried changing the url for the button, expecting it to work just as it would if I clicked enter. But that did not work. I have been stressing about this for the past week. And Thanks in advance for everyone who helped. -
Django - Only update FileField column without overriding other columns
In Django, I have a model: class List(models.Model): item = models.CharField(max_length=200) document = models.FileField(upload_to='documents/', null=True, blank=True) Also, I have a page which is to ONLY upload a file to List.document for an existing List: In views.py, I have def upload(request, item_id): if request.method == 'POST': item = List.objects.get(pk=item_id) form = ListForm(request.POST, request.FILES, instance=item) if form.is_valid(): form.save() messages.success(request, 'File saved successfully.') else: messages.error(request, f'File not saved properly: {form.errors.as_data()}') return redirect('home') . However, since the form doesn't include List.item, while clicking Upload, an error occurs File not saved properly: {'item': [ValidationError(['This field is required.'])]}. The easiest way may be add List.item as a hidden element in the html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-10"> <input type="file" class="form-control" name="document" /> </div> <div class="col-md-2"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Upload</button> </div> </div> </form> Nevertheless, is there a better way to get over this? Maybe any options to skip overwriting existing columns? Thanks! -
Trigger React Event from Django Frontend
I want to open a Dialog-window in React whenever the User clicks on the corresponding button in Navbar. The Problem is that the Navbar is part of a Django Frontend. I have tried updating a value in localstorage but I wasn't successful. I have tried using the window.addEventlistener() , but it wouldn't update if changes where made from the Django Navbar. useEffect(() => { window.addEventListener('storage', console.log("CHANGED")) return () => { window.removeEventListener('storage', console.log("CHANGED")) } }, []) Django Template <div class="navbar-nav mr-auto" id="ftco-nav"> <button id="experimentbtn" onClick="open_experiment()" class="btn nav-link">Experiment</button> </div> <script> function open_experiment() { localStorage.setItem('experiment', 'true'); } </script> <div id="root"></div> #This is where the React part is rendered The suggested solution doesn't have to be related to this, i just want to know if there is any other way to make Django communicate with React to trigger such an event switch? -
How to prune inactive / bad APNs tokens in Django-push-notifications
I'm using django-push-notifications (DPN) to send notification to an iOS app. When I send a notification, DPN gives me the response from APNs as a dict with the device tokens and their status. r = devices.send_message(message="Fancy pansy message.", sound="default") Where the response looks something like: r = [ { '<devicetoken1>': 'Success', '<devicetoken2>': 'BadDeviceToken', '<devicetoken3>': 'Success', } ] I have a view in Django which takes POST requests. I use this endpoint to post the message I send to APNs with send_message() as well as save the message to my DB. So my plan was to add the following simple logic to the same view to prune the DB each time I get feedback on expired / bad device tokens from APNs (or something like it, I may of course need to add more statuses than "BadDeviceToken"). for token_str, token_status in r[0].items(): if token_status == 'BadDeviceToken': APNSDevice.objects.filter(registration_id=token_str).delete() My question is if there is a better way of doing this? Should pruning be done with some periodic task instead? Are there any issues with doing this kind of logic in the views in Django? Or am I missing any existing solutions to this problem (pruning tokens) in either Django or DPN? Cheers! -
How can I get a Django template message displayed when I select a value from a dropdown list that matches a condition in the parent table?
I have a form whose constituent fields are foreign keys to respective parent models as shown below: class vehicle(models.Model): STATUS = [ (OPERATIONAL, ('Operational')), (GROUNDED, ('Grounded')), (NA, ('Not Applicable')), ] reg no = models.CharField(max_length=100, null=True) operationalstatus = models.CharField (max_length=100, choices=STATUS, null=True) #####child model### class managecar(models.Model): reg_no = models.ForeignKey(vehicle, on_delete=models.CASCADE, null = True) location = models.CharField(max_length=100, null=True) ####forms.py#### class manageForm(forms.ModelForm): class Meta: model = managecar fields = '__all__' I created a view as shown below and linked a url to it to be called by ajax on the frontend to trigger a message if vehicle selected in the form is 'grounded' but it returns 404 in the console while am expecting it returns a message of vehicle is grounded if I select a vehicle that is listed grounded in the parent model. views.py def validate_operation_status(request): grounded = request.GET.get('grounded', None) data = { 'is_grounded': vehicle.objects.filter(operational_status__iexact='grounded').exists() } return JsonResponse(data) ajax method $("#id_registration_no").change(function () { console.log( $(this).val() ); $.ajax({ url: 'ajax/validate-status/', data: { 'grounded': id_registration_no }, dataType: 'json', success: function (data) { if (data.is_grounded) { alert("This vehicle is grounded."); } } }); }); I'd appreciate to be guided in the right direction or someone to point out where I am failing. Thank you in … -
Django - Add help text to field inherited from abstract base class
I just discovered the "help_text" attribute at Django model fields which automatically adds help textes to fields e.g. in the admin panel. Again, what a nice Django feature! Now I have the problem that I want to add the help_text to a field which is inherited from a parent abstract base class... how could I achieve this? class AbstractBioSequence(models.Model): """ General sequence (DNA or AA) """ name_id = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True, blank=True) sequence = models.TextField() class Meta: abstract = True class DnaSequence(AbstractBioSequence): some_dna_field = models.TextField() # -------- I want to add a DnaSequence specific helper text to the "sequence" field here -
How to get Google Calendar API working in production to create an event
Problem I'm trying to solve: Using Google Calendar API to create a calendar event. It works on locahost but not in production following the Google Documentation. I'm looking for a solution to get it working in production. What I've tried: I've spent a long time looking at solutions on here including this popular one: Google Calendar API authorization working on localhost but not on Heroku but for me I'm not using pickle. I also attempted all the relevant changes in the answer in relation to my code but I still could not get it to work. I have also made sure that my API console includes the relevant permissions. What's happening: Terminal logs are showing that my code attempts to open a browser on the server machine "Please visit this URL to authorize this application" instead of popping up a browser window for the user. This is most likely because my first try block is failing - which I think is where the problem lies. Please also note I have replaced my redirect URL in the code below for privacy reasons to myurl.com/calendar/. The redirect is simply set to the same page where I am running the code from. Google … -
Unique constraint in my model in my django project?
I would like to configure my Teacher model so that I can have several teachers with the same name, the same age but different departments How to do ? class Teacher(models.Model): name=models.CharField(max_length=70) age=models.IntegerField() service=models.CharField(max_length=100) Exemple output on my database : Name Age Service Arnaud 29 Science Carmen 37 Medecine Arnaud 29 Geologie -
Django: Get multiple id's from checkbox
I'm having problems getting multiple IDs from checkbox. It shows an empty list, and if I inspect my page, it doesn't even show it's value. Unlike the other, obj.stage for example, if I highlight this it shows it's value. So it's not possible to get each id on checkbox? Or I'm just doing it wrong? Hope you can help me, thank you! index.html <a class="btn btn-primary btn-xs" href="/save/">Save</a> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.id}}"></td> <td>{{ obj.stage }}</td> <td>{{ obj.time }}</td> <td>{{ obj.sample_number }}</td> </tr> {% endfor %} views.py sid = request.POST.getlist("sid") samples = SampleHandle.objects.filter(id__in=sid)[0:11] -
Django - givingan unique ID to a blog post/element so it could be used with http referer
I am currently creating my first project and I am using an HTML template that I found online. It is a social media application where you should be able to upload a photo, like the photo, leave a comment, etc. The issue is that I implemented all those functions, but liking, commenting, copying the URL (share buttong) refreshes the whole page and you end up at the very beginning of the page, because I am not sure how to refer the user to the post they liked/commented. I am using return redirect(f'{request.META["HTTP_REFERER"]}#{photo_id}') , but since my posts don't have an unique identifier, it does nothing. Any tips would be greatly appreciated. Thanks in advance! -
Render options of ModelChoiceField
I want to render the options for a ModelChoiceField: {% for value, label in form.fields.event_type.choices %} <option value="{{ value }}" {% if form.fields.event_type.value|add:"" == value %}selected="selected"{% endif %}> {{ label }} -- {{ form.event_type.value }} .. {{ value }} </option> {% endfor %} But this does not work: selected="selected" is not set. The output: <option value=""> --------- -- 2 .. </option> <option value="1"> OptionOne -- 2 .. 1 </option> <option value="2"> OptionTwo -- 2 .. 2 </option> This is strange, since the output "2 .. 2" did not trigger the "if" to include selected. How to solve this? -
sending mail works with mailtrap but not with an outlook server or other
I made a contact form, I tested with the mailtrap service and it works I receive the messages well. But when I put the smpt parameters for a real mail account I have this error message SMTPRecipientsRefused at /contact/ {'info@mysite.net': (550, b'relay not permitted: you must be authenticated to send messages')} the smtp server and the mail account is on the host alwasdata.net, but I tested with an outloock account it's the same thing always this same error. it seems to come from the line in the contact method: message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, in settings.py i have this config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = "info@mysite.net" EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'smtp-blablabla.net' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 in a views.py def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Message d'un visiteur sur votre site" body = { 'Nom': form.cleaned_data['first_name'], 'Tel': form.cleaned_data['tel'], 'Email': form.cleaned_data['email'], 'Message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail( subject, message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') form = ContactForm() return render(request,'pages/email_form.html',{'form':form}) the forms.py from django import forms class ContactForm(forms.Form): first_name = forms.CharField(max_length=100, required=True) tel = forms.CharField(max_length=15, required=True) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea, required=True) -
install postgresql extension before pytest set up database for django
I need to install citext extension to my postgresql database for django project. For the project itself it went smoothly and works great via migrations, but my pytest is configured with option --no-migrations, so pytest create database without running migrations. How can i make pytest to install citext postgres extension before tables are created? Currently i'm getting - django.db.utils.ProgrammingError: type "citext" does not exist while pytest trying to create table auth_users sql = 'CREATE TABLE "auth_user" ("id" serial NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" timestamp ...T NULL, "is_active" boolean NOT NULL, "date_joined" timestamp with time zone NOT NULL, "email" citext NOT NULL UNIQUE)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fb313bb0100>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7fb30d9f8580>}) I tried to use django_db_setup fixture, but i did not figure out how to change it, because something like this @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_createdb, django_db_modify_db_settings, ): """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: from pytest_django.fixtures import _disable_native_migrations _disable_native_migrations() if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): from django.db import connection cursor = connection.cursor() cursor.execute("CREATE EXTENSION IF NOT EXISTS … -
Unable to login even after entering correct credentials
I have created a seperate app for user account management which handels registration, login and logout. However, after successful signup, I'm unable to login even after using the correct credentials provided during signup. Here are the required code for the review: models.py `from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('Email is required.') if not username: raise ValueError('Username is required.') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name,`your text` ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self.db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True` forms.py `from crispy_forms.helper import FormHelper from django import forms from .models import Account class RegistrationForm(forms.ModelForm): first_name = … -
enctype='multipart/form-data' is not storing images in django?
I wanted to save text and images in my database in django but when i used enctype='multipart/form-data' it is not storing the image. When i do it without enctype='multipart/form-data' it is storing the name of image this is my index.html ` <form method="POST" action="/index" enctype='multipart/form-data'> {% csrf_token %} <div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div> <div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div> <div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div> <div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div> <div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div> <div>Dish image: <input name="dish_image" type="file"></div> <button type="submit" class="btn btn-success">Submit</button> </form> this is my views.py def index(request): if request.method == "POST": dish_name = request.POST.get('dish_name') dish_size = request.POST.get('dish_size') dish_price = request.POST.get('dish_price') dish_description = request.POST.get('dish_description') dish_image = request.POST.get('dish_image') dish_category = request.POST.get('dish_category') item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description,dish_category=dish_category, dish_image = dish_image, dish_date = datetime.today()) item.save() dishs = dish.objects.all() params = {'dish': dishs} return render(request, "card/index.html", params) this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here … -
How to monitor a thread in python?
I'm having a kafka consumer which is running in a thread in my django application, I want to apply some monitoring and alerting on that thread. So how can I add thread monitoring (check state if it is alive or dead) and if thread is dead then need to raise an alert. I have tried monitoring by creating scheduler which runs every 10 mins and calls thread.is_alive() method. But the problem is the scheduler is running in a different process and unable to access main process' s thread. So how can I resolve this? -
Two models with one-to-many into single JSON dict
I have two models for 'PO Header' and 'PO Item' data like this: class po(models.Model): po_number = models.CharField(max_length=16, null=True) buy_org = models.CharField(max_length=20, null=True) supplier = models.CharField(max_length=16, null=True) class poitm(models.Model): po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitm') po_li = models.CharField(max_length=6, null=True) matnr = models.CharField(max_length=16, null=True) quantity = models.DecimalField(decimal_places=6, max_digits=16, null=True) I try to create a view that returns a json object like this: [{'po_number':'45000123','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123456','quantity':'12'},{'po_li':'020','matnr':'123457','quantity':'8'}]},{'po_number':'45000124','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123235','quantity':'15'},{'po_li':'020','matnr':'123499','quantity':'24'}]} ] In principle a list of purchase orders with each purchase order containing a list of purchase order items. I managed to create queryset containing the data like I need it but for performance reasons when using datatables.net with dom data I need to return the data in json format instead of looping through the queryset in the html template. def purchaseorders(request): polist=purchaseOrder.objects.all() itemlist=poItem.objects.all() for poentry in polist: poentry.itemlist=itemlist.filter(po_id=poentry.id) return render(request, 'purchaseorders.html', {"poitems":polist}) This seems to create a queryset with each object of a queryset. This then gives me a problem when I try to serialize it to json. Only the fields from the outer queryset are in the json result. I looked and tried for two solid days, turning in circles now, please help. -
How to get data from database, whenever database is updated in database Caching in Django [closed]
When i hit API every time data is fetching from database caching, even though database is updated(add or remove). How to communicate with cache and database, when changes are made in database -
Replace Django Admin Login page
I need to replace the Django Admin Login page. The reason for that is that I've added some extra authentication at my own login page, however, I don't know how to override the login on the admin site. -
Django authentication password returning False
I'm trying to create an authentication system using Django with a custom backend and user class, but every time I try to authenticate with an existing user and password in my Postgresql database the check_password() function always returns False and I can't proceed. Here's the code for the UserBackend on backends.py from django.contrib.auth.backends import ModelBackend from .models import user class UserBackend(ModelBackend): def authenticate(self, **kwargs): username = kwargs['username'] password = kwargs['password'] print('user: ', username) print('pass: ', password) #try: user_ = user.objects.get(username=username) try: print(user_.check_password(password)) if user_.check_password(password) is True: #Here check_password() is always false return user_ except user.DoesNotExist: pass def get_user(self, user_id): try: return user.objects.get(pk=user_id) except user.DoesNotExist: return None views.py def signin(request): now = datetime.now() if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = UserBackend.authenticate(ModelBackend(),username=username, password=password) if user is not None: #auth.login(request, user) return redirect('/index') else: messages.info(request, 'invalid username or password') return redirect("/signin") else: return render(request,'signin.html') return render(request, 'signin.html') models.py class user(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.TextField() real_name = models.TextField() email = models.TextField() password = models.TextField() description = models.TextField() last_login = models.DateField() created_at = models.DateField() class Meta: managed = False db_table = 'user' def __str__(self) -> str: return self.username what am I doing wrong? -
How to search inside json file with redis?
Here I set a json object inside a key in a redis. Later I want to perform search on the json file stored in the redis. My search key will always be a json string like in the example below and i want to match this inside the stored json file. Currently here i am doing this by iterating and comparing but instead i want to do it with redis. How can I do it ? rd = redis.StrictRedis(host="localhost",port=6379, db=0) if not rd.get("mykey"): with open(os.path.join(BASE_DIR, "my_file.josn")) as fl: data = json.load(fl) rd.set("mykey", json.dumps(data)) else: key_values = json.loads(rd.get("mykey")) search_json_key = { "key":"value", "key2": { "key": "val" } } # here i am searching by iterating and comparing instead i want to do it with redis for i in key_values['all_data']: if json.dumps(i) == json.dumps(search_json_key): # return # mykey format looks like this: { "all_data": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } -
i have a basic register api,however, it seems to be throwing this error, HTTP_201_CREATED' not found
i am getting this error ,i tried to convert fields variable in serializers.py to my_fields but it cannot be changed,also i tried to convert values of fields variable in list but of no use**.it was working at first but i dont know what seems to be the problem Internal Server Error: /api/auth/signup Traceback (most recent call last): File "/home/technogetic/Documents/Django Rest Framework/VPAProject/firstapp/views.py", line 97, in post return Response[{'msg':'Registration Successfull, A Verification code has been send to your Email'}, status.HTTP_201_CREATED] AttributeError: 'tuple' object has no attribute 'HTTP_201_CREATED' views.py class UserRegistrationView(GenericAPIView): serializer_class = UserRegistrationSerializer renderer_classes = [UserRenderer] def post(self, request, format=None): confirm_password = request.data.get('password1') #Request the Email from the user) # confirm_password = request.data.get('password1') #Request the Email from the user email = request.data.get('email') #Request the Email from the user username = request.data.get('username') # Request the username from the user password = request.data.get('password') # Request the password from the user first_name = request.data.get('first_name') # Request the first name from the user last_name = request.data.get('last_name') # Request the last name from the user if not email or not username or not password or not first_name or not last_name: # check the parameters for the email,username,password,firstname,lastname. return Response({'msg': 'Invalid parameters'}) pass_bool = Validate_Password(password) # Validate the … -
How to configure Django application deployed with Gunicorn with a front NGINX server, through docker compose?
I am finding difficulty in understanding the mistake in the following setup which attempts to serve a django-gunicorn application server with nginx. (Am not yet concentrating on static assets) Docker compose file # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: gunicorn --bind unix:/run_socket/gunicorn.sock StockWhiz.wsgi:application # Below command for using gunicorn to serve. volumes: - type: bind source: ./stockwhiz-web target: /code - type: bind source: ./run_socket target: /run_socket depends_on: - db environment: - "DJANGO_SETTINGS_MODULE=StockWhiz.settings.local" db: image: postgres:14-bullseye # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" nginx: image: nginx:stable restart: always volumes: - ./run_socket:/run_socket - ./config/nginx/:/etc/nginx/conf.d/ ports: - "80:80" depends_on: - web # Volumes set up volumes: postgres_data: NGINX config # Note in our docker compose it's typically located at etc/nginx/conf.d/ # Which are automatically copied on to the nginx.conf file at etc/nginx upstream gunicorn_application { server unix:/run_socket/gunicorn.sock; } server{ listen 80; server_name www.stockwhiz.in; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass gunicorn_application; } } Logs Some of the logs …