Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PasswordResetDoneView not using custom template in Django
PasswordResetDoneView.as_view is not loading custom template I'm using Django 2.2 version I have created a custom template and add the path to accounts app url url(r'^reset_password/done/$',PasswordResetDoneView.as_view(template_name='accounts/my_password_reset_done.html'),name='my_password_reset_done'), My Template {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Password Reset Done</h1> <p> We've emailed you instructions for setting your password if an account exists with the email you entered. You should receive them shortly. If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder. </p> </div> {% endblock %} The issue if I have - path('', include('django.contrib.auth.urls')), in my main URL then it is loading default Django template. if I removed that I'm getting the error that path doesn't exist and I'm trying to override the Django template with my own template but it is not loading. -
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I encountered this problem when I attempted to create a super user. I first had a migrations error in my model so I tried deleting my existing database (db.sqlite3) and some of the migrations file (pycache folder and 0001_initial.py) in my app. It solved the migration problem however, when I attempted to create a new superuser, an error occurred and now I can't solve it. Here's my models.py code: class Permission(models.Model): permission_name = models.CharField(max_length=255, blank=False, null=False, unique=True) description = models.TextField(max_length=500, blank=False, null=False) is_active = models.BooleanField(default=True) def __unicode__(self): return self.permission_name def __str__(self): return '{}'.format(self.permission_name) class Role(models.Model): role_name = models.CharField(max_length=255, blank=False, null=False, unique=True) is_active = models.BooleanField(default=True) user_permission = models.ManyToManyField(Permission, related_name='permissions') def __str__(self): return self.role_name class User(AbstractBaseUser): unique_id = models.CharField(primary_key=True, default=uuid.uuid1, max_length=36) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) user_role = models.ForeignKey(Role, on_delete=models.CASCADE, null=False, blank=False, related_name='user', default=2) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] It seems like the error is in here: user_role = models.ForeignKey(Role, on_delete=models.CASCADE, null=False, blank=False, related_name='user', default=2) And this is the error I got: File "C:\Users\IDAS-DEV\Envs\ltms\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed -
How to show validation errors in a Django Model form using DateTimeField and input_formats
I want to enforce a particular date-time format using Django's model form -- Class ModelEditForm(forms.ModelForm): date_one = forms.DateTimeField(input_formats=["%Y-%m-%d %H:%M:%S"]) class Meta: model = MyModel fields = (date_one, ) My form.html file -- <form method="POST" enctype="multipart/form-data"> <div class="row"> <div class="form-group col-sm-12 col-md-12"> <label> Enter date and time in this format "%Y-%m-%d %H:%M:%S" </label> {% render_field form.date_one class="form-control"%} </div> {% csrf_token %} <div class="row"> <div class="form-group col-sm-6 col-md-6"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> If the correct date-time format (e.g., 2019-08-12 09:00:00) is entered the form is saved, but a wrong format (e.g., 2019-08-12) would not show an error message like it does for other ModelForm fields, e.g, enforcing a max_digit in model.DecimalField. Using wrong format does not update the form but the user doesn't know why the form is not saved. What can I do to show the error message without using a JavaScript input. I am using Django 2.0, Python 3.6 and widget_tweaks. Thanks for your help. -
how to check if a checkbox is checked in django template
I need to check that if a checkbox is checked in django template and if False open up some other fields. I already tried something like: {% if 'closed' in 'is_closed %} but they are always True and no matter if the checkbox is checked or not so this is my checkbox properties in template <input type="checkbox" name="is_closed" value="closed"> -
In Django, what is the difference between using a "through" table or using a related name for many-to-many model fields?
When it comes to Many-To-Many fields in Django, what is the difference between using a "through" table like the following... class A(models.Model): things = models.ManyToManyField("B", through=ThroughModel) ... class B(models.Model): text = models.TextField() ... class ThroughModel(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) compared to just specifying a related name in the intermediary table like so? class A(models.Model): ... class B(models.Model): text = models.TextField() ... class ThroughModel(models.Model): a = models.ForeignKey(A, related_name="things") b = models.ForeignKey(B) Either way you should be able to reference the relationship like a_instance.things right? Is there some behind the scenes difference between how this is implemented in the database? -
Implementing set division on django models
Assuming a Django model 'model1' (can be thought of as a m*n table), that contains only 2 columns - 'col1' and 'col2'. Given a list 'lst1' that contains list of values from 'col2' domains. How can we perform set division 'model1 / lst1'. -
Some <script src> and <links src> are found by html others don't, even if they are in same file
I am trying to add some .js and some .css files to my html page, but some work others don't, even if they're in the same directory. I tried moving the one that doesn't work to same directory of the ones that work, but when i open the html page in browser i get the error saying that it wasn't found(404). <script src="{% static "admin-lte/dist/js/app.min.js" %}"></script> <script src="{% static 'admin-lte/dist/js/moment.min.js' %}" ></script> since they are in the same directory they were suppose to be found by the html i guess, but what i actually get is this error: GET http://127.0.0.1:8000/static/admin-lte/dist/js/moment.min.js net::ERR_ABORTED 404 (Not Found) -
Travis detecting Ruby default settings in a DJANGO project
I have a Django project that I want to test continously with Travis-CI. The problem is that every time i run a build in Travis it fails because a rake command of ruby. I already change my travis.yml a hundred times but it seems not to be okay even though. I leave my last travis.yml that is in the same directory that my requirements.txt language: python python: - "3.5" - "3.6" - "3.7" cache: pip services: - sqlite3 env: - DJANGO=2.2.4 DB=sqlite3 install: - pip install -r requirements.txt before_script: - sqlite3 - e 'create database test;' -u root script: - python manage.py makemigrations - python manage.py migrate - python manage.py test The output i get from travis is this: rvm $ git clone --depth=50 --branch=master ... 1.01s$ rvm use default ruby.versions $ ruby --version No Gemfile found, skipping bundle install 0.21s$ rake rake aborted! No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb) /home/travis/.rvm/gems/ruby-2.5.3@global/gems/rake-12.3.2/exe/rake:27:in `<top (required)>' /home/travis/.rvm/gems/ruby-2.5.3@global/bin/ruby_executable_hooks:24:in `eval' /home/travis/.rvm/gems/ruby-2.5.3@global/bin/ruby_executable_hooks:24:in `<main>' (See full trace by running task with --trace) The command "rake" exited with 1. Done. Your build exited with 1. -
Nginx + Firebase - how to restrict access to media files (images/videos)?
I have the following setup: Backend (purely an api): Nginx + uWSGI + Django Frontend: android app Auth process via Firebase. It's a image sharing app. To get the images, the user gets authenticated with a token by Django, receives in returns the URLs to all the images. On Android, Glide will just fetch the media files with the URL. Nginx of course serves the media files directly, without passing a /media/ request to uWSGI+Django. Problem: anyone (not even a user atm) with the URL can download the image/video. How do I implement a control system to restrict access to the media files? I am not sure this solution works for me: Create Django Session From Token -
Django PK to slugfield
I want to change my urls from PK to slugfields, but on one field this is not working. urlpatterns = [ ... url(r'^indexed/$', views.QuestionsIndexListView.as_view(), name='index_all'), url(r'^ask-question/$', views.CreateQuestionView.as_view(), name='ask_question'), url(r'^(?P<slug>[-\w]+)/$', views.QuestionDetailView.as_view(), name='detail'), url(r'^propose-answer/(?P<question_id>\d+)/$', views.CreateAnswerView.as_view(), name='propose_answer'), #url(r'^propose-answer/(?P<slug>[-\w]+)/$', views.CreateAnswerView.as_view(), name='propose_answer'), ] views class CreateAnswerView(LoginRequiredMixin, CreateView): model = Answer fields = ["content", ] message = _("Thank you!") def form_valid(self, form): form.instance.user = self.request.user form.instance.question_id = self.kwargs["question_id"] return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse( "question_detail", kwargs={"pk": self.kwargs["question_id"]}) My first problem is, on my way it is not possible to open with a slug url. I get this error. Reverse for 'propose_answer' with arguments '('',)' not found. 1 pattern(s) tried: ['propose-answer/(?P[-\w]+)/$'] And my second problem, when the form is valid, how can I forward to the slug url again? This is not the same Model. I have two models. Question and Answer. And after publishing the answer, I want go back to the Main Question like the url url(r'^(?P<slug>[-\w]+)/$', views.QuestionDetailView.as_view(), name='detail'), -
Django. Rest framework hyphen in xml tag
Need advice. I have a tag, property-type, it uses a hyphen. I know that in python you cannot use hyphens for variables. As a result, I have: serializers.py from rest_framework import serializers from listings.models import * class Serializer(serializers.ModelSerializer): property_type = serializers.CharField(source='xml_data_property_type') class Meta: model = KV fields = ['title', 'price', 'address', 'property_type'] In order for xml to work correctly, I need that the tag, property-type, be written with a hyphen. Thank you! -
Call forwarding loop instead of redirect
I have a code in django view (django==2.1), where I want to redirect from sub domain to main domain. def signup(request): current_site = Site.objects.get_current() if request.META['HTTP_HOST'] != current_site.domain: full = urljoin(current_site.domain, reverse('accounts:signup')) return HttpResponseRedirect(full) Instead of redirecting, there's a redirecting loop. And instead of the full address, there is the ending: /accounts/signup/. It should be http://localhost:8000/accounts/signup/ -
Django inlineformset_factory add line numbers
While using django.forms.inlineformset_factory is there a way to keep track of line numbers and pass that information to the model? For example, consider the following in models.py class BillLine(models.Model): parent = models.ForeignKey(BillHeader, on_delete=models.CASCADE) description = models.TextField(default = "stuff") quantity = models.IntegerField() unit_price = models.DecimalField(decimal_places = 2) line_number = models.IntegerField(default=0) and the following in forms.py class BillHeaderForm(ModelForm): class Meta: model = BillHeader fields = '__all__' class BillLineForm(ModelForm): class Meta: model = BillLine fields = ('description', 'quantity', 'unit_price') # line number not included BillLineFormSet = inlineformset_factory(BillHeader, BillLine, fields = ('description', 'quantity', 'unit_price'), form = BillLineForm) When BillLineFormSet is rendered onto the view, how would I go about keeping track of line numbers? -
How to set Crontab in django only for working days of week
I am confused to create crontab command in django that should only run on working days of the week eg :-(Monday- Friday) and also exclude the predefined holidays. -
Why my class based logout view doesn't work?
I'm trying to write a logout view that returns the main page of my application. The result is the that home page is called correctly, but the user is not logged out. Why does the logout not work correctly? views.py class BaseView(View): left_menu_bar = get_categories() # not importatn here context = {'left_menu_bar': left_menu_bar, 'username': ''} template_name = '' extra_context = {} for element in extra_context: context[element] = extra_context[element] def get(self, request): if request.user.is_authenticated: username = request.user.username self.context['username'] = username return render(request, 'buybook/' + self.template_name, self.context) class Main(BaseView): template_name = 'main.html' class LogOut(View): def get(self, request): logout(request) return HttpResponseRedirect(reverse('buybook:main')) urls.py app_name = 'buybook' urlpatterns = [ #... path('', views.Main.as_view(), name='main'), path('logout', views.LogOut.as_view(), name='logout'), ] and templates: base.html <html> {%if username%} Your nickname is <b>{{username}}</b> <a href='{%url 'buybook:logout' %}'> log me out</a> <br><br> {%else%} You're not logged in<br> <a href='{%url 'buybook:loginpanel' %}'>login</a><br> <a href='{%url 'buybook:registrationpanel' %}'>create an account</a> {%endif%} {%block books %} {%endblock%} </html> main.html <html> {% extends 'buybook/base.html' %} {% block books %} <h1>Welcom</h1> <p> etc. </p> {% endblock %} </html> I've created registration and login views before and they work correctly, so I don't paste the code for these views. Only LogOut view is a problem. -
I filling the fields do not enter in form.is_valid ():
Experts I am waiting for my problem to be solved on the internet Why when I finished filling the fields in django do not enter in form.is_valid (): Although the results are presented correctly I hope to solve this problem class Listing(models.Model): property_type = models.IntegerField(choices=PROPERTY_TYPE_CHOICES, default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) price = models.BigIntegerField() roomsTotal = models.PositiveSmallIntegerField(null=True) Bathrooms = models.PositiveSmallIntegerField(default=0) bedrooms = models.PositiveSmallIntegerField(default=0) Receptionrooms = models.PositiveSmallIntegerField(default=0) livingArea = models.DecimalField(max_digits=9, decimal_places=1) lotSize = models.DecimalField(max_digits=9, decimal_places=1) unitType = models.IntegerField(choices=UNIT_TYPE_CHOICES, default=1) VOnSea = models.BooleanField(default=False, blank=True) yearBuilt = models.PositiveIntegerField( validators=[ MinValueValidator(1900), MaxValueValidator(datetime.datetime.now().year)], help_text="Use the following format: <YYYY>") hoaPrice = models.BigIntegerField(null=True,blank=True) groundTankSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True) garageSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True) homeDescription = models.TextField(blank=True) class ForSaleForm(forms.Form): property_type = forms.ChoiceField(widget=forms.Select, choices=PROPERTY_TYPE_CHOICES,required=False) price = forms.IntegerField(required=True) roomsTotal = forms.IntegerField() Bathrooms = forms.IntegerField(required=True) bedrooms = forms.IntegerField(required=True) Receptionrooms = forms.IntegerField(required=True) livingArea = forms.DecimalField(required=True) lotSize = forms.DecimalField(required=True) unitType = forms.ChoiceField(widget=forms.Select, choices=UNIT_TYPE_CHOICES,required=False) yearBuilt = forms.DateField(required=True) remodelYear = forms.DateField(required=True) def clean(self): data = self.cleaned_data if data.get('price', None) or (data.get('Bathrooms', None) and data.get('bedrooms', None)): return data else: raise forms.ValidationError('Provide either a date and time or a timestamp') form = ForSaleForm(request.POST or None) for key in request.POST.keys(): if key != 'csrfmiddlewaretoken': print(key,":",request.POST[key]) if form.is_valid(): propertyType = form.cleaned_data.get('propertyType') price = form.cleaned_data.get('price') roomsTotal = form.cleaned_data.get('roomsTotal') Bathrooms = form.cleaned_data.get('Bathrooms') bedrooms = … -
How do you import a js file using {% load staticfiles%} in a base html template
Using Django {% load staticfiles %} I'm trying to load an app.js file in my base.html template. I've seen several questions on StackOverflow about this and I also tried to follow this tutorial: https://www.techiediaries.com/javascript-tutorial/ but no of them actually helped with my issue. It seems strange as well because on dev tools I see a 200 GET on the static/js/js.app and when I actually open the path the javascript is there. Additionally, when I put the js code in a at the end of the body it seems to work. But I want to load the js from a file. Below is the latest that I've tried, but still no luck. base.html <!DOCTYPE html> <html lang="en"> {% load staticfiles %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="favicon.ico"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'js/app.js' %}" rel="stylesheet"> <link href="{% static 'css/main.css' %}" rel="stylesheet"> <body> <div class="container"> {% block content %} {% endblock content %} </div> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <!-- jquery --> </body> </html> Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -
Idea on how to approach server side request to external API in django rest-framework and react based project
I've been working for a while on my first bigger project, it is a crypto trading platform that utilizes API of an exchange. The project is a combination of django rest-framework (users, trading history, storing different API keys for accessing the account on exchange) and react (presenting exchange's data, manual and bot trading interface etc.). Having some of the job done, I am stuck with the concept of actual trades. Namely I wonder, if I can make the requests purely on the client side and just feed the server side with trades' parameters etc. for example to store them for further review OR if it is a must to perform the trading part by making the requests on the server side. Some time ago, I made a similar, but simpler app using only django and its templates, so all the requests' logic was kept in views. This time I struggle to find the right approach, since it involves react. Although the project is just for learning purposes, I hope to land an entry level job as a developer, so I want to make it right. My main concern is security if I handle the trading logic on the client side … -
I'm getting different test results in Docker compared to a local run
In the following branch of my project I'm implementing various tests, at the moment: https://github.com/Nebucatnetzer/network_inventory/tree/tests When I ran pytest locally the tests are passing save for one, which isn't the problem. When I ran the tests with make test the tests are run inside the Docker container and roughly 50% of all the tests are failing. I can't figure out why this is happening. As far as I can tell the settings for both projects are the same and when I start the Docker container normally and do the tests by hand they seem to work just fine. I'm stuck on this since a few days and just don't understand what is going wrong. -
Django 2.2 + UUID as ID + default values
So I have this as a base model: class BaseModel(models.Model): """ base class for all models enforcing a UUID """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Meta: abstract = True Programmatically, from my Django classes, when I derive from this class and call .save() a new object it's created with a fresh UUID. However, when I look at the database schema (latest Postgres) with a tool like DataGrip, I find that the column id has nothing in the default definition - Why hasn't the default=uuid.uuid4 translate over to the database itself somehow? When I edit the database with DataGrip, I have to insert a new UUID manually for records I put in manually to be able to save correctly. Is there a way around this? To have the UUID automatically generate when I add rows from a 3rd party database client? -
How to prevent Django form from saving if no change was made?
How can I prevent a Django ModelForm from saving, for example, the qty column, if a user doesn't change that specific column? My example: models.py: class Product(models.Model): qty = models.IntegerField() price = models.IntegerField() forms.py: class ProductForm(forms.ModelForm): rows_per_page = forms.IntegerField(widget=forms.HiddenInput(), initial=1) def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) class Meta: model = Product fields = ['sku', 'qty', 'sell_price'] ProductFormSet = forms.modelformset_factory(Product, form=ProductForm, extra=0) views.py: class Inventory(FormView): form_class = ProductFormSet def get(self, req): query = Product.objects.filter('condition') form = ProductFormSet(queryset=query) return render(req, 'base.html', {'form':form}) def post(self, req): query = Product.objects.filter('condition') form = ProductFormSet(queryset=query) if product_form.is_valid(): product_form.save() return render(req, 'base.html', {'form':form}) data: Product.objects.create( name = 'test product', sku = 1, qty = 0, price = 50, ) The problem comes when 2 users are looking at the same queryset at the same time. If user1 decides to modify the qty of test product, then saves the page while user2 is still on that page, if user2 makes any changes to any of the columns (other than qty), the qty change that user1 made will be overwritten back to the original value. My solution before Django was to pass an object of price, qty, and sku to the window, then use jQuery to remove unchanged … -
While deploying my application by using heroku getting error as desc="No web processes running"
While deploying my application by using heroku getting desc="No web processes running" but i have created a Procfile and requirements file in procfile i have mentioned web: gunicorn Project.wsgi Project is my application name and i have installed gunicorn in requirements files too..! In Procfile i tried with both: web: gunicorn Project.wsgi web: gunicorn Project.wsgi.application when i tried to run heroku ps:scale web=1 i am getting output as Scaling dynos... ! ! Couldn't find that process type (web). This is what i have in setting file WSGI_APPLICATION = 'Project.wsgi.application' Looks everything fine for me but it is getting the No Web Proceeses running for me. -
Push rejected, failed to compile Python app.| I can't deploy a Django app to Heroku
I'm beginner and learned how to deploy a Django app to production with this article https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment. Author of this has django app https://github.com/mdn/django-locallibrary-tutorial that I can push to heroku. I have ~copied/pasted this and added some things https://github.com/Altay02/altai_application1. I can't push my repository to heroku and i can't find different between my and him repo that causes the problem. I've tried to find solve here Push rejected, failed to compile Python app , here Error pushing Django project to Heroku and other articles, but no result. this is my console, when i push my repository. error appears (my_django_environment) C:\Users\123\altai_application1>git push heroku master Enumerating objects: 179, done. Counting objects: 100% (179/179), done. Delta compression using up to 4 threads Compressing objects: 100% (106/106), done. Writing objects: 100% (179/179), 62.07 KiB | 2.96 MiB/s, done. Total 179 (delta 71), reused 151 (delta 55) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.7.4 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ! Push rejected, failed to compile Python app. remote: … -
How to background Django API with scalability in AWS?
I have an API in Django (restframework) actually hosted in a Elastic Beanstalk in single docker container template Web server using LoadBalancer and AutoScale provided by AWS EB. I want to background API because it deals with many requests hits in the same sec causing many 5xx http errors. After some research I found that Celery can make this work for me using SQS, but I don't know how to develop this scenario (I can run the API with Celery workers locally, but I don't know how to make this on AWS EB or even in a docker-compose). Should I use Elastic Beanstalk Worker environment and/or docker-compose? Can I put Django and Celery in a docker-compose and deploy it on EB Web or I need to change environment tier in this case? What kind of changes I need to make in my actual project (Docker-Django-EBWeb) to background tasks? Note: I need some configs in container image to integrate past Oracle 11g DB (instant client 11g + cx-Oracle5.3) -
Troubleshoot high cpu usage in django application
I try to optimise my django web application to increase max rps. My stack includes docker+django+gunicorn+nginx I made performance test with yandex.tank. When rps load is about 15 requests start to fail. Tank writes: "110 Connection timed out" In nginx access.log I have: "xxx.xxx.xxx.xxx - - [27/Aug/2019:17:37:52 +0000] "GET /url HTTP/1.1" 499 0 "-" "Tank" 5.257 - [5.256]" When I open htop during this test I see that all server cores are loaded at 100% I have tried to play with proxy_read_timeout, keepalive settings but with no results. upstream app { server django:5000; } server { listen 80; server_name my.site.com; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/my.site.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my.site.com/privkey.pem; client_max_body_size 4G; access_log /var/log/nginx/access.log combined_plus; error_log /var/log/nginx/error.log; gzip on; gzip_comp_level 2; gzip_min_length 1000; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain application/x-javascript text/xml text/css application/xml; location / { proxy_pass http://django:5000; proxy_redirect off; proxy_set_header Host $http_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-Proto $scheme; proxy_read_timeout 300; } location /static { alias /app/static/; } location /media { alias /app/media/; } } nginx.conf user nginx; worker_processes 8; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format combined_plus '$remote_addr - $remote_user [$time_local]' ' "$request" $status $body_bytes_sent "$http_referer"' ' …