Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django unit testing with fixtures - object matching query does not exist
I am trying to set up unit testing in django using fixtures. I can successfully load my fixtures, but when I attempt to retrieve data from them I get the error: DoesNotExist: BlogIndexPage matching query does not exist. Here is my code for the test (I'm using the Wagtail CMS, which extends unittest with a few additional methods): class BlogTests(WagtailPageTests): fixtures = ['demosite.json'] def test_can_create_blog_entry(self): blog_index_page = BlogIndexPage.objects.get(pk=5) self.assertCanCreate(blog_index_page, BlogPage, { 'title': 'Post 2', 'date': '2017-10-11', 'intro': 'Post 2', 'body': '<p>Test Post</p>' }) And this is my fixture: [ { "pk": 1, "model": "wagtailcore.page", "fields": { "title": "Root", "draft_title": "Root", "numchild": 1, "show_in_menus": false, "live": true, "seo_title": "", "depth": 1, "search_description": "", "content_type": [ "wagtailcore", "page" ], "has_unpublished_changes": false, "owner": null, "path": "0001", "url_path": "/", "slug": "root" } }, { "pk": 2, "model": "wagtailcore.page", "fields": { "title": "Home page", "draft_title": "Home page", "numchild": 5, "show_in_menus": true, "live": true, "seo_title": "", "depth": 2, "search_description": "", "content_type": [ "home", "homepage" ], "has_unpublished_changes": false, "owner": null, "path": "00010002", "url_path": "/home-page/", "slug": "home-page" } }, { "pk": 5, "model": "wagtailcore.page", "fields": { "title": "Blog index", "draft_title": "Blog index", "numchild": 3, "show_in_menus": true, "live": true, "seo_title": "", "depth": 3, "search_description": "", "content_type": [ "blog", "blogindexpage" … -
Iterating over Django QuerySet without pre-populating cache
I want to iterate over all the objects in a QuerySet. However, the QuerySet matches hundreds of thousands if not millions of objects. So when I try to start an iteration, my CPU usage goes to 100%, and all my memory fills up, and then things crash. This happens before the first item is returned: bts = Backtrace.objects.all() for bt in bts: print bt I can ask for an individual object and it returns immediately: bts = Backtrace.objects.all() print(bts[5]) But getting a count of all objects crashes just as above, so I can't iterate using this method since I don't know how many objects there will be. What's a way to iterate without causing the whole result to get pre-cached? -
Generating action, kwargs confused, django-activity-stream
I'm trying to use django-activity-stream in my application, but this actor, target,verd etc. really confused me. My use case is like Below, Bob creates a purchase requirement, John creates an order with reference to this requirement. I want Bob to track this requirement's status in his timeline while john's actions are beeing seen by others. 1- I did get Bob follow the requirement when he created and add an action. "Bob created Purchase requirement req-0001". so far so good, this is visible to anyone who follows Bob and bob himself. 2- Then John created an order with reference to this requirement, the action I created, "John(actor) placed an order(verb) Order-0002(action object) to req-0001(target)" I know I did that wrong , Bob cant see the req-0001 has been converted to be an order, since requirement is an target in this second action. Should I make the requirement an actor itself? and get bob to follow it? Or this usecase is simple not supported? I think I can get desired behaviour using this keyworkd argument's and templating, but I dont want to get too far from concept. Thanks -
developing django projects using git sub-modules
I have a DJango project that uses menus as part of the application For example: MENU: CUSTOMER VENDOR EMPLOYEE I would like each area to be assigned to a developer for creation and modification: one for Customer, one for Vendor, one for Employee. How could one do this? My thoughts would be that the DJango project would be as follows: Main (which is the project) Main => CustomerApp => VendorApp => EmployeeApp Main would be assigned to a Git repository CustomerApp, VendorApp and EmployeeApp would be assigned to Git Sub-Modules. The person working on CustomerApp would ~only~ have access to CustomerApp (and not the other areas: EmployeeApp, VendorApp) One developer could not "step on" or "see" the work of another developer. Could this be a valid approach? TIA -
Django 1.11 - ModelForm: change default form widget for DateTimeField
I need some help in rendering a datetime picker in my form insead of the default text field that is displayed. I am using Django 1.11 and have followed the recent solution posted here: Django 1.11 - forms.Models: change default form widget for DateTimeField however I receive errors when using the same code. The first error I receive is: cannot import name 'widget'. I can pass this error by importing 'widgets' instead. Has this been renamed? The second error I receive after renaming to widgets is: NameError: name 'forms' is not defined. I can pass this error by changing the code to: Class DateInput(widgets.DateInput):Is this the correct treatment for this error? The third error I receive is: NameError: name 'Date_Input' is not defined I can pass this error by changing the final piece of code (removing underscore in Date_Input) above to: widgets = { 'missing_date': DateInput() } After these changes I no longer get any errors however the date field in my form is still rendering as a text field and not as a date picker. Can anyone shed any further light on the solution above and why it possibly isnt working for me? Additonly I would like to modify … -
Convert two arrays to Arrays of Arrays Using Python
I am New on python and I want to make Arrays of array . this.tblData: Array(2) 0: (header)0:["A-100"B-101", "C-11", "D"] (data_values)1:["0E-11,"GERBER", "CA", "960350E-110.0215.500000000"] 1: (header)0:["E-100"B-101", "C-11", "D"] (data_values)0:["0AE-11,"GERBER", "DA", "960350E-110.0215.500000000"] Currently i have 2 separate Arrays 1.For header ["A-100"B-101", "C-11", "D"] ["E-100"B-101", "C-11", "D"] 2.Array for Data Values ["0E-11,"GERBER", "CA", "960350E-110.0215.500000000"] ["0AE-11,"GERBER", "DA", "960350E-110.0215.500000000"] Thanks In Advance -
Running tests in django / wagtail to create sub pages under pages
I'm trying to get a grasp on how to write tests for my own wagtail site. I read the documentation: http://docs.wagtail.io/en/v1.3/advanced_topics/testing.html#wagtail.tests.utils.WagtailPageTests.assertCanCreate and now I want to create a test to see whether I can create a Blog (entry) page under a Blog Index Page. So I have a few tests set up that run successfully, but the last does not: from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.test import TestCase, SimpleTestCase, Client from wagtail.tests.utils import WagtailPageTests, WagtailTestUtils from wagtail.wagtailcore.models import Page # Create your tests here. from blog.models import BlogIndexPage from blog.models import BlogPage class BlogTests(WagtailPageTests): def test_parent_child_relationships(self): # A Blog page can only be created under a blog index page self.assertAllowedParentPageTypes( BlogPage, {BlogIndexPage}) # It should not be possible to create a blog index page under a blog page self.assertCanNotCreateAt(BlogPage, BlogIndexPage) self.assertCanCreate(BlogIndexPage, BlogPage, { 'title': 'Post 2', 'date': '2017-10-11' }) When I attempt the assertCanCreate test, I get the error: `'cached_property' object has no attribute 'allowed_subpage_models' I suspect the problem is that I am loading two models, and attempting to create a page under another page, but I am not actually grabbing a specific page by ID. Versus in the wagtail documentation: def test_can_create_content_page(self): # Get the … -
Django- Login not working
I am trying to make a page that registers users and then logs them in immediately after. It then redirects them to their profile which is a url that contains their id. There is a model called person, and it has a one-to-one field with User. This is the code for my post method (when someone fills out the register form). def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() newperson = person(user=user) newperson.save() user.save() if user is not None: if user.is_active: login(request, user) return redirect('/profiles/' + str(user.person.id)) return render(request, self.template_name, {'form': form}) It then runs this function: def loadprof(request, profile_id): print(request.user) try: user = person.objects.get(id=profile_id) user_schedules = user.schedules_set.all() except person.DoesNotExist: raise Http404("The profile you are looking for does not exist.") if request.user.person.id == profile_id: return render(request, 'profile.html', {'user': user, "user_schedules": user_schedules}) return render(request, 'profile.html', {'user': user, "user_schedules": user_schedules}) It raises a 'AnonymousUser' object has no attribute 'person' error when it runs "if request.user.person.id == profile_id:" in the loadprof function. What is happening? I assume because it is an AnonymousUser, the login function didn't work? I imported the login function correctly and everything, I am very lost. Thank … -
How to join two tables in Django Admin system
I have two models connected to Django Admin system. And would like to have a possibility to , using dropdown list, choose a specyfic value from the first model in a second model. What do you think, is this possible ? Thanks in advance -
Comparing and delete api data
I have a django project that takes in some data from another app of ours. The data looks like this: {u' updated': u'2017-04-03T22:30:53.760278 Z', u'added': u'2017-04-03T22:30:53.760197 Z', u'name':u'Jean Bacon, 1942- ', u' authority':{ u'id':2, u'added_by':2, u'name':u'VIAF' }, u'local_identifier':u'85363862', u'concept_type':{ u'id':5, u'identifier': u'viaf:personal', u'name':u'', u'description':None }, u'identifier': u'http://viaf.org/viaf/85363862', u'identities':[ { u'part_of':{ u'id':1, u'added_by':2, u'name': u'builtin:Conceptpower' }, u'added': u'2017-04-03T22:33:20.476637 Z', u'name':u'Jean Bacon', u'confidence':1.0, u'updated': u'2017-04-03T22:33:20.476699 Z', u'concepts':[ u'http://viaf.org/viaf/85363862', u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0' ], u'id':208, u'added_by':{ u'username':u'erickpeirson', u'email':u'erick.peirson@asu.edu' } }, { u'part_of':{ u'id':1, u'added_by':2, u'name': u'builtin:Conceptpower' }, u'added': u'2017-04-03T22:35:02.546054 Z', u'name':u'Jean Bacon', u'confidence':1.0, u'updated': u'2017-04-03T22:35:02.546116 Z', u'concepts':[ u'http://viaf.org/viaf/85363862', u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0' ], u'id':209, u'added_by':{ u'username':u'erickpeirson', u'email':u'erick.peirson@asu.edu' } }, Right now I have a function that goes through and compares the concepts in in the identities. What I want to do is delete the duplicate concepts. The nesting of the dictionaries and lists are throwing me off. What I have been trying is: del results[i]["identities"][z]["concepts"] Any ideas as to why this does not work? Here is my loop incase anyone is interested: while (i != di): test = results[i]["identities"] if results[i]["identities"]: z = 0 while (z != len(results[i]["identities"])): con1 = results[i]["identities"][z]["concepts"] print "this is con1: %s", con1 if z != len(results[i]["identities"]): z = z + 1 else: break if … -
How to make an multiple image upload best practice Django
What is the best practice for making an multiple image upload in Django ? How can I reach this <input type="file" name="img" multiple> in my forms.py ? So the user can select many images not only one ? image = models.ImageField(upload_to="", default="", null=True) Some kind of that but with multiple selection. The next question is, how do I handle or even get all the image urls and save them in my database ? Would I do this with Ajax ? For example getting all the urls and save them in my database ? What is the best way or flow of doing it ? -
django reverse lookup query within three tables
I have three tables User, Users_clients, and Credits. I want to list tables of current user's clients with their details and credit. If any client is listed in credit table then credit should return 0 where else it should return the credit value. my model.py is class User_clients(models.Model): user = models.ForeignKey(User, related_name='myuser') client = models.ForeignKey(User, related_name='myclient') class Credits(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) credit = models.IntegerField(null=True, default=0) my views.py is def clients(request): try: data = User_clients.objects.order_by('-id').filter(user_id=request.user.id)[0:10] except User_clients.DoesNotExist: data = None return render(request, "client_list.html",{'title':"Client List",'clients':data,'active':'myclients','open':'clients'}) Thanks a lot in advance! -
Django DRF TypeError: object is not iterable, how to approach this?
Wondering what I'm doing wrong here. I'm running DRF with a React frontend. Trying to get one serializer to GET and POST a user's selected stations. The AJAX POST works great, but the get on a page's initial load no longer works, and Django tells me: TypeError: 'Station' object is not iterable. From reading around I'm vaguely aware that I shouldn't be declaring station with many = True, as this is causing the exception to be thrown. But I can't find any other way to get it working, it mangles the JSON POST request if I remove this option and stops the data validating. The create is using custom code and is working fine. Should I be trying to get this to work seamlessly or should I just hack it / make a different serializer to do the POST? Am I doing this in a logical way or have i got it all back-to-front? Thanks models.py class Station(models.Model): network = models.ForeignKey(Network, on_delete=models.CASCADE) name = models.CharField(db_column='name', max_length=256) # Field name made lowercase. latitude = models.FloatField() longitude = models.FloatField() users = models.ManyToManyField('Account', through='UserStations') class Meta: managed = True def __str__(self): return self.name class UserStations(models.Model): station = models.ForeignKey(Station, on_delete=models.CASCADE) user = models.ForeignKey(Account, on_delete=models.CASCADE) … -
Django AWS S3direct Upload with Dynamic Forms
1. Initial Situation OK I use django-s3direct to upload Images directly to AWS S3. django-s3direct let me only upload one image on the form. I thought the easiest solution is to add dynamically another ImageForm if the user uploaded an Image or clicks an "add more" button. I use django-dynamic-formset. 2. Problem I can upload one image. Then i click the "add more" button and another ImageField appears. After I select a new file to upload I get an error: POST [XHR] http://127.0.0.1:8005/en/s3direct/get_upload_params/ [HTTP/1.0 403 FORBIDDEN 7ms] TypeError: uploadParameters is null The s3direct/bundled.js function which causes the error is: const checkFileAndInitiateUpload = function(event) { console.log('Checking file and initiating upload…') const element = event.target.parentElement, file = element.querySelector('.file-input').files[0], dest = element.querySelector('.file-dest').value, csrfTokenName = element.querySelector('.csrf-cookie-name').value, destinationCheckUrl = element.getAttribute('data-policy-url'), signerUrl = element.getAttribute('data-signing-url'), form = new FormData(), headers = {'X-CSRFToken': Cookies.get(csrfTokenName)}; form.append('dest', dest) form.append('name', file.name) form.append('type', file.type) form.append('size', file.size) request('POST', destinationCheckUrl, form, headers, element, function(status, response) { const uploadParameters = parseJson(response) switch(status) { case 200: initiateMultipartUpload( element, signerUrl, uploadParameters.object_key, uploadParameters.access_key_id, uploadParameters.region, uploadParameters.bucket, uploadParameters.bucket_url, uploadParameters.cache_control, uploadParameters.content_disposition, uploadParameters.acl, uploadParameters.server_side_encryption, file ); break; case 400: case 403: case 500: error(element, uploadParameters.error) break; default: error(element, 'Sorry, could not get upload URL.') } }) } and here is the snippet … -
Session token api in Django tastypie
I need to implement using api such behavior: App opening without registration If it's new user, then send /signup request, and get new session If there is a session, then check it. So I think I need /signup method which creates session and returns a session token. And /check method which gets a token and returns check result. I want to know how to create user without any params and return session token and how to check this token? I'm new at Django. And I want to use Tastypie for api. -
Retrieving a Django form field value using AJAX
For each fact in facts, there is a form where you can upvote or downvote the fact. Further explanation is found below. Template and Form code are listed below respectively: template <ul> {% for fact in facts %} <form method='POST' action="{% url 'facts:list' fact.pk %}" id="list_vote"> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> {% endfor %} </ul> forms.py code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect(attrs={'class': 'vote'})) For each fact in models.Fact.objects.all(), there is a form, which consists of radio buttons of 2 inputs (upvote, downvote), created for this specific fact. What I'm now doing is basically Django 101: getting the value of the fact that is being voted and update its model accordingly in the views. What I want to do is retrieve the value of this specific fact using AJAX and update the model accordingly without leaving/refreshing the page -
How to filter in django by two properties of the same related object in a many-to-one relationship?
My model structure looks like this: class OneModel(model): not_important = IntegerField() class RelatedModel(): propertyA = IntegerField() propertyB = IntegerField() original = ForeignKey(OneModel, related_name='related') I am looking for a native django solution (without raw sql), to recreating basically this query: select * from OneModel om where not exists (select id from RelatedModel rm where original_id = om.id and propertyA = 1 and propertyB = 2); Here's what I've tried: OneModel.objects.exclude(related__propertyA=1, related__propertyB=2) Unfortunately this has the effect of selecting OneModel objects which have neither a related with propertyA=1, nor a related with propertyB=2, not ones that don't have a single related that matches both criteria. Here's the generated sql from my django query: SELECT lots_of_fields FROM "OneModel" WHERE NOT ("OneModel"."id" IN (SELECT U1."original_id" AS Col1 FROM "RelatedModel" U1 WHERE U1."PropertyA" = 1) AND "OneModel"."id" IN (SELECT U1."original_id" AS Col1 FROM "RelatedModel" U1 WHERE U1."PropertyB" = 2)) And just to be clear, my problem is not with using "id" in instead of exists, but with the logic of the query. I tried playing around with Q-objects, but can't figure out any way to use to solve this. I also looked at F-objects, but they also don't seem to be relevant. Is there any … -
Multiple updates on MySQL without overwriting data
I am using a jQuery sortable to sort the rows of my table. The new order gets saved in the backend and I am using python, Django. I have a column in my database called priority. This is how I handle the logic in the backend. the last array is a 2D list Basically, I want the following to happen: previous_order = [ 1,2,3,4,5 ] new_order = [3,4,5,1,2] orders_to_rearrange = [ ### gets passed in a function [1,3], [2,4], [3,5], [4,1], [5,2] ] ### UPPDATE the following: ### Priority 1 to become 3 ### Priority 2 to become 4 ### Priority 3 to become 5 ### Priority 4 to become 1 ### Priority 5 to become 1 The above is a pretty example, but when I encounter a complicated switch like this: ### Priority 5 to become 2 ### Priority 2 to become 4 ### Priority 4 to become 1 Notice how after 5 becomes 2, 4 becomes 2 and so did the previous 5. Now I end up having two priority 2 because it overwrites the statement inside the loop. I though that the WHEN THEN case statement in MySQL will help, but it ends up doing the same … -
Django Rest Framework: Function Based API serializers
Unsolicited for I've been put on an API-project where the requirements are: Django Django Rest Framework Python 3.5 API needs to be function based (so no classes) Where the goal is an API that returns data (so I only need 'Read' from CRUD-design principles) in JSON format for internal use by displays. Django itself has to connect to a default database and a legacy MYSQL data (this works). I've done so with the settings.py file. I then created a new application called museum_api; this works as well. After that I built my models of the legacy database with the help of python manage.py inspectdb --database=museum_data > models.py the above code generated a python file with classes for every table in the MYSQL database in the rootfolder called 'musart' of the project (this folder holds: manage.py, musart and museum_api.) Then I created a static JSON response by going inside of the folder called museum_api and created a file: views.py and urls.py I left these empty for a sec and went back to the root-folder and into the inner-project folder to edit the urls.py file in there. In that file I added: url(r'', include('museum_api.urls')), The intent is that the API is the … -
Django forward www.domain.com to domain.com with fastagi RewriteRule
I want to forward www.myapp.com to myapp.com. My current htaccess AddHandler fcgid-script .fcgi RewriteEngine on # Set up static content redirect: RewriteRule static/(.+)$ myapp-folder/public/static/$1 # The following two lines are for FastCGI: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ application.fcgi/$1 [QSA,L] I tried adding below lines to above content RewriteCond %{HTTP_HOST} ^www.myapp.com$ [NC] RewriteRule ^(.*)$ http://myapp.com/ [R=301,L] But it doesn't give me the output I want. Without fastcgi I can just replace those lines since my app depends on it how can I add this forwarding without removing fcgi rule. -
running specific test case with python unittest in django
I have a set of unit tests that I can successfully run with: ./runtests.py wagtail.wagtailcore.tests But if I want to execute just one of them, I get an error that 'module' object has no attribute [test_case_name] My class would be something like: class TestPagePrivacy(TestCase): def test_anonymous_user_must_authenticate(self): so I would think you could just say: ./runtests.py wagtail.wagtailcore.tests.test_anonymous_user_must_authenticate Why doesn't this work? From the django docs: https://docs.djangoproject.com/en/1.11/topics/testing/overview/#running-tests # Run just one test method $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak -
Django ORM filter by Max column value of two related models
I have 3 related models: Program(Model): ... # which aggregates ProgramVersions ProgramVersion(Model): program = ForeignKey(Program) index = IntegerField() UserProgramVersion(Model): user = ForeignKey(User) version = ForeignKey(ProgramVersion) index = IntegerField() ProgramVersion and UserProgramVersion are orderable models based on index field - object with highest index in the table is considered latest/newest object (this is handled by some custom logic, not relevant). I would like to select all latest UserProgramVersion's, i.e. latest UPV's which point to the same Program. this can be handled by this UserProgramVersion queryset: def latest_user_program_versions(self): latest = self\ .order_by('version__program_id', '-version__index', '-index')\ .distinct('version__program_id') return self.filter(id__in=latest) this works fine however im looking for a solution which does NOT use .distinct() I tried something like this: def latest_user_program_versions(self): latest = self\ .annotate( 'max_version_index'=Max('version__index'), 'max_index'=Max('index'))\ .filter( 'version__index'=F('max_version_index'), 'index'=F('max_index')) return self.filter(id__in=latest) this however does not work -
Django Rest Framework MultipleChoiceField with dynamic options
So I just started using Django Rest Framework and one of my serializers has a MultipleChoiceField in which the choices are simply all the instances of another model. Here is the serializer in question: class ObjectTypeSerializer(serializers.ModelSerializer): def get_field_choices(): return sorted([ (p.id, p.name) for p in Parameter.objects.all() ]) object_fields = serializers.MultipleChoiceField( choices=get_field_choices() ) instance_fields = serializers.MultipleChoiceField( choices=get_field_choices() ) labels = serializers.SlugRelatedField( queryset=Label.objects.all(), many=True, allow_null=True, slug_field='name' ) class Meta: model = ObjectType fields = ('id', 'name', 'object_fields', 'instance_fields', 'labels') However, when I add a new Parameter object, the choices are not updated. In regular Django forms, I solved this simply using forms.ChoiceField(choices=[(p.id, p.name) for p in Parameter.objects.all()]) and it would update the choices when a new parameter is added without restarting the server. How can I accomplish the same thing with Django Rest Framework serializers? Any help is appreciated. Thanks! -
Django readonly form field does not appear in cleaned data
in my forms I changed this field to readonly class myForm(forms.Form): ... database = forms.CharField(label='Database', widget=forms.TextInput(attrs='style':'width:164px','readonly':'readonly'}), initial='production') I can see the initial value in the form on the browser, but then when I try to retrieve the values in the code def clean(self): cleaned_data = super(ReportForm, self).clean() print "CLEANED DATA ",cleaned_data database = cleaned_data['database'] # this throws an error The cleaned_data has all the other form items except the database it worked fine before adding attrs readonly -
django https 502 bad gateway
I am using nginx server with django. nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } and the file in sites-available upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80; server_name example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _ technocyan.com; ssl_certificate /home/django/example_cert_chain.crt; ssl_certificate_key /home/django/example.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/myapp/media; } # your Django …