Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTP Authentication Error with Django on Heroku
I am trying to send emails from my django app using the the gmail smtp servers. The emails are being sent when I run the application on my local server. But I'm getting an SMTP Authentication Error while using it on heroku. Traceback - link settings.py - # Email configuration. EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '***************@gmail.com' EMAIL_HOST_PASSWORD = '************' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = '******************@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' And I have rechecked the account password, also I have enabled the access of less secure apps from my google account. But still I am getting this error. -
Seeking guidance on debuging Django/mod_wsgi/apache performance
I've inherited a Django application currently hosted in docker/EC2 (python 3.6) running nginx/gunicorn with Postgres RDS. It's reasonably simple application whose big demand is to generate a very large template that is then spit out as a pdf report. The current production app takes about 1 to 2 minutes to render and download the file (about 1 MB). I've been looking to migrate the application into Beanstalk. Things going well except performance. Same code takes about 2x to 3x to render. Been trying to figure out how to bring them into line and what the diff is. New beanstalk environment is running the same instance size. Differences are: Python 3.4 vs production 3.6 Apache/mod_wsgi vs nginx/gunicorn. My suspicion is that I haven't configured apache correctly (followed https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/). I haven't instrumented the code yet so don't have proof of where the time is spent but that's what I'm thinking. This is obviously wage but wondering about guidance on tuning beanstalk/django application on apache/mod_wsgi and what I might consider looking into first. Can provide any details required. Just not sure what's helpful. -
Django Middleware Error
I'm trying to write a custom django middleware package by referring an example here: from django.conf import settings class StackOverflowMiddleware(object): def process_exception(self, request, exception): if settings.DEBUG: print exception.__class__.__name__ print exception.message return None and this is present at location venv/lib/python2.7/site-packages/django_error_assist/middleware.py I try to invoke/include this middleware in my django settings as follows: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_error_assist.middleware.StackOverflowMiddleware', ] But I get a traceback which I've been struggling to get rid of which follows like this : File "/Users/Shyam/PycharmProjects/untitled/untitled/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parameters Where am I going wrong ? Any leads/help will be appreciated. I'm trying to make this middleware a pip package. I also did my homework of looking into this, this and of course the official django link but couldn't get much help from these as in where am I going wrong. -
Django formset raises KeyError `form-0-id`
I'm trying to save a formset but I keep getting django.utils.datastructures.MultiValueDictKeyError: "'form-0-id'" modelformset.forms raises the same error. There is an autogenerated id field in the database table, but not specified explicitly in the model (not sure if that's relevant). Here's the view that I post to: def submit(request, list_id): OrderedManInputFormSet = modelformset_factory( OrderedManInput, form=OrderedManInputForm ) modelformset = OrderedManInputFormSet(request.POST) pprint(modelformset.management_form.__dict__) print(modelformset.save()) return HttpResponseRedirect( reverse('collector:thanks') ) Here's the html that does the posting: <form action="{% url 'collector:submit' list_id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} <table id="id_data_table"> {% for form in formset %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr> {%for field in form.visible_fields %} <td> {{field}} </td> {%endfor%} </tr> {% endfor %} </table> <p/> <div class="div-submit"> <input type="submit"/> </div> </form> so each row is a form and each column a field: Here's a question that seems very close, but adding {{form.id}} right before {%for field in form.visible_fields %} does not seem to help. -
How to create a dynamic Django choice field
I am trying to generate a list to populate choices for a form. This list will be dynamic and will depend on what choices have been created by other users. Here is an example of the model the list should derive from: #models.py class User(models.Model): brewery_you_work_for = models.CharField(choises=ALL_THE_BREWERIES_IN_THE_WORLD) username = models.CharField() I want the form to be something like this: #forms.py class BestBrewery(forms.Form): vote = forms.ChoiceField(choices=BREWERIES_A_USER_WORKS_FOR) What I want to do is have a list of all the breweries in the world for some users to select as the brewery they work for. Then I want to generate a list for other users to vote as the best brewery. Lets say I have 3 users that claim they work the Sierra Nevada, 2 users that claim they work for Budweiser, and 5 users that claim they work for Coors. I want to generate a list of breweries that would look like this: ( 'Budweiser', 'Coors, 'Sierra Nevada', ) Note the alphabetical order and no repeated brewery listings. Any help is appreciated! -
I wanna write all in javascript
I wanna write all in javascript.I made a web site was changed background&h1&p 's color.The colors' data are in model is made in Python&Django.So,in that time,I used changed color data in the model.Now,I can get color data in json format,so I wanna embed the json data in html and work corectly like before.But I cannot understand how I can do it. index.html is <!DOCTYPE html> <html> <head lang="ja"> <meta charset="UTF-8"> </head> <body> {{ form }}<br> <hr> <h1>h1LETTER</h1> <p>pLETTER</p> {{ form }}<br> <hr> <h1>h1LETTER</h1> <p>pLETTER</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> color_array = { for (var i=0 ; i<=colors.length ; i++){ "{{ color.id }}" : { "background-color" : "{{ color.background_color }}" , "h1" : "{{ color.h1_color }}" , "p" : "{{ color.p_color }}" , }, } }; function change_color(){ color_id = $("#id_color").val(); color_object = color_array[color_id]; $("body").css("background-color", color_object["background-color"]); $("h1").css("color", color_object["h1"]); $("p").css("color", color_object["p"]); } $( '#id_color' ).change( function () { change_color(); }); change_color(); var xhr = new XMLHttpRequest(); xhr.onload = function(){ colors = JSON.parse(xhr.response) console.log(color) } xhr.open("GET","http://localhost:8000/app/api/get/",false); xhr.send({}) </script> </body> </html> In this part, var xhr = new XMLHttpRequest(); xhr.onload = function(){ colors = JSON.parse(xhr.response) console.log(color) } xhr.open("GET","http://localhost:8000/app/api/get/",false); xhr.send({}) especitally in colors = JSON.parse(xhr.response),I can get color data in json."{{ color.id }}" & "{{ color.background_color }}"&"{{ … -
Using Django w/ mod_wsgi and Apache
I've been trying to work out how I'll go about setting up a Django application on production, when it's ready for deployment. I'm using Django v1.11, and my EC2 is running Ubuntu 14.04. I have been attempting to refer to this guide as reference, however it is not specific to Ubuntu, so I've been experiencing a bit of difficulty in this regard. I've referred to several other resources, but much of what is out there seems to be outdated. I have a host rule set up on my local machine, pointing www.example.com to my EC2 instance's public IP address. I have a virtualenv set up which lives in /home/django/example.com/ENV. My Django project lives in /home/django/example.com directly. The project name is mysite, and was generated using django-admin startproject mysite, thus it has the default wsgi.py file inside the /home/django/example.com/mysite directory. The contents of wsgi.py look like: """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() I've tried adding VirtualHost rules such as the following: <VirtualHost *:80> ServerName example.com ServerAlias www.example.com WSGIScriptAlias / /home/django/example.com/mysite/wsgi.py … -
How to connect models from different apps in Django?
I have a few apps within my Django project. There are two apps that I am currently working with: "Application" and "User" and I have two questions related to models: Question 1: I want to design it in such a way so that external users submit their contact form on Application/templates/Application/Apply.html and the info would get added to the database. Internal users would be able to add external users as well but from a different template: User/templates/User/AddNewContact.html I am able to add new contact from an internal user's perspective: User/models.py class Contact(models.Model): ContactName = models.CharField(max_length = 250, default='') ContactResidence = models.CharField(max_length = 250, default='') Tel = models.CharField(max_length = 250, default='') def get_absolute_url(self): return reverse('User:ContactDetails', kwargs={'pk': self.pk} ) def __str__(self): return self.ContactName class Locations(models.Model): contact = models.ForeignKey(Agent, on_delete=models.CASCADE) Country = models.CharField(max_length=250, default='') def __str__(self): return self.Country I was going to just copy this model and paste it into Application/models.py but there are two problems: 1) I don't want external users to be directed to url: User:ContactDetails and technically, it is not going to work out because I will build the authentication later on. 2) I feel that by copying and pasting I am breaking the 'don't repeat yourself" rule. Should I … -
Django CSS only works on certain elements
I've just added some CSS the my django project in a static folder and it only works on some elements. The file is loaded on the site but when I try to make changes to the paragraph element nothing happens. When I edit the body element in the external style sheet it does have an effect on the style. Here is my css and HTML: HTML <!DOCTYPE html> <html> {% load staticfiles %} <head> <title>Would-be Username</title> <link rel="stylesheet" type="text/css" href="{% static 'css/test.css'%}"> </head> <body> <img src="{{ current_user.userprofile.profile_picture.url }}"> <p>Username: Would-be Username</p> <p>Name: {{ current_user.userprofile.first_name }} {{ current_user.userprofile.last_name }}</p> <p>Email: {{ current_user.username }}</p> <a href="{{ request.path }}edit/">Edit</a> <a href="/reset-password/">Forgot your password?</a> </body> </html> CSS @charset "UTF-8" p { color: red; } body { margin: 0; } The body margin changes, and I can change the color of the text when I add color: red; to the body. However, no matter what I do to 'p', nothing happens. What am I doing wrong that won't let me edit the 'p' tags? -
Is there a way to use Wagtail Snippets to display existing Django Models?
With Wagtail CMS, what is the best way to mimic the "Plugin" functionality of Django CMS? In Django CMS I am able to write a custom plugin that can display a template and any related information to that model. Content Managers can then add that plugin to a placeholder anywhere on the site. With Wagtail, the closest thing I can find is the Snippet, but each time you use the Snippet you have to include it specifically in the Page model. Take these two models for example: class Pet(models.Model): species = models.CharField(max_length=10) name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) For the content manager to be able to access these I'd need to register them as snippets, and then list each model in that page's model like so: class HomePage(Page): content_panels = Page.content_panels + [ SnippetChooserPanel('pet'), SnippetChooserPanel('book'), ] Is there a better way to do this with Wagtail? -
How can I implement the concept of ANDs and ORs with predicates and brackets in Django
If I have 4 functions f1, f2, f3 and f4 which return True or False depending on custom criteria, how I can implement the concept of having brackets around functions in Django? For example: (f1 OR f2) AND (f3 AND f4) Right now, I have a Criteria model and a GroupCriteria model each with a boolean operator field. I also have a RuleSet model which contains a many to many relation to the other models. However, I am struggling to think of how to combine boolean operators with brackets. -
Django trying to add up values in the django template
Hi Guys I am trying to figure this out but not having any luck. So I am showing my events in the homepage which shows how many seats are available, once the user has made a booking I would like to minus that from the amount showing on the homepage. But I am already stuck at adding all the values up for that event in the booking model to minus from that amount. So this is what I have model for events class Events(models.Model): ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),) ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing')) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True, default='') date = models.DateField() time = models.TimeField() price = models.CharField(max_length=240, blank=True, default='') seats = models.IntegerField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) model for bookings class Bookings(models.Model): OPTIONS_STATUS = (('y', "Yes"), ('n', "No"), ('p', "Pending"),) user = models.ForeignKey(User, on_delete=models.CASCADE) event = models.ForeignKey(Events, on_delete=models.CASCADE) eventdate = models.DateField() event_amount = models.CharField(max_length=50, blank=True, default='') guests = models.IntegerField() bookingstatus = models.CharField(max_length=50, default='p', blank=True, choices=OPTIONS_STATUS) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) my homepage how I get my data into a loop form the view today = datetime.now().strftime('%Y-%m-%d') events_list_data = Events.objects.filter(active='a').filter(Q(date__gte=today)|Q(date=today)).order_by('date') How I am … -
Django - Show list of purchases in user's profile - include template with list from another app
I'm doing a project with Django and I'm using PayPal subscriptions. When you buy a product it saves the details in the Purchases table (by the way, it writes the purchase 3 times in the DB, but that's for another question). Now I'm trying to show a list of purchases in the user's profile template. I have a purchases template with the list and it works when I see it through its own URL, but whenever I try to show it in other templates it's just blank. This is my structure: Apps: Account, Product, PayPal Models: User(custom), Product, Purchase Templates: profile, products, purchases, paypal_return/cancel,... Views: register, login, logout, all_products, paypal_return/cancel,... templatetags/products_extra: paypal_form_for, and right now a simple_tag with purchases_list (I also tried with just a view in products/views.py) And my questions are: Should I have a different app for purchases? What is the best way to build the purchases list and show it in a template in another app? I've read loads of posts and documentation and tried just including the template {% include.. %}, with simple_tags, with template inheritance, inclusion tags... but I cannot make it work. Below is the code I have right now. Thank you in advance! … -
"403 CSRF cookie not set" when doing POST on Android, with CSRF_USE_SESSIONS = True (Django 1.11)
Good evening, Following this discussion, we are facing a new problem. We are trying to make a POST request (login) work on Android using the Volley library to make HTTP requests. The /login/ works well on Postman or Advanced REST Client, but it doesn't when using Volley. We have seen many other persons facing this problem and trying to find an answer on SO, but the only answer was to disable CSRF and we really don't want to do this. On Postman, the response is 200 OK. On Android Volley, the response is 403 forbidden : CSRF cookie not set. Since we set CSRF_USE_SESSIONS as True, it doesn't make sense for us. CSRF_USE_SESSIONS is True in Django The library used to make HTTP requests on Android is Volley We don't want to disable CSRF protection/middleware (I'm pointing this because many answers in other posts talking about this problem suggest to disable CSRF, but we are using it for both web client and mobile apps) Here is the Java request : private void loginPost(final String csrf) { RequestQueue queue = Volley.newRequestQueue(getActivity()); String url = "https://api.ourapi.com/login/"; JSONObject object = new JSONObject(); try { object.put("username", "hello"); object.put("password", "world"); System.out.println(object); } catch (JSONException e) … -
django rest framework not parsing utf8 ¿Some idea?
I'am trying to migrate my old backend to django rf,i have my old mysql database with utf8 in my database for example a name is saved as "Felipe Niño Arango" i not sure but i think drf should decode this in response "Felipe Niño Arango". I'am trying passing the chartset to db options: 'OPTIONS': { 'charset': 'latin1', 'use_unicode': True, } ¿Some idea? -
Upload file in a folder with date time Using Django
I am trying to upload a file in a project folder from admin.After the file is uploaded in the project folder I would like to process that file and insert data in table. accounts/forms.py- class CouplingUploadForm(forms.ModelForm): def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] valid_extensions = ['.xml'] if not ext.lower() in valid_extensions: raise ValidationError(u'Only files with ".xml" extension are supported, ' 'received: "%s" file.' % ext) coupling_file = forms.FileField(label='XML File Upload:', required=True, validators=[validate_file_extension]) class Meta: model = models.Coupling exclude = ['coupling_name', 'module_name'] accounts\admin.py - class couplingAdmin(admin.ModelAdmin): list_display = ('coupling_name','module_name') form = CouplingUploadForm def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) return HttpResponse("Successful") return HttpResponse("Failed") def handle_uploaded_file(file, filename): if not os.path.exists('uploads/'): os.mkdir('uploads/') with open('uploads/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) admin.site.register(Coupling, couplingAdmin) The above code is not triggering I think. I want to upload and then process the file from admin. But the file is not uploading. There is no model.FileField so I won't be able to use upload_to. Any help/suggestion is highly appreciated. Thanks in advance. -
Django: Use model field value as valid template tag in html template
I have a part on my site where an admin user can create new widget which display in the sidebar on the homepage. I would like to allow users to input code into the form and have the code act as valid code within the template instead of just text. I can't find anything on stack overflow and google which talks about this. So far I have the form and template setup which allows users to add widgets however it is displayed in the page rendering is text instead of executing it as code. Here is what I have so far and what it is doing, I think you'll be able to see what I'm going for based on the code that is being displayed as standard text. Adminpanel app models.py: from django.db import models # Create your models here. class Widget(models.Model): name = models.CharField(max_length=50) widget_order = models.IntegerField(blank=False,unique=True) body = models.TextField(max_length=500) def __str__(self): return self.name Adminpanel app widget_list_inner.html template: {% for widget in widget_list %} <div class="widget"> <div class="widget-content"> <p>{{ widget.body }}</p> </div> </div> {% endfor %} Adminpanel app widget_form.html template: {% extends "base.html" %} {% block content %} <div class="colorset-base"> <h2>Create new widget</h2> <form id="postForm" action="{% url 'adminpanel:create-widget' %}" … -
running django on apache
First of all: please don't blame me for making newbie mistakes or anything like that. I am still learning and need just a bit of help. So I created a droplet on digitalocean with ubuntu 16.04 and logged in and ran: sudo apt-get update sudo apt-get upgrade sudo apt-get install python-setuptools python-pip apache2 libapache2-mod-wsgi and installed django: sudo pip install Django==11.1.4 and created the project (without virtualenv) in a directory: django-admin.py startproject mysite However, if I do "runserver" python manage.py runserver and type xxx.xxx.xxx.xx:8000 in firefox there is nothing even though I see in the terminal that the runserver did work. If I type xxx.xxx.xxx.xx then I see the default page of apache. My goal is to run django over apache but I cannot even get started because the runserver which is just for testing didn't even work. How can I make this work, where did I make a mistake? -
Django - call to missing asset blocks render of template
I have a template where I render this block: {% for producer in producers %} <a class="ProducerCard" href="{% url 'show_djprofile' producer.slug %}" style="background: linear-gradient( rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.65) ),url('{{ producer.img.url }}'); background-size: cover"> <span class="Producercard__name"> {{ producer }} </span> </a> {% empty %} <span>{% trans "Sorry, no Producers available." %}</span> {% endfor %} If producer.img.url is missing the whole template is not rendered. I'd like to understand why, and how to avoid this problem. Also, this issue is only happening in production environment (Heroku); in my local system I don't have this problem. -
Django: Show link based on model field value
I want the "Admin" link to display based on a field in my UserLevels model called "access_level". If the currently logged in user's access_level field is equal to "admin" then the "Admin" link should display. Currently there are no errors however the "Admin" link will display for every logged in user and not take into account the access_level field value. HTML: {% if user.is_authenticated and userlevels.access_level == 'admin' %} <a class="nav-link" href="{% url 'adminpanel:widgets' %}">Admin</a> {% endif %} Adminpanel app models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserLevels(models.Model): user = models.OneToOneField(User) access_level = models.CharField(max_length=5,default='user',blank=True) def __str__(self): return self.user.username -
What is the best way to insert a record in log/history table in django
I have two models: class RateCard(models.Model): name = models.CharField() pricing_type = models.ForeignKey(PriceAttribute) and class RateCardHistory(models.Model): name = models.CharField() pricing_type = models.ForeignKey(PriceAttribute) what i want is on every operation in RateCard a new record should get insert RateCardHistory Which one will best way to achieve this Django signals post_save or over ride the RateCard save method or is there any other approach which will be good. -
django - how save in mysql "Angela CR Céspedes RodrÃguez" not "Angela CR Céspedes Rodríguez"
I have to use the same database for two apps one with yii as backend php and other with django the problem that i have is when i save a name for example in yii "Angela CR Céspedes RodrÃguez" vs in django "Angela CR Céspedes Rodríguez" i need save in django in the same way. -
Django and Vue issue
At my Django project I have some problems with Vue.js. HTML: <script type="text/javascript" src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script> <div id="app"> <button class="like-button" :class="{ 'active': active }" @click="liked"><% active ? likedText : buttonText %></button> </div> <script type="text/javascript" src="{% static 'board/script.js'%}"></script> Script.js var app = new Vue({ el: '#app', data: data, delimiters: ["<%","%>"] data: { active: false, buttonText: 'Like this', likedText: 'You like this' }, methods: { liked: function() { this.active = !this.active; } } }); Button don't working and show: "<% active ? likedText : buttonText %>" What's a problem? Thanks in advance! -
Django: Use a QuerySet in Function
I want to make some tournament matches in a DetailView. But I can't figure out how to make a query of all registrations context['regs'] and use the queryset in my function create_matches(). class KategorieDetail(DetailView): model = Kategorie context_object_name = 'kategorie' def create_matches(regs): red_corner = [] blue_corner = [] matches = [] # Separate the regs into both corners i = 1 for reg in regs: if i%2 == 1: red_corner.append(reg) else: blue_corner.append(reg) i += 1 # Create Match-Ups while blue_corner: match = {'red': red_corner.pop(), 'blue': blue_corner.pop()} matches.append(match) return matches def get_context_data(self, **kwargs): context = super(KategorieDetail, self).get_context_data(**kwargs) kid = context['kategorie'].id context['regs'] = Registrierung.objects.filter(kategorie=context['kategorie'].id) context['regs_count'] = context['regs'].count() context['matches'] = create_matches(context['regs'].values(), kid) return context In my HTML-View I can't display the matches. If I say {{matches}}, I get: HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/events/" I also don't get why I have to give the Kategorie_ID to the create_matches(regs) function. -
How to configure nginx+uwsgi+django with venv?
Trying to deploy a django website. Followed DigitalOcean intruction but instead of virtualenvwrapper I want to use venv for python 3.6. The problem that it doesn't want to see my venv, I tried in mysite.ini file to write in this ways: [uwsgi] project = myproject uid = user base = /home/%(uid)/websites chdir = %(base)/%(project) home = %(base)/%(project)/venv venv = %(base)/%(project)/venv module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true and getting: Traceback (most recent call last): File "/home/petriichuk/websites/petriichuk/petriichuk/wsgi.py", line 20, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 1980, cores: 1) When I activate my venv and try: uwsgi --http :8000 -H /home/user/websites/myproject/venv --chdir /home/user/websites/myproject --wsgi-file /home/user/websites/myproject/myproject/wsgi.py it works, but if my venv is not activated it doesn't take -H path and shows the error above