Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django cassandra get Unable to connect to any servers docker
I use windows 10. get this error when building cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'127.0.0.1:9042': ConnectionRefusedError(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")}) Dockerfile FROM python:3.8.5 ENV PYTHONUNBUFFERED=1 ENV CASS_HOST=cassandra ENV CASSANDRA_HOST=cassandra RUN apt-get -y update RUN apt-get -y upgrade RUN apt-get -y install wait-for-it RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ EXPOSE 8080 docker-compose.yml version: '2' services: cassandra: hostname: cassandra image: cassandra:latest ports: - "9042:9042" - "9160:9160" networks: - cassandra web: build: . command: /bin/bash -c "cd api_messages && wait-for-it cassandra:9042 -- python manage.py sync_cassandra && python manage.py runserver 0.0.0.0:8080" volumes: - .:/code ports: - "8000:8080" depends_on: - cassandra networks: - cassandra environment: - PYTHONUNBUFFERED=1 - PYTHONDONTWRITEBYTECODE=1 - CASSANDRA_HOST=cassandra - CASS_HOST=cassandra networks: cassandra: -
Django browser upload failed
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | dbik_1 | 2021-05-19 10:45:54.221 UTC [1] LOG: starting PostgreSQL … -
Django: To check if old password emtered by the user is valid or not
I am able to check the new_password1 and new_password2, but i am unable to check whether the old password entered by the user is right or not. As it is not giving me the validationerror on old password on the django template. Please suggest me the condition that can be used on forms.py This is forms.py class ChangePasswordForm(forms.Form): old_password = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password1 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password2 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def set_user(self, user): self.user = user def clean(self): old_password = self.cleaned_data.get('old_password') valpwd = self.cleaned_data.get('new_password1') valrpwd = self.cleaned_data.get('new_password2') if not old_password: raise forms.ValidationError({ 'old_password':"You must enter your old password."}) elif valpwd != valrpwd: raise forms.ValidationError({ 'new_password1': 'Password Not Matched'}) return self.cleaned_data This is views.py class PasswordsChangeView(FormView): template_name = 'dashboard/password/password_change.html' form_class = ChangePasswordForm success_url = reverse_lazy('dashboard:admin_login') def get_form(self): form = super().get_form() form.set_user(self.request.user) return form This is change_password.html <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <h6>Old Password</h6>{{form.old_password}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <span style="color:red">{{ form.old_password.errors }}</span> <div class="input-group mb-3"> <h6>New Password</h6> {{form.new_password1}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>Re-Type Password</h6> {{form.new_password2}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> … -
POST request to upload file
I want to upload a file to my django application. views.py @api_view(['POST']) def upload_to_evm(request): if request.method == 'POST' and request.FILES['file']: file = request.FILES['file'] filename = FileSystemStorage().save('abcd', file) return JsonResponse({'Status': 'Successful'}) urls.py urlpatterns = [ path('api/evm_process/', views.upload_to_evm) ] Currently, I am sending my request with Binary File option and with header Content-Type: multipart/form-data and it gives MultiValueDictKeyError error which means my request.FILES is empty and I cannot understand why. My question are: What is the correct way to make a POST request with all the headers and query_params for the same ? Do I need a parser (FileUploadParser, MultiPartParser or FormParser) to upload, save or process the uploaded file ? Python version: 3.6.9 Django version: 3.2.3 -
Set default values of year and month using django-yearmonth-widget
How to set default value using django-yearmonth-widget for year as current year and month as month_name-1 Forms class FileUploadForm(forms.ModelForm): file = forms.FileField(required=True,widget=forms.ClearableFileInput(attrs={'multiple':True}), label='Select Files') file_remote = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple':True}), required=False) class Meta(): model = FileUpload fields= ('file_upload_datetime','file','file_remote') widgets = { 'file_upload_datetime': DjangoYearMonthWidget(), 'file_remote':forms.HiddenInput() } Models class FileUpload(models.Model): file = models.FileField(upload_to='files') file_remote = models.FileField(upload_to=RetailFormsConfig.remote_folder, storage=upload_storage, blank=True) file_upload_datetime = models.DateField() -
How to post data to custom user model using abstract user?
I'm pretty confused in this I've created a form for accepting the user model data. Even i customised the user model data to Abstract user. models.py class User(AbstractUser): user_role=models.IntegerField(default=0) views.py from django.contrib.auth.models import User def register(request): if request.method == 'POST': post.first_name=request.POST.get('first_name') post.last_name=request.POST.get('last_name') post.email=request.POST.get('email') post.username=request.POST.get('user') post.password=make_password(request.POST.get('password')) post.user_role=1 post.save() while posting, no data is passed ,it's totally null and when tried print(post.user_role) it says user has no attribute user_role any help will be appreciated. -
django.db.utils.OperationalError: no such table: store_product
When I run makemigrations error is occurred. Here is models.py def unique_order_id(): not_unique = True while not_unique: uo_id = random.randint(1000000000, 9999999999) if not Order.objects.filter(order_id=uo_id): not_unique = False return uo_id class Product(models.Model): #product code, name, category, unit price, current stock product_code = models.IntegerField(unique=True) name = models.CharField(max_length=100) category = models.CharField(max_length=100) unit_price = models.FloatField() current_stock = models.IntegerField() def __str__(self): return self.name class Order(models.Model): order_id = models.IntegerField(unique=True, default=unique_order_id) customer_name = models.CharField(max_length=100) phone = models.CharField(max_length=14) email = models.EmailField() qr_code = models.ImageField(upload_to='qr_codes', blank=True) def __str__(self): return self.customer_name #override ths save method for creating qrcode based on fields on this model. def save(self, *args, **kwargs): qr_info = "Invoice No : "+ str(self.order_id)+" Name : "+self.customer_name +" Phone : "+str(self.phone)+ " Email : "+ self.email qrcode_img = qrcode.make(qr_info) #canvas = Image.new('RGB', (290, 290), 'white') canvas = Image.new('RGB', (qrcode_img.pixel_size, qrcode_img.pixel_size), 'white') canvas.paste(qrcode_img) fname = f'qr_code-{self.customer_name}.png' buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) class OrderItem(models.Model): qty = models.IntegerField(default=0) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) #this will return total price of product(unit_price*quntity) @property def get_total(self): total = self.product.unit_price * self.qty return total This is forms.py codes class ItemSelectForm(forms.Form): p_name = forms.ChoiceField(label='Select Product',choices=list ((obj.product_code,obj.name) for obj in Product.objects.all())) qty = forms.IntegerField() #function for checking product … -
Django: 'utf-8' codec can't decode byte 0xe9 in position 10298: invalid continuation byte while performing python manage.py loaddata operation
Good day, I am transferring db from vscode django project to heroku postgres db. when I do python manage.py loaddata products.json I get the error: thank you -
TypeError: 'NoneType' object is not subscriptable in Django?
@property def geolocation(self): """ This function will fetch lat and lng value from location_data JSON filed and return combined value in form of string( pattern="lat,lng"). """ location = "" if self.location_data: lat = self.location_data["geometry"]["location"]["lat"] lng = self.location_data["geometry"]["location"]["lng"] location = location + str(lat) + "," + str(lng) return location when this function is called it return Type error. This function is @property of model and location data JSONFIELD of model and where I stored lat and lng value and it can be null. But when i fetch empty location data it show error? I am confused why Iif I already handled else? -
django sendgrid get error when sending email
I set up sendgrid as following and it works perfectly when I use send_mail to send a test message EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 EMAIL_USE_TLS = True Howerver when I implement it with an activation code in views.py for registration as bellow: def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() #completed sign up username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) # Create data in profile table for user current_user = request.user data=UserProfile() data.user_id=current_user.id data.image="images/users/user.png" data.save() current_site = get_current_site(request) subject = 'Please Activate Your Account' # load a template like get_template() # and calls its render() method immediately. message = render_to_string('user/activation_request.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # method will generate a hash value with user related data 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('activation_sent') # messages.success(request, 'Your account has been created!') # return HttpResponseRedirect('/') else: messages.warning(request,form.errors) return HttpResponseRedirect('/register') form = SignUpForm() #category = Category.objects.all() context = { 'form': form, } return render(request, 'user/register.html', context) It throws out this error: SMTPDataError at /register (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error … -
Django Admin connection to Firebase
I don't know how to connect the Django Administration page to Firebase. For example, I can't set data entered in a field of a model in my Firebase Database. I know how to do it with the other pages I created but with admin page I can't get a way to do so. And I don't know how to deal with admin page like the other pages so that I can customize it or add functions to it. -
Django Form Validation: It is not showing me django error message in template
Here I want to show validationerror on template but it is not returning the error before i even type the password. I want to check the newpassword entered by the user and match the re-entered password, but it's not showing me the error message though it isnot accepting the form if the password arenot matched. This is my views.py class PasswordsChangeView(FormView): template_name = 'dashboard/password/password_change.html' form_class = ChangePasswordForm success_url = reverse_lazy('dashboard:admin_login') def get_form(self): form = super().get_form() form.set_user(self.request.user) return form This is forms class ChangePasswordForm(forms.Form): old_password = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password1 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password2 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def set_user(self, user): self.user = user def clean(self): cleaned_data = super().clean() old_password = self.cleaned_data.get('old_password') valpwd = self.cleaned_data.get('new_password1') valrpwd = self.cleaned_data.get('new_password2') if valpwd != valrpwd: raise forms.ValidationError({ 'new_password1':'Password Not Matched'}) return self.cleaned_data This is template <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <h6>Old Password</h6>{{form.old_password}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>New Password</h6> {{form.new_password1}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>Re-Type Password</h6> {{form.new_password2}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> <span class='form-error'> {{form.errors.new_password1}}</span> </div> {% comment %} {{ … -
Pip install mysqlclient this command shows error while iam trying to connect django with existing wamp MySQL. Is there any other way to do it?
the prblem that I have is given below -
What is this url path mean?
Hello I am new to Django, I saw a line path('dashboard/(?P<user>.*)/$'), . I didn't understand this. I want to learn this part. But I don't know how to search on google and youtube about this. -
Get the last 2rd item in HTML
I have used Django to develop a webapp In the admin model, I want to choose the last 2rd one in the list(models) How could I slice in the below? <div v-for="(c,j) in models" :key="c.name" class="quick-wrap"> <a href="javascript:;" @click="openTab(c,(j+1)+'')"> <span class="icon" :class="c.icon"></span> <span class="card-name" v-text="c.name"></span> </a> </div> -
Most effective way of updating an m2m field in django?
I have looked at the documentation on how to update an m2m relation, but I got confused with the backend working of .set as it says that .set([]) clears all the previous relationships and then adds new ones for many to many relations, since bulk keyword argument does not exist. NOTE-> I want to update the list of objects in my model. link to django docs -> https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.set -
browser time out using domain name but not on local server
I require help in setting up the browser (Chrome) time-out session. For example:- 1 am generating a report in real-time when I am generating it on the local server (127.0.0.1). it is working without any issue and no time-out issue. But when I am trying that the same using domain name from a local PC and if it is taking more than 120 Sec to generate because of more data say 1000000 records in the report the page is getting expired or timeout. How to fix this issue? The development platform is Python, Django & PostgreSQL. -
How to add two url argument to Django template url tag?
my django version is 2.0.5 my os version is ubuntu 20.04 I want to pass two url argument in Django template url tag,my url code is blow path('download/<str:bucket>/<str:object>/',views.Download.as_view(), name='download'),# appname= storage the code below can work <a href="{% url 'storage:download' bucket=bucket object='object.Key' %}">{{ object.Key }}</a> but the the code below doesn't work <a href="{% url 'storage:download' bucket=bucket object= object.Key %}">{{ object.Key }}</a> <a href="{% url 'storage:download' bucket object.Key %}">{{ object.Key }}</a> is there any way to make my code work? -
Django project how to find admin username and password
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | dbik_1 | 2021-05-19 10:45:54.221 UTC [1] LOG: starting PostgreSQL … -
TypeError in returned value django
I have this property for my table: @property def commission_percent(self): with connection.cursor() as cursor: # Data retrieval operation - no commit required cursor.execute('SELECT crowdfunding_offering.commission_percent FROM crowdfunding_offering WHERE crowdfunding_offering.id = %s ORDER BY crowdfunding_offering.id DESC LIMIT 1', (int(self.offering.id),)) row = cursor.fetchone() if not row is None: return row return 0 which returns 0.05. It's going exactly how I expected it, but when I try to use the value to compute for another property like so: def commission_due(self): if not self.commission_paid is None: return (self.invested * self.commission_percent) - self.commission_paid return self.invested * self.commission_percent I get this error: Exception Value: can't multiply sequence by non-int of type 'decimal.Decimal' I tried changing self.commission_percent to self.commission_percent() but I get this error: Exception Value: 'tuple' object is not callable I don't know what to do, and this is all very new to me. Any help is appreciated. -
Can't import views from application the the URLS of project in Django 3.1
I'm not able to import my views in the app folder to the URLS of project folder. I've tried every possible methods like 'from . import views' or 'from newapp import views as newapp_views' and 2-3 more alternatives that I searched on the internet. My app name is newapp and project name is newproject. Please help me. This is my models file: from django.db import models class User(models.Model): first_name=models.CharField(max_length=128) last_name=models.CharField(max_length=128) email=models.EmailField(max_length=256, unique=True) This is my URLS of newapp folder: from django.conf.urls import url from django.urls.resolvers import URLPattern from .models import views urlpatterns= [url(r'^$', views.users, name='users'), ] This is my views of newapp folder: from django.shortcuts import render from .models import User def index(request): return render(request, 'newapp/index.html') def users(request): user_list=User.objects.order_by('first_name') user_dict={'users': user_list} return render(request, 'newapp/users.html', context=user_dict) This is my URLS of newproect folder: from django.contrib import admin from django.urls import path,include from newapp import views urlpatterns = [ path('', views.index, name='index'), path('users/',views.users, name="users"), path('admin/', admin.site.urls), ] This is my settings file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newapp' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, … -
Django MPTT get specific child category
I have two models a category and a product model, the category is using django MPTT. I am unable to get or filter on a specific child. class Item(models.Model): title = models.CharField(max_length=150) merchant = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="Merchants", on_delete=models.CASCADE, related_name="items" ) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="category" ) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.DecimalField( max_digits=9, decimal_places=2, blank=True, null=True ) class Category(MPTTModel): title = models.CharField(max_length=100) parent_category = TreeForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE, related_name="sub_categories", ) slug = models.SlugField(max_length=100) vertical = models.ForeignKey(Vertical, on_delete=models.CASCADE, blank=True, null=True) class Meta: indexes = [GinIndex(fields=["title", "parent_category"])] verbose_name_plural = "categories" unique_together = ["slug", "parent_category"] class MPTTMeta: order_insertion_by = ['title'] parent_attr = 'parent_category' the problems I have when I run a queryset against a sub_category it continues to give me all the object in the main category items = Item.objects.filter(category__parent_category__sub_categories__slug='flu') However it is returning all items under the parent category not only the items that belong to the flu category many thanks -
Django view returning POST instead of GET request
So I have these working views for registration and login using POST requests, both of which returning profile.html. The problem is the login and registration views return a POST to the login or register urls when i submit the forms(according to cmd), to run the necessary functions. which means it is simply rendering the profile.html, but not running ITS view function. How do i have the form submissions send a GET to the profile view while still having them send POST for their own respective functions. Views: def log_in(request): if request.method == 'POST': form = log_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: print("user exists") login(request, user) return render(request, 'profile.html') else: print("user does not exist") print(form.errors) return render(request, 'login.html', { 'form2': log_form }) else: return render(request, 'login.html', { 'form2': log_form }) else: return render(request, 'login.html', { 'form2': log_form }) def profile(request, username): if request.method == 'GET': user = Users.objects.get(username=username) interests = [] interest_list = Interests.objects.filter(member=user)#i got 5 objs here for i in interest_list: interests.append(i.item) print('added interest') info = Bios.objects.get(author=user) return render(request, 'profile.html', { 'user': user, "interests": interests, 'info': info }) Urls: urlpatterns = [ path('reg/', views.register, name='register'), path('log/', views.log_in, … -
I can't display a google maps map with django
I am trying to display a map with django: {% block content %} {% load static %} <div id="map"></div> <script src="{% static 'display_map.js'%}"></script> <script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places&callback=initMap"></script> {% endblock %} And the display_map.js file is: let map; function initMap(){ map = new google.maps.Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } It does not show the map. Thank you -
Why Does My Django Project Reject React Tags?
In my project, I am trying to tie together Django and React. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> {% load static %} <link rel="icon" href="{% static 'logofavicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta property="og:image" content="{% static 'Banner.png' %}"> <meta name="description" content="The future of digital content" /> <link rel="apple-touch-icon" href="{% static 'logo192.png' %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Drop Party</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <script type="module" src="{% static 'index.js' %}"></script> <div id="root"></div> </body> </html> index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import "./styleguide.css"; import "./globals.css"; ReactDOM.render( < React.StrictMode > < App / > < /React.StrictMode>, document.getElementById("root") ); reportWebVitals(); settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/frontend/' STATICFILES_DIRS = ( FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public' ) Project Hierarchy Extension of this post. I have added in the script, but I have found that I get an Uncaught SyntaxError: Unexpected token '<' on line 9, which is where the React tag is.