Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get/display the author of a post from another app for notifications system
So I am making this notification system that is supposed to show/tell the user when someone else has liked or commented on their post. However, instead of telling the user when someone liked your post it instead records your personal activity and shows all of the likes and comments you yourself have made. I know why this is happening (after all I set it up), I just don't know how to reverse it so the post author get's notified instead of the current user. I think I have all the info I need, I just don't know how to go into the other apps model, get the extra bit of info I don't have and then display the notifications for/to the post's author. Please help. Also, please ignore the sloppy imports, I know that needs to be cleaned up. Notify app views: from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from feed.models import UserPost,UserComment from users.models import UserProfile from notify.models import UserNotification from feed.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView, RedirectView,) User = get_user_model() … -
django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name
Django version 1.11.5, views.py class SignupPage(CreateView): form_class = forms.UserSignupForm success_url = reverse_lazy('login') template_name = 'signup.html' website/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView,LogoutView from . import views app_name = 'website' urlpatterns = [ url(r'^login/', auth_views.LoginView.as_view(template_name='signin_2_w.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^signup/', views.SignupPage.as_view(), name='sign_up'), forms.py class UserSignupForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = "Display Name" self.fields['email'].label = "Email Address" self.fields['password1'].label = "Password" self.fields['password2'].label = "Confirm Password" proj/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomePage.as_view(),name='home'), url(r'^website/',include('website.urls',namespace='website')), url(r'^website/',include('django.contrib.auth.urls')), url(r'^website/',views.StreamyePage.as_view(),name='streamye'), url(r'^thanks/$',views.ThanksPage.as_view(),name='thanks'), url(r'^congrats/$',views.CongratsPage.as_view(),name='congrats'), url(r'^aboutus/$',views.AboutusPage.as_view(),name='about_us'), HTML <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> <li><a href="{% url 'sign_up' %}">Signup</a></li> {% endif %} </ul> In the above code, the signup page is throwing me a error -- "django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name." Please someone help me out where im wrong! Thanks in advance! -
django mysql-client or mysql-db error
I am facing these errors when I am running the python manage.py runserver Also i have tried: 1.pip install MySQL-python 2.pip install mysql-python but nothing worked.I need help Errors i am getting -
Success message not displayed in Django ClassBasedView
I am trying to display success message after saving form. I am using message framework for this settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ '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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_PATH], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py class VolunteerCreateView(SuccessMessageMixin, CreateView): model = Volunteer form_class = VolunteerForm template_name = 'volunteer.html' success_message = 'Thank you!' success_url = reverse_lazy('volunteer') volunteer.html {% if messages %} <div class="alert center block" role="alert"> <ul class="messages"> {% for message in messages %} <li class="text-center"{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}..... But the message is not displayed. I can see the message json on request header in redirected url but is not displayed. Part of request header Cookie:olfsk=olfsk1757071755791586; hblid=HecPjm2lDQ2xTzgn3m39N0J00JEB6o1A; sessionid=z8zh4t13mw655mf3yn1vfnow8y58zxt9; csrftoken=GZxsdPZmBsefPU0nv7ZEfEaxsnPCMjIehpiFihY3GtTrhFnuFc5c3NXplD35Qslw; ext_name=jaehkpjddfdgiiefcnhahapilbejohhj; messages="ab8f5c6976dd0939d4f1b867ca564577ba9cc0d7$[[\"__json_message\"\0540\05425\054\"Thank you!\"]]" What could be the reason that message is not displayed. Is there anything I am missing. -
How to implement an activity feed/notifications system?
I'm using redis and know how to make an activity feed but like in Instagram if let say 20 users liked your feed, it just shows JOHN Mike and 18 others liked your picture I have been able to show all 20 but don't know how to implement this kinda feature I don't need the code I just need to understand the logic behind this Thanks -
Django makemigrations works but migrate doesn't
I've an app which I've just putting onto a VPS to test. It works fine on my PC (Ubuntu) using the manage.py runserver When I try and put it on the server I get the following error/traceback: Applying listing_cms_integration.0002_auto_20171017_1634...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 237, in apply_migration state = migration.apply(state, schema_editor) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 204, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 495, in alter_field old_db_params, new_db_params, strict) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 255, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 186, in _remake_table self.alter_db_table(model, temp_model._meta.db_table, model._meta.db_table) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 372, in alter_db_table "new_table": self.quote_name(new_db_table), File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 112, in execute cursor.execute(sql, params) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", … -
Django SMTP [Errno 111] Connection refused
I am trying to send email from a web app using django and a sendgrid SMTP server. It works fine locally but when I try to use it on pythonanywhere I get error: [Errno 111] Connection refused The code from the relevant view is def contact(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): mail = form.cleaned_data send_mail( 'Automated Enquiry', 'A user is interested in part ' + mail['part'] + '.Their message: ' + mail['msg'], mail['email'], ['myemail@gmail.com'], fail_silently = False, ) return render(request, 'manager/error.html', {'msg': "Thanks, we will be in touch as soon as possible"}) else: part = request.GET.get('part', '') form = EmailForm() return render(request, 'manager/contact.html', {'form': form, 'part':part}) And in my setting.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'myuser' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True It didn't work from the console either. Any help would be greatly appreciated. -
Django: get related objects of related objects and pass to template
In a Django app I have three models: class A(models.Model): aId = models.AutoField(primary_key=True) class B(models.Model): bId = models.AutoField(primary_key=True) aId = models.ForeignKey(A) class C(models.Model): cId = models.AutoField(primary_key=True) bId = models.ForeignKey(B) There is a on-to-many relation between A and B, as there is between B and C. And there is a View class with context_data. In the template I need to show and filter Bs, with their Cs. How can I pass All Bs related to an A and All Cs related to those Bs to my template (context)? I tried to get Bs and Cs separately in two arrays, but it seems not to be a good idea because I can not categorize Cs by Bs. -
How to easily add Django urls?
I am working on a website, very basic, just HTML and CSS. Its all static and I'm needing to add more urls. I have read the Django documentation and it isnt quite clicking with me. What I have is my home page and I need to be able to click the link on my navbar and be taken to the next page. I'm just not sure how to add another URL in django. Thank you in advance! Sorry if I missed anything. It's my first post -
Editable but not changeable foreign keys in django admin
In Django admin, you can mark fields as readonly, including Foreign Key fields. A regular ForeignKey field gets both a pencil to let you edit the current object being pointed to, and a dropdown/plus to let you point to another object. I'd really like a ForeignKey field that has the pencil but not the dropdown/plus. That is, I'm fine with the admin allowing editing of the thing I'm pointing to, but not changing what I'm pointing to. Is there an easy way to do this? -
django: generate external .html file with external .css files
I'm relatively new to django and am having an issue including static css files (like bootstrap, font-awesome) into a html file that I'm writing as an external output file (which I then need to open with MS Word - that's the endgame). The html that I render to the browser is fine, but when I write it to a file for a download link that I'm implementing, it's not "including" the static files, just the links. The download is also working for the .html file generated. Is there any way to flatten these styles as they are rendered with the django dev server so Word will recognize the styles? I've tried using the cdn and just including my local styles in the header, but the html generated is using the link rel="stylesheet", so they are not being "pulled into" the generated html when downloaded as a file. Thanks for any pointers/assistance! Really appreciated! -
Getting 404 not found when working with docker container nginx uwsgi django
I'm having 3 docker containers. One container has Django with uwsgi and nginx. I configure inside with 80 port exposed. And later run with 8800:80 mapping in my localhost. A second container has another Django project with uwsgi and nginx, similar configuration and run with 8801:80 mapping in my localhost. So right now I can access different Django apps from the container with different ports. localhost:8800 -> app1 localhost:8801 -> app2 now I create a third container with nginx, which aims to do the reverse proxy. So I third container has only nginx configuration. Which has something like this: error_log /var/log/nginx/error.log; events { worker_connections 1024; } http { sendfile on; gzip on; gzip_http_version 1.0; gzip_proxied any; gzip_min_length 500; gzip_disable "MSIE [1-6]\."; gzip_types text/plain text/xml text/css text/comma-separated-values text/javascript application/x-javascript application/atom+xml; upstream app1{ server my_machine_ip:8800; } upstream app2{ server my_machine_ip:8801; } access_log /var/log/nginx/access.log; server { listen 0.0.0.0:80; location /firstapp/ { proxy_pass http://app1/; proxy_set_header Host $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-Host $server_name; } location /anotherapp/ { proxy_pass http://app2/; proxy_set_header Host $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-Host $server_name; } } } Again the container with 80 port expose and I run with port 8888:80 mappings. Then I have … -
uWSGI uses Python 2.7 instead of 3.5 which causes consequential errors
I'm trying to create a Django app with WebSockets on a Raspberry Pi 2 using django-websocket-redis pip package. /manage.py runserver doesn't seem to work (got 404 calling /ws/ although it's set by WEBSOCKET_URL = '/ws/' in settings.py), I wanna try a standalone uWSGI server like described here in the official docs. When I run uwsig, I got strange errors. I think this is caused by a wrong python version. The output of uwsig show me that Python 2.7 is used: Python version: 2.7.13 (default, Jan 19 2017, 14:48:08) [GCC 6.3.0 20170124] But I need Python 3 (exactly 3.5) for my project. I changed the default python environment, so that the python comamnd points to python 3.5 instead of 2.7. Additionally, I passed the version using --plugin switch like this: uwsgi --http :9090 --plugin=python35 --wsgi-file wsgi.py I also used pip3for all pip packages to make sure that no 2.x packages were used. This seems having no effect, cause my script breaks and uwsgi show me that Python 2.7 is used... -
Update object value from function based view
I have a django project that has a form with two buttons in one of my templates. These buttons either accept or decline an "Offer", which is one of my models. I pass a POST request from the template to the view where i have two functions. How do i make these approve and decline buttons update the value "approved_by_x" in my model? The Template: <form method="post" class="login-container" action="{% url 'accept_booking' %}"> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Accept" name="Accept"/> <input type="hidden" name="offer" value="{{ offer }}" /> </form> <form method="post" class="login-container" action="{% url 'decline_booking' %}"> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Decline" name="Decline" /> <input type="hidden" name="offer" value="{{ offer }}" /> </form> The View: def accept_booking(pr): offer = pr.POST.get("offer") print(offer) def decline_booking(pr): offer = pr.POST.get("offer") print(offer The Model: class BookingOffer(models.Model): artist = models.ForeignKey(Artist, null=True, related_name='artist') artist_manager = models.ForeignKey(User, default=1, limit_choices_to= {'groups__name': 'artist_manager'}) comment = models.TextField(max_length=120, blank=True) time_slot = models.ForeignKey('TimeSlot', null=True, blank=True) price = models.IntegerField(null=True, blank=True) tech_needs = models.TextField(blank=True) approved_by_bm = models.BooleanField(default=False) accepted_by_am = models.BooleanField(default=False) -
Django slow to delete rows based on Foreign Key when rows are not created through ORM
I'm encountering a situation where Django is slow to delete rows from a table when they are related to another table via a Foreign Key (FK), but were not created via the Django ORM. I have the following Django model for Record: class Record(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) index = models.IntegerField(null=True, default=None) record_id = models.CharField(max_length=1024, null=True, default=None) document = models.TextField(null=True, default=None) error = models.TextField(null=True, default=None) This is related to the model Job via the job column (job_id in MySQL after Django migration creation). However, Record rows are not written via Django, but instead from Apache Spark via jdbc.write(). A typical example might be 1 Job with 45k related Record rows. The problem is, while deleting a Job instance via the Django ORM via job.delete() does delete the associated Record rows, it is quite slow, 5-7 seconds for 1 Job with 45k associated Record rows, 20-30 seconds for 160k, and so forth. My understanding is that Django emulates ON DELETE CASCADE to accommodate different DB backends, which makes sense. But I'm wondering: if the Record rows are not created via the Django ORM, does that bypass some kind of internal Django indexing that would otherwise make this cascading deletion of associated … -
Django & Postgresql annotate datetime field to localtime
I'm using Django 1.11 with Postgresql 9.6 and JQuery DataTables (using django-datatables to provide AJax datasource from Djang model. Model example: class MyModel(models.Model): start = models.DateTimeField() end = = models.DateTimeField() Postgresql stores the datetimes in UTC with timezone info, which is fine. I can override the DataTables render column to render the datetime correctly in the DataTables view: if column == "start": return timezone.localtime(row.start).strftime(STRFTIME_DATETIME_FORMAT) The problems when trying to provide the search filter query for partial dates. If I add an annotation to add date_str to search on: def filter_queryset(self, qs): search = self.request.GET.get(u'search[value]', None) if search: sql_datetime_format = getattr(settings, "SQL_DATETIME_FORMAT", "DD/MM/YYYY HH24:MI") qs = qs.annotate( start_str=Func(F('start'), Value(sql_datetime_format), function='to_char'), end_str=Func(F('end'), Value(sql_datetime_format), function='to_char'), ) q_objects = Q() q_objects |= Q(start_str__icontains=search) q_objects |= Q(end_str__icontains=search) qs = qs.filter(q_objects).distinct() return qs The start_str and end_str are converted to strings as UTC datetimes not local datetimes. So I UK date in summer displays correctly as 01/06/2017 00:00, but to search for it you have to enter: 31/05/2017 23:00 I can't seem to find away to get start_str and end_str to local time instead of UTC. -
how to calculate field in django admin model
i have a model that i have added to my django admin panel from django.db import models from django.contrib import admin class Employee(models.Model): fee = models.IntegerField(null=False) vat = models.IntegerField(null=False) and have added this my admin panel admin.site.register(Employee, EmployeeAdmin) readonly_fields('vat',) so while adding a new employee, the admin inputs the fee amount, id like vat to be calculated and shown as a direct result of entering the vat. how can create this calculation on the fly as the admin is entering the fee -
Django - Remove object from database after day
I want to remove object after one day. Here is part of my code: data = models.DateField(null=True) So for example value of data field is 10.10.2017 And I want to remove it in 11.10.2017 Thanks for help ! -
Passing User object in celery using django
I'm currently editing the save method in one of my models, so that I can save who changed an object or created a new one. Currently, its working fine when its ran in the main thread, but the save method is also used in different tasks through Celery. And when the save method is ran in a task get user returns None. To get a user i'm currently using django-curser since this model is being used in different apps inside my Django project. Is there a way to send the current user to celery? I've been told to use a context manager or a wrapper but im not sure how. My save method is: def save(self, *args, **kwargs): from models import Log log_entry = Log() log_entry.object_id = self.id log_entry.object_repr = self user = CuserMiddleware.get_user() log_entry.user = user log_entry.content_type_id = ContentType.objects.get_for_model(self).id log_entry.save() Thanks. -
Djagno instagram/facebook/youtube Auto like/follow
Is it possible to make a system with php/python or django where i will put my account username and password and it will auto like/follow/subscriber from my account to whatever account i want of youtube/facebook/instagram -
How to stop python-social-auth and reverse a transaction during pipeline step?
I have a Django application which uses python-social-auth for authentication. I have this in my django settings: SOCIAL_AUTH_PIPELINE = ( ... 'my.app.my.custom.pipeline', ) How do I stop the whole user creation process in my custom pipeline? I have tried throwing various exceptions including ValueError and AuthException but the created users remain in the database. Doesn't throwing an exception reverse the database transaction? -
Display an unknown number of fields in Django template with field content of another record as the label
I have a Django app which I want to be able to use in multiple instances. One model (Listing) can have a variable number of fields (for the different instances) but will then always have exactly those extra fields for the instance. I want these extra fields added through admin so I've created models like this: class BespokeField (models.Model): name = models.CharField( max_length = 20, verbose_name = "Field Title" ) def __unicode__(self): return self.name class Listing (models.Model): name = models.CharField ( verbose_name = 'Listing', max_length = 30 ) slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True, blank=True, null=True ) class ListingBespokeField (models.Model): bespoke_field = models.ForeignKey(BespokeField) listing = models.ForeignKey(Listing) value = models.CharField ( max_length = 60 ) def __unicode__(self): return u'%s | %s' % (self.listing.name, self.bespoke_field.name) The theory is admin specifies the bespoke fields and these are then displayed to the user in forms. Within admin this is relatively simple as I can assume a modicum on intelligence from the users so my admin.py looks like: class ListingBespokeFieldInline(admin.TabularInline): model = ListingBespokeField extra = len(BespokeField.objects.all()) max_num = len(BespokeField.objects.all()) class ListingAdmin(admin.ModelAdmin): inlines = [ListingBespokeFieldInline] It does mean the admin user has to select one of each BespokeField from the dropdown … -
Open source video hosting patform with Django/Python
Can anyone redirect me to an open source web applications for posting and sharing videos using laptops webcam or smartphone cameras built with Django and Django Rest Framework ? -
Having an edit form and a detail view on the same page
I am currently trying to get an edit form working on the same page as a detail view in Django. I am currently trying out the way as recommended on the docs (i.e. using FormMixin). So, my view looks like this: class ProductiveMinutesDetail(FormMixin, DetailView): model = models.ProductiveMinutes pk_url_kwarg = 'productiveminutes_pk' form_class = forms.EditForm def get_success_url(self): return reverse_lazy('productiveminutes_list') def get_context_data(self, **kwargs): context = super(ProductiveMinutesDetail, self).get_context_data(**kwargs) context['form'] = forms.EditForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ProductiveMinutesDetail, self).form_valid(form) And my form looks like this: from django import forms from . import models class EditForm(forms.ModelForm): class Meta: model = models.ProductiveMinutes fields = ('name', 'description',) The model I am using is this: class Scenario(models.Model): name = models.CharField(max_length=200) class ProductiveMinutes(models.Model): scenario = models.OneToOneField(Scenario) name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=50, decimal_places=2) description = models.CharField(max_length=200) Using this I can get the form to render on the page but I know I am doing something wrong as the fields are empty when I would like them to be populated with the data that is already present. Another piece of complexity is that this form should not be editing the … -
Django Rollout to Apache2 server WSGI script load failure
This is the first time I have attempted to deploy a Django project. I am using Raspbian on a Pi3. The project works with the built in Django test server. The project root (where the manage.py file is) is: /datadisk/powermon/power The virtualenv is found at: /datadisk/powermon/pja The Django settings.py file is at: /datadisk/powermon/power/power I have added the following lines to /etc/apache2/sites-enabled/000-default.conf WSGIDaemonProcess power python-home=/datadisk/powermon/pja WSGIProcessGroup power WSGIScriptAlias /power /datadisk/powermon/power/power/wsgi.py WSGIApplicationGroup $(GLOBAL) <Directory /datadisk/powermon/power/power> <Files wsgi.py> require all granted </Files> </Directory> Apache restarted after the changes. The WSGI file is the default one that is created by Django. import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "power.settings") application = get_wsgi_application() When the browser attempts to access the website it gets a 500 Internal Server Error Apache reports the following in /var/log/apache2/error.log [Tue Oct 17 13:05:25.006487 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] mod_wsgi (pid=764): Target WSGI script '/datadisk/powermon/power/power/wsgi.py' cannot be loaded as Python module. [Tue Oct 17 13:05:25.007679 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] mod_wsgi (pid=764): Exception occurred processing WSGI script '/datadisk/powermon/power/power/wsgi.py'. [Tue Oct 17 13:05:25.008344 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] Traceback (most recent call last): [Tue Oct 17 13:05:25.009152 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] File "/datadisk/powermon/power/power/wsgi.py", line 24, in <module> …