Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting data from some rest API on Django
So here's the deal: I have some nodeJS/PHP rest API! And I need to build a Django app which feeds on that API. Everything will be done on the server-side! So I would not use Django's back-end structure. Basically I would GET some JSONs and POST it back so the server, which in turn would process that data. How should I proceed? I've been looking for tutorials for a while now. However everywhere I look, people are using django-rest or something "django friendly". I tried to start using python-requests but it is still kind of cloudy, am I letting my front-end unprotected using direct GET/POST calls to the server (using requests)!? Any guidance would be much appreciate! -
For django template pass params to {%%}
Alguém que manje de django pelo amor de jah me ajude, não estou conseguindo usar o reverse no template seguinte: {% for aula in aulas %} <a href="{% url 'contas:aula_especifica' slug_instrutor=modulo.curso.instrutor.slug slug_curso=modulo.curso.slug slug_modulo=modulo.slug slug_aula=aula.slug %}">{{aula.titulo}}</a> {% endfor %} ele está passando o slug_aula como vazio, logo ele não gera o reverse da url (da erro por falta de params), então, não sei o porque disso, e antes que me sugiram montar a url, eu não quero montar, preciso utilizar o reverse, obrigado desde já. -
Django site, getting error __init__() missing 1 required positional argument: 'request' when calling a view
I'm getting the error message above when trying to load my edit_transaction view. I know what the error means but don't understand why it is happening as it was working before and still works on another similar page. Can provide more code if needed, I'm wondering though if there is something blindingly obvious here, so much so that I can't see it. Full traceback: Traceback: File "/Users/c/.virtualenvs/django-budget/lib/python3.5/site->packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/Users/c/.virtualenvs/django-budget/lib/python3.5/site->packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/c/.virtualenvs/django-budget/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/c/.virtualenvs/django-budget/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/c/sites/budget/budget/views.py" in edit_transaction 83. form = TransactionForm(instance=transaction) Exception Type: TypeError at /budget/transaction/3/edit/ Exception Value: init() missing 1 required positional argument: 'request' extract from urls.py: url(r'^transaction/(?P<pk>[0-9]+)/edit/$', views.edit_transaction, name='edit_transaction'), extract from views.py: @login_required def edit_transaction(request, pk): transaction = get_object_or_404(Transaction, pk=pk) if request.method == "POST": form = TransactionForm(request.POST, instance=transaction) if form.is_valid(): transaction = form.save(commit=False) transaction.updated = timezone.now() transaction.save() return redirect('view_transaction_detail', pk=transaction.pk) else: form = TransactionForm(instance=transaction) return render(request, 'budget/new_transaction.html', {'form': form}) template extract: {% extends 'budget/base.html' %} {% block content %} <h2>{{ transaction.title }}</h2> <h4>{{ transaction.date }}</h4> <h4>Transaction type: {{ transaction.transaction_type }}</h4> <h4>Category: {{ transaction.category }}</h4> <h4>Budgeted amount: {{ transaction.budgeted_amount }}</h4> <h4>Actual … -
Button Like In Django- Getting likes For only the First Post
I am Trying to implement like buttons in my Html using Django, jquery, and Ajax. I thought it was working well, but later realized that the likes are only getting incremented for the first post. Here is the HTML page <div class="col-sm-10 col-sm-offset-1"> {% for it in lists %} <div class="row"> <div class="col-sm-12"> <div class="thumbnail"> {% if lt.image%} <!img src="{{ lt.image.url }}" class="img-responsive"> {% endif %} <img src="{{ lt.image.url }}" alt="..."> <div class="caption"> <h3><a href="{% url 'posts:detail' lt.id %}">{{ lt.title}}</a><small> {{ lt.timestamp|timesince }} ago</small></h3> <p>{{ lt.content|linebreaks|truncatechars:120 }}</p> <p><a href="{% url 'posts:detail' lt.id %}" class="btn btn-primary" role="button">View</a></p> <button id="likes" data-catid="{{ lt.id }}" class="btn btn-primary glyphicon glyphicon-thumbs-up" type="button"> Like {% if lt.likes > 0 %} {{lt.likes}} {% endif %} </button> </div> </div> </div> {% endfor %} </div> And this is the Jquery $(document).ready(function(){ $('#likes').click(function(event){ alert("button") event.preventDefault(); var element=$(this); $.ajax({ url : '/posts/like_category/', type : 'GET', data : { category_id: element.attr("data-catid")}, success : function(response){ element.html(' ' + response) } }); }); }); The likes are Incremented only for the first post, I Think the problem is with my HTML page. Please help me to sort out this problem. -
Serve files without exposing directory structure in Django
Right now, for every Foo object in my database I have related file that is being stored in path that has following structure some/example/path/foo/pk/name.txt. The default way of serving them in Django would be by specifying MEDIA_ROOT and MEDIA_URL in settings. This way, I could access file related with Foo object with id=1 by visiting localhost:8000/media/foo/1/name.txt and similar way for other objects. But I would prefer not to expose to user how the files are stored internally (directory structure, primary keys etc.) and serve them from localhost:8000/media/mapped_path_to_name.txt. For now, the only solution I can think of is to create custom view responsible for serving files and in this view put logic that does paths mapping. Is there any more elegant(minimalistic) solution to this problem? -
Django blogs not looping properly
I have created a blog with Django that I originally looped through each post with: <div class="container"> <h2 class="latest-posts">Latest Posts</h2> <hr /> {% for post in posts.all %} <h4><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h4> <i class="fa fa-calendar" aria-hidden="true"></i> {{ post.pub_date_pretty }} <img src="{{ post.image.url }}" class="img-responsive center-sm-block" style='width:75%; text-align:center;' /> <br/> <p>{{ post.summary }}</p> <br/> <br/> {% endfor %} </div> Which worked great! But I didn't just want to have a linear list of post and wanted to display each unique post in a bootstrap card which I attempted with this solution: <div class="container"> <h2 class="latest-posts">Latest Posts</h2> <hr /> {% for post in posts.all %} <div class="row"> <div class="col-12 col-md-6"> <!-- Card --> <article class="card animated fadeInRight"> <div class="card-block"> <h4 class="card-title"><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h4> <h6 class="text-muted">Antoine de Saint-Exupéry</h6> <p class="card-text">{{ post.summary }}</p> </div> <div class="card-block text-center"> <div class="btn-group hidden-sm-down hidden-md-down" role="group" aria-label="Card buttons"> <a href="#" class="card-link">Read more</a> </div> </div> <img class="card-img-bottom img-responsive" style='width:100%; text-align:center;' src="{{ post.image.url }}" alt="White sand" /> </article><!-- .end Card --> </div> <div class="col-12 col-md-6"> <!-- Card --> <article class="card animated fadeInRight"> <div class="card-block"> <h4 class="card-title"><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h4> <h6 class="text-muted">Antoine de Saint-Exupéry</h6> <p class="card-text">{{ post.summary }}</p> … -
custom django command - help string not visible
Following is a custom command I have written in following file myapp/management/commands/create_myadmin.py from django.core.management.base import BaseCommand from django.contrib.auth.models import User class Command(BaseCommand): help = 'Creates a superuser that can view the admin page' def handle(self, *args, **options): try: user = User.objects.get(username='myadmin') except User.DoesNotExist: user = User.objects.create_superuser('myadmin', 'myadmin@mymail.com', 'myadmin') user.save() After this, I added myapp into INSTALLED_APPS in myproject/settings.py My problem is that when I use autocomplete feature and list down commands starting with "create", it doesn't show help string against create_myadmin as shown below python3 manage.py create (pressed tab here) createcachetable -- creates table for SQL cache backend createsuperuser -- create a superuser create_admin_user (help string missing??) I expected the string stored in help variable to be visible here. Any quick pointers? Update: I checked code for django/core/management/commands/createcachetable.py and the help text mentioned there doesn't match what I got above. Any idea where can one define the help text shown in above autocomplete? -
How to iterate over the pk_set in m2m_changed Django ManyToManyField
I have a model Course declared as follows class Course(models.Model): ... students = models.ManyToManyField(settings.AUTH_USER_MODEL, editable=True, verbose_name="students", related_name="students, null=True) Another model Member as the AUTH_USER_MODEL class Member(models.Model): ... courses = models.ManyToManyField(Course) The model Member has a m2m_changed connected signal on Member.course.through declared as followed: @receiver(m2m_changed, sender=Member.courses.through) def courses_member_changed(sender, **kwargs): if action == 'post_add': # how to iterate over the pk set here? for id in pk_set: c = Course.objects.get(pk=id) instance.courses.add(c) c.students_set.add(instance) c.save() instance.save() When performing a PUT/PATCH operation on the Member object changing the courses on the model the signal get's called but ends up with a RuntimeError: maximum recursion depth exceeded in comparison [04/Mar/2017 17:18:18] "PUT /members/2/ HTTP/1.1" 500 3296498 How do I correctly update the Course.students field when a member(student) updates his own object. -
Django self.client.post does not send data to view with decorator
I have a simple test case which checks that POST request with valid data returns an HTML response with 200 status code: class PostRequestTestCase(TestCase): def test_valid_post_request(self): response = self.client.post('/foo/', data={'text': 'bar'}) self.assertEqual(response.status_code, 200) Here is the view foo which is triggered for that request: logger = logging.getLogger(__name__) # decorator to trace enter and exit events enter_exit_tracer = enter_exit_Tracer(logger) @enter_exit_tracer def foo(request): if request.method == 'POST': # print('request.POST:', request.POST) # # some stuff where @enter_exit_tracer is a decorator to trace entering/exiting a function: def enter_exit_Tracer(logger): def middle(f): def inner(*args, **kwargs): logger.debug('Enter %s.', f.__name__) result = f(*args, **kwargs) logger.debug('Exit %s.', f.__name__) return result return inner return middle It turns out that when I add this decorator to foo function, then the POST data sent via self.client.post are actually not passed to foo. They are missing in the test request - so my test fails: request.POST: <QueryDict: {}> ERROR: Invalid form F ====================================================================== FAIL: test_valid_post_request (textstat.tests.PostRequestTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/Pro/myapp/tests.py", line 111, in test_valid_post_request self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.018s FAILED (failures=1) We see request.POST: <QueryDict: {}> and eventually this leads to ERROR: Invalid form. At the same time when I do the … -
Django search Query not working
So Im trying to filter my posts using a search query, however every time I press search all the posts are loaded regardless of the query. Was hoping for some help. This is my views.py: def post_timeline(request): object_list = Post.objects.all() #order_by("-post_date") paginator = Paginator(object_list, 7) if request.GET.get("q"): object_list = object_list.filter(post_title__contains=request.GET.get("q")) page = request.GET.get('page') try: object_list = paginator.page(page) except PageNotAnInteger: object_list = paginator.page(1) except EmptyPage: object_list = paginator.page(paginator.num_pages) context = { "object_list": object_list, "title": "Timeline", } return render(request, "post_timeline.html", context) And here is the html: <form method="GET" action=""> <li><input type="text" name="q" value="{{ request.GET.q }}"placeholder="Search by Title"></li> <li><button type="button input" class="button">Search</button></li> </form> Thanks for any help! -
Python and HTML
I've created a web template using django and need to open a open an audio file where signal processiong takes place in the background with the use of python code to give an appropriate result. How do I link all these? I'm new at this -
How to use Django template variables in template tags
I've defined a custom tag function and am trying to pass two arguments into the function that are derived from the array I'm looping through. Essentially, I'm trying to do something akin to the following: {% for x in array %} {% custom_tag_function {{ forloop.counter }} {{ array|length }} %} {% endfor %} However I'm receiving a parsing error as django is passing in the argument as a string (e.g. "{{ forloop.counter }}") instead of the evaluated value. I tried to do this: {% for x in array %} {% with cnt={{ forloop.counter }} len={{ array|length }} %} {% custom_tag_function cnt len %} {% endfor %} But I receive the same parsing error. Is there a proper way to do this within django? -
the using of AuthenticationForm in django return no errors
I'm trying to use the AuthenticationForm model to authenticate my users. Here is my view : from django.contrib.auth.forms import AuthenticationForm def connection(request): if request.user.is_authenticated(): return redirect('user:profile') if request.method == "POST": connection_form = AuthenticationForm(request.POST) if connection_form.is_valid(): username = connection_form.cleaned_data["username"] password = connection_form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: login(request, user) if next is not None: return redirect(next) else: return redirect('home') else : connection_form = AuthenticationForm() return render(request, 'user/connection.html', { 'connection_form': connection_form }) It almost works. But my problem is that no errors are returned by the form when the username and/or the password are incorrect. When i try this in the shell it works >>> POST = {'username' : 'test', 'password' : 'me', } >>> form = AuthenticationForm(data=POST) >>> form.is_valid() False >>> form.as_p() '<ul class="errorlist nonfield"><li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li></ul>\n<p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" value="test" required /></p>\n<p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p>' Any ideas ? -
Newly added database entry is not visible from other model
I'm playing around with django framework and trying to create some expense tracking application as an exercise. I got two models: Category and Expense: class Category(models.Model): name = models.CharField(max_length=50) class Expense(models.Model): categories_list = Category.objects.order_by('name') categories_tuples = ((x.name, x.name) for x in categories_list) category = models.CharField(max_length=50, choices=categories_tuples) add_date = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2) I also got two forms for adding new Categories and new Expenses: class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['category', 'add_date', 'amount'] class CategoryForm(ModelForm): class Meta: model = Category fields = ['name'] I use these forms in separate views: def new_expense(request): if request.method == "POST": form = ExpenseForm(request.POST) if form.is_valid(): expense = form.save(commit=False) expense.save() return redirect('index') else: form = ExpenseForm() return render(request, 'expenses/new_expense.html', {'form': form}) def new_category(request): if request.method == "POST": form = CategoryForm(request.POST) if form.is_valid(): expense = form.save(commit=False) expense.save() return redirect('index') else: form = CategoryForm() return render(request, 'expenses/new_category.html', {'form': form}) So, the desired behaviour is that I can add new Category with assigned name and color and after that it should be possible to add new Expense using data from new Category database entry. The problem is that after adding new Category in new_category view and switching to new_expense view, newly added Category name … -
How do I make Django template HTML file load CSS/JS without putting Django code in the HTML file?
I have an index.html in my templates folder. In the HTML file's head tag is <script src="scripts/main.js"></script>. When I open a terminal in templates/ and run python manage.py runserver, the HTML loads just fine. But I get a 404 error like this: GET /PATH/TO/scripts/main.js HTTP/1.1" 404 2446 index.html can't find my JS file. Without editing index.html, how do I make the HTML file load the JS file? -
Get full URL in Django
What is the right way to get full URL (including the domain name) for a view in Django? It seems that reverse returns partial URLs (without the domain). -
The best way to run function on each page
I have one question, namely, what is the best way to run any function on each python application in the project? For example, I have 1 project - bbCms which contains 2 apps - articles and board. And I would like to run function doSomething on each page of these apps. On PHP I can create file, e.g. functions.php, type code and inside each app by require run this function. How can I solve this problem in Python (django)? -
How to reproduce the behaviour of TabularInline in ModelAdmin outside of Django admin, when ManyToManyField.through is used?
I am building upon the Person-Group-Membership example from the documentation: https://docs.djangoproject.com/en/1.8/topics/db/models/#extra-fields-on-many-to-many-relationships from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) def __str__(self): return self.person.name.upper() + ' in ' + self.group.name.upper() The crucial point here is that Members is in Group through Membership. I have added a way to edit the membership in the admin both from person and from group, using TabularInline: from django.contrib import admin from .models import Person, Group, Membership class MemberInline(admin.TabularInline): model = Membership class PersonAdmin(admin.ModelAdmin): inlines = [MemberInline] class GroupAdmin(admin.ModelAdmin): inlines = [MemberInline] admin.site.register(Person, PersonAdmin) admin.site.register(Group, GroupAdmin) How could I recreate this behaviour outside of the Django admin? And more generally: Is there a simple way to get from something that works in the admin to something that works on a different page? -
Radio Buttons within Django
I'm Trying to create a questionnaire within Django which will ask a user 10 questions then input that data into a database to be analysed later on class QuestionForm(forms.Form): q1 =forms.ModelChoiceField(), q2 =forms.ModelChoiceField(), q3 =forms.ModelChoiceField(), forms.ChoiceField(choices=CHOICES, Widget=forms.RadioSelect()) My current forms.py is laid out like so and I'm trying to use the Radio select widget to make Django use Radio select. Views.py Below def questions(request): form = QForm(request.POST or None) if form.is_valid(): choice = form.save(commit=False) choice=form.cleaned_data['choice'] choice.save return render(request, 'music/question.html') I feel like I'm on the wrong track and none of the Django documentation helps with understanding. -
Django MultiChoice widget with Add Button
I'm using Django 1.10. I do not understand as to why the multichoice widgets lack so much basic functionality. I would like to add something like this to the multichoice widgets. So far here is what I've tried but failed bad. It makes no difference at all and nothing gets added. Please help me out thanks. class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js") def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, readonly=False, attrs=None, choices=()): output = [super(FilteredSelectMultiple, self).render(name, value, attrs=attrs)] if readonly: return mark_safe(u''.join(output)) output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % \ (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX)) return mark_safe(u''.join(output)) -
Apache unable to load virtualenv properly: "ImportError: No module named 'psycopg2._psycopg'"
I moved my Django project from Python 2.7 to Python 3.6. Since then, I can't get my project up & running, as Apache complains as follows (full output after a restart): [mpm_prefork:notice] [pid 2340] AH00173: SIGHUP received. Attempting to restart [:notice] [pid 25019] FastCGI: process manager initialized (pid 25019) [:warn] [pid 2340] mod_wsgi: Compiled for Python/3.4.0. [:warn] [pid 2340] mod_wsgi: Runtime using Python/3.4.3. [mpm_prefork:notice] [pid 2340] AH00163: Apache/2.4.7 (Ubuntu) mod_fastcgi/mod_fastcgi-SNAP-0910052141 PHP/5.5.9-1ubuntu4.21 OpenSSL/1.0.1f mod_wsgi/3.4 Python/3.4.3 configured -- resuming normal operations [core:notice] [pid 2340] AH00094: Command line: '/usr/sbin/apache2' [:error] [pid 25025] [client 10.0.10.117:49933] mod_wsgi (pid=25025): Target WSGI script '/home/myuser/projects/myproject/myproject_project/wsgi.py' cannot be loaded as Python module. [:error] [pid 25025] [client 10.0.10.117:49933] mod_wsgi (pid=25025): Exception occurred processing WSGI script '/home/myuser/projects/myproject/myproject_project/wsgi.py'. [:error] [pid 25025] [client 10.0.10.117:49933] Traceback (most recent call last): [:error] [pid 25025] [client 10.0.10.117:49933] File "/home/myuser/projects/myproject/myproject_project/wsgi.py", line 29, in <module> [:error] [pid 25025] [client 10.0.10.117:49933] application = get_wsgi_application() [:error] [pid 25025] [client 10.0.10.117:49933] File "/home/myuser/.virtualenvs/myproject-3.6/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [:error] [pid 25025] [client 10.0.10.117:49933] django.setup(set_prefix=False) [:error] [pid 25025] [client 10.0.10.117:49933] File "/home/myuser/.virtualenvs/myproject-3.6/lib/python3.6/site-packages/django/__init__.py", line 27, in setup [:error] [pid 25025] [client 10.0.10.117:49933] apps.populate(settings.INSTALLED_APPS) [:error] [pid 25025] [client 10.0.10.117:49933] File "/home/myuser/.virtualenvs/myproject-3.6/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate [:error] [pid 25025] [client 10.0.10.117:49933] app_config = AppConfig.create(entry) [:error] [pid … -
The jquery file not gettting loaded in Django
I am trying to load the jquery files to the Django. But its not working for me. When I write the code inside the script tag inside the Head its work perfectly.I wrote the code in a file called main.js <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"> </script> <link rel="stylesheet/javascript" href="{% static 'js/main.js' %}"> This is my static path in settings STATIC_URL = '/static/' How can I load the jquey file to the django. I think its a stupid question. Anyway please help me. ThankYou -
recommended location for static & templates directories
I am a little bit confused about the recommended location of the templates and static directories. Apparently it is better to have 1 templates directory in every app folder. Django automatically look for templates there. However it seems not to be the case for static, is it? Can I tell django to look for static within the directory of the app currently running (instead of a single directory in the root folder)? Thanks. -
Is it complusory to pass instance to serializer in DRF?
Suppose I have a serialize DeviceGroup and a APIView class for posting devices into the group. The serializer for DeviceGroup is class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) class Meta: model = DeviceGroup fields = ['id','name'] class DevicesGroupsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, token=None, format=None): print('reqquest', request.data) print('token', token) device_group_instance = DeviceGroup.objects.get(token=token) for device_token in request.data['devices']: device = Device.objects.get(token=device_token, owner=request.user) device.group = device_group_instance device.save() In above post function, is it compulsory to create a instance of serializer and check if serializer is valid then return the response. The relation between Device and DeviceGroup is a device can be on only one group and a group can have multiple devices(list of device ids) How should the post function be if i need to use DeviceGroupSerializer to post the list of devices? I did not understand this serializer and view part clearly. -
Nginx and uwsgi connection refused when placed in separate docker containers
I am setting up a Django project and using combination of nginx and uwsgi to serve them. Plus, I am using docker to put django+uwsgi in one container and nginx in other. For testing purpose, I want to set this up locally and I want to use a custom domain name as well for testing. I am really struggling to set it up. This is my nginx.conf user nginx; worker_processes 1; 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 main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; #gzip on; upstream app { server 0.0.0.0:8000; } server { listen 80; charset utf-8; server_name someapp.app *.someapp.app; location / { # checks for static file, if not found proxy to app uwsgi_pass app; include uwsgi_params; #try_files $uri @proxy_to_app; } location /static { alias /static; } location /media { alias /media; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://someapp.app; } } } and this is my uwsgi.ini [uwsgi] http-socket = 0.0.0.0:8000 chdir = /app master = true processes = 4 cheaper = 2 …