Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: lxml-4.5.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform
I am trying to install some packages required for weasyprint that is Pango and Cairo for my Django project. I have downloaded both packages to the file system. The file names are as follows: 1.lxml-4.5.0-cp36-cp36m-win_amd64.whl 2.pycairo-1.19.1-cp38-cp38-win_amd64.whl 3.pygtk-2.22.0-cp27-none-win_amd64.whl I am on 64 bit windows 10 system,I have a 32-bit python 3.7.3 installed on the machine.I am also working on Django 3.0.But whenever I try installing the packages using pip i.e pip install lxml-4.5.0-cp36-cp36m-win_amd64.whl, it throws the errors below. ERROR: lxml-4.5.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. ERROR: pycairo-1.19.1-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. -
Django: How to let user decide with checkboxes what categories of images they want to see?
I want to create some kind of gallery. My Image model has two choice-fields: cat1 = models.CharField(max_length=250, choices=(('g1',"Game1"), ("g2", "Game2"), ("g3", "Game3"), ("g4", "Game4"))) cat2 = models.CharField(max_length=250, choices=(('type1',"Drawn"), ("type2", "Computer graphic"), ("type3", "Pixelart"))) I want to let the user click on checkboxes "Game1, Pixelart", then on "Show!" button and the whole page then reloads to show images having both of those categories (so only Pixelarts from Game1). How should the view and template look like? -
How to use extends tag in django templates?
Hi I am stuck at extending template in django. I have a base file called auth_layout.html which contains: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Question Time</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Lora&display=swap" rel="stylesheet"> {% block style %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> </html> and there is another template called login.html which contains: {% extends 'auth_layout.html' %} {% load crispy_forms_tags %} {% block auth %} <h1> Question Time </h1> <p class ="lead text-muted"> Share Your Knowledge! </p> <div class="login-form-container"> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-sm btn-outline-primary">Login</button> </form> </div> {% endblock %} My project directory is something like this: QuestionTime QuestionTime templates users (app) manage.py and here is my template settings in settings.py:- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] The problem is that it is not extending my auth_layout.html file. Whenever i hit the login endpoint it shows an empty page. On commenting the extend statement, html content of login.html is shown. How can I fix this? -
How to implement WishList on Django
I'm trying to implement a couple of this on my website but don't know how to go about it. First of all i'm trying to add a wishlist for my product and ratings, if you know how to implement any of this could you please help me thank you. class Category(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) products = models.ManyToManyField('Product') image = models.ImageField(upload_to='imagess/', blank=True) def get_products(self): return Product.objects.filter(category=self) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category', args=self.slug) class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='images/', blank=True) image2 = models.ImageField(upload_to='images/', blank=True) image3 = models.ImageField(upload_to='images/', blank=True) image4 = models.ImageField(upload_to='images/', blank=True) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('single',args=[self.id, self.slug]) -
How to see what an object contains in Django
I am working in Django with PyCharm and I have a simple model that look like so: class Test(models.Model): description = models.CharField(max_length=255, null=True, blank=True, verbose_name=_("description")) start_date = models.DateTimeField(null=True, blank=True, verbose_name=_("start date")) end_date = models.DateTimeField(null=True, blank=True, verbose_name=_("end date")) And a simple form that look like so: import datetime from django import forms from . import models from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = models.Test def clean(self): cleaned_data = super().clean() if cleaned_data.get("start_date"): starting_date = cleaned_data["start_date"] print(starting_date) t = datetime.date.today() print(t) g = datetime.datetime.combine(t, datetime.time.min) print(g) if starting_date < g: raise forms.ValidationError(mark_safe(_("The starting date is before today's date."))) When I am trying to debug my code, I would like to see the content of different objects (cleaned_data, t, g ect) so I can understand why my code is not working. How do I do that ? -
How to solve a string to data conversion problem on a Django template
I have a string to data conversion problem on a Django template. I'm trying to take a string (of a date) and calculate the days since that date; so it says something like "1 month, 2 weeks (since all time high date)". The string to date conversion is working fine, the problem is on the Django template. The template currently shows only the last date from the json data request for each item in returned in the for loop. Obviously I need the date for each specific record converted and displayed. I've formatted the string from the json data request into date object. Currently only the last item in the list is being sent as the days_since_ath_formatted variable. Here's the Django view def: coin_list_url = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page={per_page_limit}&page=1&sparkline=false" request_coin_list = requests.get(coin_list_url) results_coin_list = request_coin_list.json() crypto_data_geckco = [] #string to date conversion def to_string(time): return time.strftime('%Y %M %d') def from_string(date, formatting): dt = datetime.datetime.strptime(date, formatting) return dt #for loop for currency_gecko in results_coin_list: days_since_ath = currency_gecko['ath_date'] days_since_ath_formatted = from_string(days_since_ath[:-14], "%Y-%m-%d") print('days since ath formatted', days_since_ath_formatted) crypto_data_geckco.append(currency_gecko) print("crypto_data_geckco", crypto_data_geckco) return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco, 'days_since_ath_formatted': days_since_ath_formatted} ) and then on the Django template: {% for currency in crypto_data_geckco %} All-Time Percentage: {{ currency.ath_change_percentage|intword … -
How to make condition inside mutation to restrict mutation if hero dupliacates in the same draft?
I`m not able to understand how to make statement so if I make draft 1 and I have two heroes with same ID (or name, for example 'Spectre') it will restrict mutation with an error: 'You can have same hero in the draft' Bolded text inside user_draft.py is unused because I dont know were or how to make condition. Inside mutate before I save it or? user_draft.py import graphene from graphene_django import DjangoObjectType from user_draft.models import UserDrafts from users.schema import UserType from heroes.schema import HeroType from users.models import User from heroes.models import Hero class UserDraftType(DjangoObjectType): class Meta: model = UserDrafts class Query(graphene.AbstractType): all_drafts = graphene.Field(lambda: graphene.List(UserDraftType)) def resolve_all_drafts(self, info): return UserDrafts.objects.all() class CreateDraft(graphene.Mutation): message = graphene.String() user = graphene.Field(UserType) hero = graphene.Field(HeroType) class Arguments: draft = graphene.Int() hero = graphene.ID() user = graphene.ID() @staticmethod def mutate(self, info, draft, user, hero): hero_id = Hero.objects.get(id=hero) user_id = User.objects.get(id=user) **error_message = 'You cant duplicate heroes' draft_error = 'You can only pick 1, 2 or 3.'** draft_data = UserDrafts.objects.create( draft=draft, hero=hero_id, user=user_id, ) draft_data.save() return CreateDraft( message='You created ur hero pool successfully' ) class Mutation(graphene.ObjectType): create_draft = CreateDraft.Field() So inside my CreateDraft mutation I want to be able to restrict user not to have … -
Heroku Django error: SSL certificate has expired
How do I make my free Heroku site work? I did not change it from the time it was working to when it stopped working. site code When I opened my site, I got an "Application Error" page. I followed its instructions. I ran the Heroku CLI command "heroku logs --tail" and got an error. I then ran "heroku logs --tail --app moresomervillehappinessapp". Here are the last logs: 2020-04-06T20:49:47.204222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/urllib/request.py", line 1320, in do_open 2020-04-06T20:49:47.204222+00:00 app[web.1]: raise URLError(err) 2020-04-06T20:49:47.204228+00:00 app[web.1]: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)> According to Heroku, I can use the "*.herokuapp.com" certificate for SSL. Should I try to get rid of the SSL certificate? I care a little bit about SEO, but not the security of user data. Software I used: Django 3.0.2, Python 3.8 -
How to add custom query / queryset to Django Admin?
I'm building a Django project and have a model called Animal. Something like: class Animal(models.Model): type = models.CharField() In the django admin interface I can easily see all animals which is awesome. However I would like to add 2 additional views to the admin so that I can see all animals of a certain type: For example if my Admin view could look like this: Animals -> Shows all animals (default) Animals (type == dog) -> Shows only dogs Animals (type == cat) -> Shows only cats Any advice or best practices on how to do this? Thanks. -
Can't log into heroku using bash command line for Django
I'm trying to deploy my first django app on heroku but i am not being able to do so. I have done pip install django-heroku and also done a pip freeze to requirements.txt . I also installed guincorn and psycopg2 according to a tutorial. All the installations are in a virtual env. I am currently using bash command line from windows (on vscode). When i do heroku login it shows bash: heroku: command not found. What should I do? -
How to escape the required login in Django?
A Django web application usually has login required, however there is a url or view that does not need to have a login_required. How to make it work? -
Django: How to create an user and set a related field
I've extended the user data using another model (OneToOne relation) and when a user is created, its profile is also created. I'd like to update the field mailing when the user is created without a query. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mailing = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py def register(request): ... if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.mailing = profile_form.cleaned_data['mailing'] user.save() #The user is created but mailing is not set return redirect('login') profile_backend.py class ProfileBackend(ModelBackend): def get_user(self, user_id): UserModel = get_user_model() try: return UserModel._default_manager.select_related('profile').get(pk=user_id) except UserModel.DoesNotExist: return None I can set the variable taking the user as object but this imply using an extra function. -
UpdateView using foreignkey in Django
Is there a way that instead of pk i will select the model data by foreign key in UpdateView? It is no doubt it works on the id of the data but what if i will select the data object in the model using foreign key condition? How would i do that? Here is my UpdateView class: class SettingsProfileView(UpdateView): model = UserInfoModel template_name = 'site/views/settingsprofile.html' form_class = UserInfoForm I try to put: def getquery_set(self): return self.model.objects.filter(users_id = self.kwargs['pk']) but still its refering to get the data by primary key. -
Does using post_save and post_delete methods slow down over all Django project speed?
I want to keep track of number of database entries. I do not want to use (in my case) Book.objects.all().count(). I know it works quite fast, but I do not think it is the good way. I have implemented Tracker class and I will be working with that singleton type of class if the numbers are needed. Question: Does using post_save and post_delete slow down my Django project? my source code models.py from django.db.models.signals import post_save, post_delete from django.db import models class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class Book(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tracker(Singleton): def __init__(self): self.__count = self.__get_numbers() def __get_numbers(self): print("I am getting records") return Book.objects.all().count() @property def count(self): return self.__count def update_record_count(sender, **kwargs): tracker = Tracker() print("Database entries: {}".format(tracker.count)) post_save.connect(update_record_count, sender=Book) post_delete.connect(update_record_count, sender=Book) What I have written above is truely imaginative, just for learning purposes -
Filtering searches with Django filters, query gets deleted
I've been coding an ecommerce app with Django and I'm in the proces of creating a filtering system for the searches. This is the listview that displays the items: class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context This is the filter: import django_filters from .models import publicaciones class PubFilters(django_filters.FilterSet): o = django_filters.OrderingFilter( fields=( ('Fecha', 'Más nuevo'), ), ) class Meta: model = publicaciones fields = ['Precio', 'Categoría'] The problem is that if I search something and then try to apply a filter, the query that I searched is deleted, and displayed by "None". Any help will be appreciated EDIT: This is the template: {% extends 'store/store.html' %} {% load static %} {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'css/style_search.css' %}"> {% block content %} <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button class="btn btn-primary" type="submit">Buscar</button> </form> </div> <h3>{% if count == 0 %} Ningún resultado para {% elif count == … -
Django GraphQL django-graphql-jwt token not working in self-signed ssl server
I'm using django-graphql-jwt for GraphQL API authentication. Deployed to ubuntu server with self-signed ssl. Here is the mutation for authentication mutation { tokenAuth(email: "example@test.com", password: "password") { token } } So I used this token for authorization. Request Header: Authorization: JWT <token> Request Body: query { me { username firstName lastName email phone } } Result: { "errors": [ { "message": "'AnonymousUser' object has no attribute 'email_verified_at'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "me" ] } ], "data": { "me": null } } This is correctly working in none-secure server(http). How can I fix this issue? Regards. -
Python Django: Customize Admin Startpage as analytical Dashboard
I am currently developing a mobile app using Ionic and I am using Django Admin Interface as sort of Backend for adding and editing the content of my mobile app through a MySQL Database. I currently wish to create a custom analytical dashboard for tracking the usage of the users of my mobile app in the startpage of the Django Admin. While there are some analytical packages for tracking the usage in Django, they only function for web applications. In my case I need to gather and display aggregate data from my database (Django models & not Django models) as well for other APIs. Is there a way how can I fetch data in form of SQL queries and display them in my dashboard using Python (Django)? And how can I extend the starting page of Django Admin to a full analytical dashboard with the named functionalities? I am currently struggling with this as I am new to Django. Any help is much appreciated! -
Django. IntegrityError: NOT NULL constraint failed: MyApp_song.albums_id
For starters, I just started learning Django. I'm trying to add a new song object to my album via the form. But I don't want to manually select the album (my foreign key) that I want to add a new song to. Instead, I want the value of my foreign key to be set depending on the album I'm adding a new song from. How can i do that in Django? I tried to do it like this: views.py class SongCreate(CreateView): template_name = 'music/album_form.html' # fields = ['albums', 'file_type', 'song_title', 'audiotrack', 'is_favorite'] model = Song fields = ['file_type', 'song_title', 'audiotrack', 'is_favorite'] def form_valid(self, form): album = get_object_or_404(Album, pk=self.kwargs['pk']) form.instance.album = album return super(SongCreate, self).form_valid(form) urls.py path('music/album/<int:pk>/add', views.SongCreate.as_view(), name='song-add'), models.py class Song(models.Model): albums = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) audiotrack = models.FileField(upload_to='media/') is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('param', kwargs={'pk': self.albums.id}) def __str__(self): return self.song_title Link to add a new album <a href="{% url 'song-add' album.id %}">Add album</a> But for some reason it doesn't work, although I thought it should help. So i'm getting this error. Maybe you know what's the problem? Thanks, any help will be appreciated! -
How do I upgrade an old Django Google App Engine application to a Second Generation Cloud SQL Instance?
I have a Django application that I wrote 5 years ago, which has been running successfully on Google App Engine - until last month when Google upgraded to Second Generation Cloud SQL. Currently, I have a settings.py file, which includes a database definition which looks like this: DATABASES = { 'default': { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'my-project-name:my-db-instance', 'NAME': 'my-db-name', }, Google's upgrade guide, tells me that the connection name needs to change from 'my-project-name:my-db-instance' to 'my-project-name:my-region:my-db-instance'. That's simple enough. Changing this leads me to get the error InternalError at /login/ (0, u'Not authorized to access instance: my-project-name:my-region:my-db-instance') According to this question, I need to add the prefix '/cloudsql/' to my instance name. So, I changed this (and the ENGINE specification) to give: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'INSTANCE': '/cloudsql/my-project-name:my-region:my-db-instance', 'NAME': 'my-db-name', 'USER' : 'root', 'PASSWORD': '******************', }, I uploaded the modified file to Google (using gcloud app deploy). This time I get a completely different error screen, showing: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. When I look in the Logs, I see: ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb It was pointed out … -
check if the directory name is year python [duplicate]
how can I check if the directory name is a year using python ? If I have directories called 2018, 2019, 2020, test1, test2, I want to get only directories which name is a year . in this case I want directories with name : 2018, 2019, 2020 -
Filter queryset inside a form
I have one app that holds a list of work orders, and another app that holds list of parts. class Order(models.Model): parts = models.ManyToManyField(Part, blank=True) # Assosiated parts class Part(models.Model): partnum = models.CharField(max_length=20) # Part number mwos = models.ManyToManyField('mtn.Order', blank=True) # Assosiated work orders Now i want to add a button to my DetailView for order which will open a list of parts, which i will be able to add to my order. At the moment i have a created an UpdateView for my order class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm ... and a form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "Parts", } def FilterList(request): qs = Part.objects.all() search_part_query = request.GET.get('search_part') if is_valid_queryparam(search_part_query): qs = qs.filter(Q(partnum__icontains=search_part_query) | Q(descr__icontains=search_part_query) ).distinct() return qs def __init__(self, *args, **kwargs): super(AddPartForm, self).__init__(*args, **kwargs) self.fields["parts"].widget = CheckboxSelectMultiple() self.fields["parts"].queryset = self.FilterList() for this template {% block content %} <form method="GET" action="."> <div class="form-row justify-content-start"> <div class="form-group col-md align-self-center"> <div class="input-group"> <input class="form-conrol py-2 border-right-0 border" type="search" placeholder="Find part" name="search_part"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <button type="submit" class="btn btn-primary btn-sm btn-block">Search</button> </form> <form action="{% url 'mtn:add_part' order.id %}" … -
Context in Django HttpResponse
I happen to pass by Django documentation for TemplateResponse. (My question is for HttpResponse) Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the template and context that was provided by the view to compute the response. Here it says that response object which we get from self.client.get() which is an object of HttpResponse, does not retain the context provided by view. But when I did dir(response) I could find context there. Kindly explain me the actual meaning of documentation. -
Does using pre_save or post_save slow down overall Django project?
I need to keep track of Database records count. I was wondering if using post_save or pre_save methods slow down overall Django project's performance. Question: Does using post_save or pre_save signals slow down overall Django project's performance? -
connecting button to modal with bootstrap
I need some help connecting a button which pops up a modal to submit form. this is my html before the modal (works fine and another page is rendered after button is clicked) <div class="container my-container"> <h3> Let's get started </h3> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button type="submit"> Submit</button> </form> </div> </div> I have added the modal but I now have a couple of issues <div class="container my-container"> <div class="row my-row"> <h3> Let's get started </h3> </div> <div class="modal fade" id="demo123"> <div class="modal-dialog"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal"> <span> &times; </span> </button> <div class="modal-header"> <h2 class="modal-title"> Confirm upload </h2> </div> <div class="modal-body"> <p>this is the file name</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Confirm </button> </div> </div> </div> </div> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns titled</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button class="btn btn-primary" data-toggle="modal" data-target="#demo123"> Submit </button> </form> </div> </div> First issue I have is the "submit" button automatically makes the upload(renders to another page). How … -
Django WAMP (Apache) mod_wsgi on Windows
Im new to Django and web development. I have completed a project in development environment and now we need to deploy it in production. I have been trying to go through the deployment process using wamp on a windows virtual machine. The details are as under: OS: Windows 10 Python: 3.7.6 Webserver: Wamp 3.2 with Apache 2.4.41 mod_wsgi ver 4.7.1 (this was downloaded pre-compiled from here Im using pycharm for the development and the default python interpreter path is of system i.e. C:\Users\User\AppData\Local\Programs\Python\Python37 which includes the installed/ extracted mod_wsgi packages in site-packages. The 'Django' package is installed however within venv at C:\Users\User\TryProject\venv\Lib\site-packages I configured my files as folows: httpd-vhosts.conf: <VirtualHost *:8080> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/User/TryProject/TryProject.error.log" CustomLog "C:/Users/User/TryProject/TryProject.access.log" combined #WSGIDaemonProcess TryProject python-home=C:/Users/User/TryProject/venv/Lib/site-packages #python-path=C:/Users/User/TryProject/venv/Lib/site-packages #venv/Lib/site-packages" #WSGIProcessGroup TryProject WSGIScriptAlias /mysite "C:/Users/User/TryProject/TryProject/wsgi.py" #process-group=TryProject #application-group=%{GLOBAL} WSGIApplicationGroup %{GLOBAL} <Directory "C:/Users/User/TryProject/TryProject"> <Files wsgi.py> Require all granted </Files> </Directory> httpd.conf: ... LoadFile "c:/users/user/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/user/appdata/local/programs/python/python37" ... and wsgi.py import sys from django.core.wsgi import get_wsgi_application #site.addsitedir("C:/Users/User/AppData/Local/Programs/Python/Python37/Lib/site-packages") site.addsitedir("C:/Users/User/TryProject/venv/Lib/site-packages") # Add the app's directory to the PYTHONPATH #sys.path.append('C:/Users/User/TryProject') sys.path.append('C:/Users/User/TryProject/TryProject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TryProject.settings') application = get_wsgi_application() while the apache error log file shows this group of error on every request: [Tue Apr 07 20:18:44.672498 2020] [wsgi:error] [pid 12456:tid …