Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can upload multiple images in django to different parts of an article on a site?
Hello I am trying to allow users to use images in articles how i can upload multiple images to different parts of an article on a site? And the best way to do it? It's not a problem for me to upload multiple images to one place, but I don't know how to do it in different places. Any help would be much appreciated! -
How can I set up the scss/sass file in django?
Im working on a personal project and im using django. In this project I like to use scss/sass style file, but I dont know how to install and set up in my Django project. Any help will be appreciated Thank u! -
How can I use django validation form with ajax/form validation?
I try to implement popup before form validation. popup contains data recovered form an ajax query. it works but it is not optimized as I have lost django validation form: if my form is not valid, no error messages are displayed for now, the only way I manage to "solve" this issue, is to use the same ajax query to test for form validation and display error message but it is the not the good way to do that How can I manage to use django validation form with ajax/form validation? JS var prevent_edit = false; var prevent = false; $("#form_unblind_edit").submit(function (event) { if (!prevent_edit) { event.preventDefault(); } }); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // affichage des informations sur le patient sélectionné pour la ré-allocation $("#unblind_edit").on("click", function (event) { var csrftoken = getCookie('csrftoken'); var patient = $("#id_pat").val(); var treatment = … -
Django Popup modal which displays form options/selection
I am building an application with has a few forms where people can select options from my database. I found the django-popup-view-field (image below). When you click on the search icon on the form, a modal opens where you can search all database options by name or letter, and select them as an entry in your form. The downside of this method is that the value you display in the form needs to be your primary key. I would rather use the default pk of django since it is much more reliable than for instance a name or other text field. Also, this solution requires quite some code and I have a feeling that this can be done more efficiently. In addition, having an id as pk makes CRUD way easier. Do any of you have suggestions or links to documentation where they try to achieve a similar thing? -
I'm trying to make a blog. I want to display all the post belongs to same date in detailed view on one page?
I'm trying to make a blog where I want to display all the blogs posted on same date on one page in detailed view. models.py class Article(models.Model): article_name= models.CharField(max_length=255) article_data=models.TextField() image=models.FileField(blank=True,null=True) video=models.FileField(blank=True,null=True) module_name=models.ForeignKey(Module, on_delete=models.CASCADE) paper_name=models.ForeignKey(Paper, on_delete=models.CASCADE) subject_name=models.ForeignKey(Subject, on_delete=models.CASCADE) topic_name=models.ForeignKey(Topic, on_delete=models.CASCADE) subtopic_name=models.ForeignKey(SubTopic, on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.article_name def get_absolute_url(self): #return reverse('dca_detail', args=(str(self.id))) return reverse('home') views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, DateDetailView, CreateView , UpdateView, DeleteView from dca.models import Article from dca.forms import ArticleForm from django.urls import reverse_lazy from django.http import request def home(request): return render(request, 'home.html') class dca_list(ListView): model = Article template_name= 'dca.html' ordering= ['id'] class dca_detail(DetailView): model= Article template_name= 'dca_detail.html' class add_dca(CreateView): model = Article form_class= ArticleForm template_name = 'add_articles.html' success_url= reverse_lazy('dca_list') # fields = '__all__' # fields = ('article_name','article_data',) class update_dca(UpdateView): model = Article template_name = 'update_dca.html' fields='__all__' success_url= reverse_lazy('dca_list') class delete_dca(DeleteView): model = Article template_name = 'delete_dca.html' success_url= reverse_lazy('dca_list') can someone help me what should be the code in my template? The schema of the output is as follows: POSTS on DD/MM/YYYY where clicking on the posts should display all the detailed views of posts posted on same date. -
What is the most efficient and scalable way to set up a React front-end for Django?
I'm building a web-project that will have a React based front-end backed by a Django REST back-end. I'm trying to figure out the most efficient way to set-up and connect both applications into one. Here is the set-up I have in mind, creating a frontend/ folder inside my Django project directory. ProjectDirectory/ manage.py core/ __init__.py settings.py urls.py asgi.py wsgi.py frontend/ src Is the standard and scalable way to implement Django and React together? -
Django - add context to request to be used by the view
Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself. For example, I have a middleware that looks at the request, and adds the user's permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it. This saves the need for multiple views (and multiple parts within the view) to query for this information. I'm wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that? -
Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
https://www.youtube.com/watch?v=AlJ8cGbk8ps i followed this video and when i do this command django-admin makemessages -l ar it gives me this error CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. and i have installed pip install python-gettext any aswers? Thanks in advance -
Asynchronous execution of a function inside Django
This is how the views.py file would look like for example. The user will make some post request and trigger a CPU intensive execution which will take a long time to finish. I want to return a response to the user with some message denoting that execution started and maybe some unique execution id. The point being the user does not need to wait for the execution to end. So I am starting the time-consuming function in a separate thread, and whenever it finishes execution, it will make entry to some remote database. Is this a good approach to achieve the same or are there any potential vulnerabilities with this approach? Note: Although the function takes a long time to finish, it is essentially a small service, with probably one instance needed to run in production. import threading from rest_framework.views import APIView from rest_framework.response import Response def async_function(x): time.sleep(10) print(f'[*] Task {x} executed...') class MainFunctionView(APIView): def get(self, request): return Response({'val': 1}) def post(self, request): #req = ExecutionRequest(request) t1 = threading.Thread(target=async_function, args=(request.data.get('val'),)) t1.start() return Response('exection started') Thanks in advance. -
Forbidden HTTP 403 DRF + ReactJS request.session
I am working on a Quiz Application using DjangoRestFramework and ReactJS. My App is comprised of two apps, api and frontend. In my api app, I have multiple API views for many different things. One of my API Views is called JoinQuiz. When I call it on my frontend, I get this error in the console: Forbidden: /api/join-quiz [16/Dec/2020] "POST /api/join-quiz HTTP/1.1" 403 58 I don't think my problem is due to a CSRF error because my other API views are working perfectly fine. I may be wrong on this point. [16/Dec/2020] "GET /api/get-question?id=3 HTTP/1.1" 200 10009 [17/Dec/2020 01:15:47] "POST /api/create-quiz HTTP/1.1" 201 11959 I suspect that my request.session may be the issue because when I go directly to /api/join-quiz and make a POST request with my code, nothing goes wrong and I have a successful post. Files Views.py class QuizView(generics.ListAPIView): queryset = Quiz.objects.all() serializer_class = QuizSerializer class GetQuiz(APIView): """ Searches for a quiz given its code and returns the Quiz with is_host info""" serializer_class = QuizSerializer lookup_url_kwarg = 'code' def get(self, request, format=None): # This is an HTTP GET request code = request.GET.get(self.lookup_url_kwarg) if code != None: # Check if code is not equal to None quiz = Quiz.objects.filter(code=code) … -
How to validate request.POST.get() is not None and not empty is there any easy way to handle?
i am trying to validate my request.POST.get() data if it is null or empty i am redirecting to error page i tried this way if there is better way to handle this please let me know. given_name = request.POST.get('given_name') surname = request.POST.get('surname') gender = request.POST.get('gender') DOB = request.POST.get('DOB') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') if given_name == "" or given_name == None or surname == "" or surname == None or gender == "" or gender == None or DOB == "" or DOB == None or email == "" or email == None or phone == "" or phone == None or address == "" or address == None: -
"Too many redirects" error with naked domain on PythonAnywhere Django web app + Google Domains, but www works?
I've been messing with the settings for my Google Domains DNS for "mollygeerling.com" as my PythonAnywhere web app will work fine if the address is "www.mollygeerling.com" but not the naked domain. I think this has something to do with my DNS settings and/or my Django settings.py file (allowed hosts includes both the www and naked domains which I thought would fix it but it does not). I am using the Google Domains name servers and I have DNSSEC turned on. At PythonAnywhere I have "force HTTPS" turned on. My guess is something in my Google Domains subdomain forwarding is wrong. Any help appreciated! -
Why does a field(liked_songs) show for a userprofile in admin/ but not when I query the database
ORM queries >>> from comparison.models import UserProfile, Song, Album >>> UserProfile.objects.all() <QuerySet [<UserProfile: kb>, <UserProfile: Daniella>]> >>> Song.objects.all().values_list("pk", flat=True) st' <QuerySet [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, '...(remaining elements truncated)...']> 6, 17, 18, 19, 20, '...(remaining elements truncated)...']> >>> UserProfile.objects.get(id=2) <UserProfile: Daniella> >>> UserProfile.objects.get(id=2).liked_songs.all()[0:20] <QuerySet []> >>> UserProfile.objects.get(id=1) <UserProfile: kb> >>> UserProfile.objects.get(id=1).liked_songs.all()[0:5] <QuerySet [<Song: Emotionally Scarred>, <Song: Lonely Child>, <Song: Really Love>, <Song: Another Life>, <Song: Bitches Ain't Shit>]> >>> models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) liked_songs = models.ManyToManyField("Song", null=True , default=None, related_name="users_that_liked_me") class Meta: db_table = "UserProfile" def __str__(self): return self.user.first_name class Album(models.Model): Album_name = models.CharField(max_length=40) class Meta: db_table= "Album" def __str__(self): return self.Album_name class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200) album = models.ForeignKey(Album, on_delete= models.CASCADE, null=True, default=None, related_name = "songs") class Meta: db_table="Song" def __str__(self): return self.track_name views.py(one which uses the models) def liked(request): try: sp = Spotify(auth_manager=oauth) liked = sp.current_user_saved_tracks(limit=30)['items'] spotify_user = sp.current_user() user__ , created = User.objects.get_or_create(username=spotify_user['uri'], first_name=spotify_user["display_name"]) userprofile = UserProfile.objects.get_or_create(user=user__)[0] a = [] for idx, item in enumerate(liked): track = item['track']["name"] artist= item["track"]["artists"][0]["name"] album_ = item["track"]["album"]["name"] tracks = item['track'] val = tracks['name'] + " - … -
Django Model Field for html5 Range Slider
I'm looking for a Django Model Field to render a HTML5 range slider like: <input type="range" min="1" max="100" value="50"> This question comes close Which Django Form Field can provide me a HTML output of <input type="range" />? but it asks for a form where I would search for an admin field for Django Admin. Further this discussion shows as well how to use an IntegerField as range slider in forms: https://code.djangoproject.com/ticket/20674 Long story short, can I use forms in Django Admin, or is there already a specific range field? -
how to open only one collapse button inside for loop in django
I am working on a practice project for a weather app, showing the next 7 days of weather forecast when clicking the button in a current weather bootstrap5 card. Using bootstrap collapse shows every city's daily weather forecasts at once. which part should I change and I haven't learned javascript yet. The next 7days of the weather forecast list(city_weather_forecast) is placed in the current city weather status(city_weather_data) so that the current city's latitude and longitude can be used to get info for a daily forecast. views.py/ parts for the context to provide templates. def index(request): current_weather_url = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}" forcast_weather_url = "https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&units=metric&exclude=current,minutely,hourly&appid={}" api_key = "3305a1cea0761d956da3c5f87c21b563" message = '' err_msg = '' message_class = '' form = CityForm() if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_city = form.cleaned_data['name'] count_city_in_data = City.objects.filter(name=new_city).count() if count_city_in_data == 0: r = requests.get(current_weather_url.format(new_city, api_key)).json() if r["cod"] == 200: form.save() return redirect('weather:home') else: err_msg = "The city name is not a proper name." else: err_msg = "The city is already in your list." if err_msg: message = err_msg message_class = 'alert-danger' else: message = 'The city is added successfully.' message_class = 'alert-success' cities = City.objects.all().order_by('-created_date') weather_data = [] for city in cities: # Current weather status … -
Why does this docker compose file build the same image four times?
When I run docker-compose build on the following docker-compose file, which is for a django server with celery, it builds an identical image four times (for the web service, celeryworker, celerybeat and flower). The entire process is repeated four times I thought the point of inheriting from other service descriptions in docker-compose was so that you could reuse the same image for different services? How can I reuse the web image in the other services, to reduce my build time by 75%? version: '3' services: web: &django image: myorganisation/myapp container_name: myapp_web build: context: . dockerfile: ./compose/local/django/Dockerfile # This is a multistage build installing private dependencies, hence this arg is needed args: PERSONAL_ACCESS_TOKEN_GITHUB: ${PERSONAL_ACCESS_TOKEN_GITHUB} command: /start volumes: - .:/app ports: - 8000:8000 depends_on: - db - redis environment: - DJANGO_SETTINGS_MODULE=backend.settings.local - DATABASE_URL=postgres://postgres_user:postgres_password@db/postgres_db - REDIS_URL=redis://:redis_password@redis:6379 - CELERY_FLOWER_USER=flower_user - CELERY_FLOWER_PASSWORD=flower_password env_file: - ./.env celeryworker: <<: *django container_name: myapp_celeryworker depends_on: - redis - db ports: [] command: /start-celeryworker celerybeat: <<: *django container_name: myapp_celerybeat depends_on: - redis - db ports: [] command: /start-celerybeat flower: <<: *django container_name: myapp_flower ports: - 5555:5555 command: /start-flower volumes: postgres_data: driver: local pgadmin_data: driver: local -
Django/Python : Many to Many Nesting Serializer with Unique Validation Not Working
I'm having an issue posting/serializing m2m data. I've tried the below code out but I'm getting a grant type already exists issue. I understand this is because I set the type field to unique. When I try to override the create method I get the same issue. I tried to delete the grant_type and post the call again but I get the following error: \django\db\models\fields\related_descriptors.py", line 545, in set raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use region.set() instead. ->My goal is to create with the grant type object, and also retrieve grants with the grant type object Request Body I was using { "name": "GrantName 1", "amount": "5000", "grant_type": [ {"type": "Hiring"} ], "deadlines": "Open Until Filled", "region": ["2"] } Models class Grant(models.Model): name = models.CharField(max_length=250, unique=True) amount = models.IntegerField() grant_type = models.ManyToManyField(GrantType) deadlines = models.CharField(max_length=250) region = models.ManyToManyField(Region) class Meta: db_table = "grants" def __str__(self): return self.name class GrantType(models.Model): type = models.CharField(max_length=250, choices=GRANT_TYPE_CHOICES, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.type class Meta: db_table = "granttypes" class Region(models.Model): abbreviation = models.CharField(max_length=150, choices=REGION_CHOICES, unique=True) name = models.CharField(max_length=250, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.abbreviation … -
How to build a multi object ORM model
I'm trying to build models for a Django app. But I'm not sure what is the correct way to build a multi object link, I'll explain what I mean by that. So let's say I have a 'main' model, for example a post on a news website, and I want the post to be either a text, a video or an image. My question is what is the best way to implement that, is it to have an abstract model and have every types of articles inherit it, or to have a One To One relation with a 'post item' for example. Here a quick code in Python used for the Django ORM to demonstrate what I mean: The 'inheritance' way of doing things: class Category(models.Model): title = models.CharField(max_length=100) class PostAbstract(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="%(class)s_posts") title = models.CharField(max_length=100) [...] class Meta: abstract = True class Video(PostAbstract): duration = models.DurationField() [...] class Article(PostAbstract): text = models.TextField() [...] Or the 'One To One' relation to a 'base' model: class Category(models.Model): title = models.CharField(max_length=100) class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=100) [...] class Video(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) duration = models.DurationField() [...] class Article(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) text … -
how to force column dtype prior to loading data with django ORM
We are using pandas (v0.25.3) to run analysis and data manipulation from large data sets from our postgres database accessed via the Django ORM (django v2.2.6). The situation we have is that the table we are importing to a DataFrame includes a foreign key ID column which is stored as a models.BigIntegerField. This foreign key field is typically a large number but can also be null in those rows where the foreign key is not set. When we import the list of records from the Django query set into a new pandas DataFrame, pandas sets the dtype of the ID column to np.float64 since the data includes some null values. But, for those rows where the ID is not null, the conversion from BigInteger to np.float64 causes the least significant digits to change such that if we subsequently try to re-cast the column dtype to np.int64 (using DataFrame.astype()), we end up with a different value. The following a simplified example of the problem we are seeing: import numpy as np import pandas as pd data = [{'id': 144123525091332019}, {'id': None}] df = pd.DataFrame(data) df Out[6]: id 0 1.441235e+17 1 NaN df.fillna(0, inplace=True) df.astype({'id': np.int64}) Out[8]: id 0 144123525091332032 1 0 … -
Implementing select2 in form to query existing users, ModelMultipleChoiceField is always invalid on form
I inherited a project where we wanted to use django's native User model but also give users some additional fields. So I made a model called UserProfiles, which has a foreignkey to each User instance. I made a template to update these UserProfiles called settings-userprofile.html. Previously, we only had the field api_key for people to modify, so things were basic. We want every User to have their own list of "assistant" Users, a label relevant for an API we'll be implementing. So I added the field assistants and updated settings-userprofile.html to include a <select multiple> element that lists out all the existing users on our site. We're using a theme/template that is able to implement the select2 pillbox/tokenization element (like the rightmost screencap in this picture) user_profile/models.py class UserProfile(models.Model): phone_number = models.CharField(max_length=15, verbose_name='Phone Number') user = models.OneToOneField(User, on_delete = models.CASCADE) api_key = models.CharField(max_length=200, default='12345678',) assistants = models.ManyToManyField(User, related_name="assistants") settings-userprofile.html <form class='form-horizontal' method="post" action="{% url 'profileUpdate' %}"> {% csrf_token %} <div class="form-group row mb-4"> <label for="api_key" class="col-sm-3 col-form-label"><b>Profile Api Key:</b></label> <div class="col-sm-9"> <input type="text" name="api_key" class="form-control" id="horizontal-apikey-input" value="{{ request.user.userprofile.api_key }}"> </div> </div> <div class="form-group"> <label class="control-label">User list</label> <select name="assistants" class="select2 form-control select2-multiple" multiple="multiple" data-placeholder="Choose ..."> <optgroup label="Existing users"> {% for u … -
Django: Annotating Sum() of two columns in different tables
assuming I have the following models - How can I annotate the total posting and total story reach of each influencer in my queryset? class Influencer(models.Model): name = models.CharField(max_length=100) class Posting(models.Model): influencer = models.ForeignKey(Influencer, on_delete=models.CASCADE) reach = models.IntegerField() class Story(models.Model): influencer = models.ForeignKey(Influencer, on_delete=models.CASCADE) reach = models.IntegerField() I have tried this: queryset = Influencer.objects.all() queryset = queryset.annotate(posting_reach=Sum("posting__reach")) queryset = queryset.annotate(story_reach=Sum("story__reach")) However, the values are not calculated correctly using this approach (I assume because of the LEFT OUTER JOIN which is made by Sum()). How would I do this in Django? -
How to update a django moodel value from a button click in a class based view
i currently have a model that looks like: class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) is_best_answer = models.BooleanField(default=False) def set_best_answer(self): self.is_best_answer = True self.save() def get_absolute_url(self): return reverse('question-detail', kwargs={'pk': self.question.pk}) def __str__(self): return f"Answer by {self.author} with text: {self.content}" I have a Class based Listview which lists all of the answers above. I want to add a button in the template that would update the value in the model of is_best_answer to True e.g. <a class="btn btn-outline-dark " href="{% url '' answer.id %}">Set Best Answer</a> Is there a clean way to do this within the class based view? Dango version 3.1 -
How can i access choices of the model in the serializers and obtain a json view
models.py MSI_OPTIONS = ( (ANC1, 'AN1'), (ANC2, 'AN2'), (ANC3, 'AN3'), (ANC4, 'AN4'), (DELIVERY, 'Delivery'), (FAMILY_PLANNING, 'Family Planning'), ) class MSIService(models.Model): girl = models.ForeignKey(Girl, on_delete=models.CASCADE) option = models.CharField(choices=MSI_OPTIONS, default=ANC1, max_length=250) Am trying to obtain a JSON object counting how many time each MSI_OPTIONS is used like { "ANC1": 3, "ANC2": 4, "ANC3": 4, "ANC4": 10 } Note: each girl has one of MSI_OPTIONS. -
how to auto add multiple models in a single model form auto instanced
so i already have a modelform that has 2 models inline inside it, but only the main model instances appear at start, and to start editing the other two models i have to click add like below : so i want it to be displayed automatically at the page without me starting it. here is a snippet of my code: class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) class FamilyGroup(models.Model): name_choices = (('FG_1', 'FG_1'), ('FG_2', 'FG_2'), ('FG_3', 'FG_3'), ('FG_4', 'FG_4'), ('FG_5', 'FG_5')) name = models.CharField(max_length=10, choices=name_choices) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_type = models.ForeignKey(FamilySituation, on_delete=models.PROTECT, null=True, blank=True) class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=m odels.PROTECT) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] -
AH00035: access to / denied 403 Forbidden Django mod-wsgi
I am trying to configure apache with Django using mod-wsgi. But I am getting the following error AH00035: access to / denied (filesystem path '/home/ec2-user/ezvoice') because search permissions are missing on a component of the path URL is showing 403 forbidden Here is the conf file LoadModule wsgi_module "/home/ec2-user/venv/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" <VirtualHost *:80> DocumentRoot /home/ec2-user/ Alias /static /home/ec2-user/ezvoice/sub_app/static <Directory /home/ec2-user/ezvoice/sub_app/static> Options FollowSymLinks Order allow,deny Require all granted </Directory> WSGIDaemonProcess ezvoice python-path=/home/ec2-user/ezvoice:/home/ec2-user/venv/lib/python3.7/site-packages WSGIProcessGroup ezvoice WSGIScriptAlias / /home/ec2-user/ezvoice/main_app/wsgi.py ErrorLog /home/ec2-user/ezvoice/log-error.log CustomLog /home/ec2-user/ezvoice/custom-error.log combined <Directory /home/ec2-user/ezvoice/main_app> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The directory structure is as follow home -ec2-user --ezvoice ---main_app ----asgi.py ----settings.py ---sub_app ----views.py --venv ---bin ---include ---lib