Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign member "image_url" for type "Article" "Literal['http://default']" is incompatible with "property"
impot_data: from blog.models import Article def run(): for i in range(5,15): article= Article() article.title="Article num° #%d" % i article.desc="description article num° #%d" % i article.image_url ="http://default" print("opération réussie ") -
django.db.utils.OperationalError: no such column: users_classroom.class_code When attempting to Migrate
This is my first Django project, and I am attempting to add the attribute class_code to Classroom, and class_code is a random 6 character string that I plan to use to allow users to join a classroom using it. I attempted to make it random using the code from the following post:https://stackoverflow.com/a/67546412/20015529 and followed this django document:https://docs.djangoproject.com/en/4.1/howto/writing-migrations/#migrations-that-add-unique-fields. I modified the instructions to use the random string as opposed to a uuid due to the length of uuid's. When attempting to migrate, I recieve the following error: "django.db.utils.OperationalError: no such column: users_classroom.class_code". Here are my Django Files. my project name is Project and the app name is users. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile, Classroom from home.models import Announcements class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data['email'] # if User.objects.filter(email=email).exists(): # raise forms.ValidationError('That email is in use. Please Log in or use a different Email') return email class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class ClassJoinForm(forms.ModelForm): class Meta: model = … -
changing the src of an image using javascript for a django website
I'm creating a website using django. At the front end I want to change slides every x seconds. My approach was to change the src of the image every x seconds using javascript Here's how I went about it: //Javascript function newSlide() { var imageTemplate = document.querySelector(".slide-img"); setInterval({ imageTemplate.setAttribute("src", "{% static 'images/newSlideImage.png' %}") }, x); } <!-- html --> <img class="slide-img" src="image.png"> I thought this would change the image for me but it didn't work at all. When I checked my console, it said I couldn't load the file and returned 404 error. error: "failed to load resource: the server responded with a status of 404 (Not Found)" However the initial image loaded perfectly despite using the same syntax {% %} -
failure to deploy by django webapp on heroku
Good day, I'm trying to deploy by django webapp on heroku but i'm facing the following problem. The conflict is caused by: The user requested botocore==1.23.50 awsebcli 3.20.3 depends on botocore<1.24.0 and >1.23.41 boto3 1.26.59 depends on botocore<1.30.0 and >=1.29.59 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts ! Push rejected, failed to compile Python app. ! Push failed And my requirement.txt is the following... asgiref==3.6.0 awsebcli==3.20.3 boto3==1.26.59 botocore==1.23.50 cement==2.8.2 certifi==2022.12.7 charset-normalizer==2.0.12 colorama==0.4.3 contourpy==1.0.7 cycler==0.11.0 distlib==0.3.6 dj-database-url==1.2.0 Django==4.1.4 django-crispy-forms==2.0 django-heroku==0.3.1 django-storages==1.13.2 filelock==3.9.0 fonttools==4.38.0 future==0.16.0 gunicorn==20.1.0 idna==3.4 jmespath==0.10.0 kiwisolver==1.4.4 matplotlib==3.6.3 numpy==1.24.1 packaging==23.0 pathspec==0.9.0 Pillow==9.4.0 platformdirs==2.6.2 psycopg2==2.9.5 psycopg2-binary==2.9.5 pyparsing==3.0.9 python-dateutil==2.8.2 PyYAML==5.4.1 requests==2.26.0 s3transfer==0.6.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.3 termcolor==1.1.0 tzdata==2022.7 urllib3==1.26.14 virtualenv==20.17.1 wcwidth==0.1.9 whitenoise==6.4.0 What am i missing? -
Current path does not match path patterns error
I'm pretty new to Django and I've been following this page step-by-step: https://docs.djangoproject.com/en/4.1/intro/tutorial01/. However, when I try to call the polls app using localhost:8000/polls, a page not found error shows up. I don't have too much of an idea how to fix this, since I'm pretty new. I remember seeing how VS was complaining about the module admin not working but I resolved it by just reinstating the python interpreter. I also tried to re=run the server and reloading VS but it didn't really help. All of my modules match the one in the tutorial. -
Using custom queries with Django annotate
In annotate. When counting records, how can I use a custom query to narrow down what to count? class User(models.Model): name = models.CharField(max_length=50) class Tweet(models.Model): user = models.ForeignKey("User", related_name="tweet") favorite = models.IntegerField(default=0) is_active = models.BooleanField(default=False) objects = TweetQuerySet.as_manager() class TweetQuerySet(models.QuerySet): def buzzed(self): return self.filter( is_active=True, favorite__gte=100 ) # I want to count only the tweets returned using the buzzed query. users = User.objects.annotate(tweet_count=Count("tweet")) Thanks in advance. -
message.success not showing
I'm trying to set up success messages for whens u user successfully logs in. But it is not working for me. I Have tried both in and out of block, both don't work. View: def UserLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,("You were successfully logged in...")) return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) Main.html: {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show alert-main" role="alert"> <p style="color: darkgreen;">{{ message }}<p> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% block content %} {% endblock %} -
Cant loging in django app service using auth
I develope a website using django, nginx and docker in an azure container registry and app service. when i run the image using docker desktop it runs properly, but when i try to login in appservice in only redirect me to login page. I want to use the default database of django proyect. I am using a simple auth as follow from django.contrib.auth.decorators import login_required @login_required def home(request): username = request.user.username context = {'username': username} return render(request, 'Home/home.html', context) I added in my settings the follow AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = 'auth.User' ROOT_URLCONF = 'sitioindicadores.urls' and also CSRF_TRUSTED_ORIGINS = ['https://*.abc.net/','https://*.127.0.0.1'] SESSION_COOKIE_DOMAIN='https://abc.azurewebsites.net/' my nginx and docker are: server web:8000; } server { listen 80; location / { proxy_set_header Host $host; proxy_pass http://app_server; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { autoindex on; alias /app/static/; } } and FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY sitioindicadores . RUN pip install -r requirements.txt COPY nginx.conf /etc/nginx/sites-available/default RUN python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate EXPOSE 80 CMD ["gunicorn", "--bind", "0.0.0.0:80", "sitioindicadores.wsgi:application"] i dont know why it runs ok in docker but not in the web. I'd appreciate … -
Form filtering in Django?
error: 'RegisterlesonForm' object has no attribute 'id' form class RegisterlesonForm(forms.ModelForm): class Meta: model = Registerleson fields = ['leson', 'book', 'discount'] widgets = { 'leson': forms.Select(attrs={'class': 'form-control'}), 'discount': forms.NumberInput(attrs={'class': 'form-control'}), 'book': forms.Select(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super(RegisterlesonForm, self).__init__(*args, **kwargs) self.fields['leson'].queryset = Registerleson.objects.raw( "SELECT * FROM classes_classes WHERE classes_classes.id not IN (SELECT leson_id FROM member_registerleson WHERE student_id = %s )", {self.id}) -
how can i code a plagiarism detector using python django [closed]
I want to make a website where a web URL given by the user is compared with the text entered by the user and the copy rates are printed on the screen. how can i code this with django? i used jaccard similarity to find the plagiarism ratio but I don't know how to ask the user to enter a text and whether that text has been copied from a website. My goal is to make a simple version of turnitin. -
Select using Django/Ajax
In the user profile page, there is a section for user to see the comments made on their posts. There is also a Select filter to query comments by Post. I am trying to use AJAX with the goal of avoiding page reload/refresh. Where am I going wrong? Since the page is still refreshing, I think I am missing some sort of div wrapper around my results. Besides that, the script probably needs more details. The /api url is showing the objects in Json format if I visit the link. urls.py: path('api/',views.api,name='api'), path('profile/<str:pk>/', views.profile, name='profile') views.py def profile(request,pk): user = request.user posts = Post.objects.filter(active=True, owner=request.user) notfirstvisit = UserFirstVisit.objects.filter(user=request.user) comments = Comment.objects.filter(post_owner=request.user) filter_post = request.GET.get('filter_post', None) if filter_post: comments = comments.filter(post__id__exact=filter_post) return render(request, 'profile.html', {'user':user, 'notfirstvisit':notfirstvisit, 'posts':posts, 'comments':comments}) profile.html: <form id="filter_post_form"> <select class="form-select" id="filter_post" name='filter_post'> <option value=""{% if value == "" %}selected {% endif %}>Select Post</option> {% for post in posts %} <option value="{{post.id}}" {% if post.id == filter_post %} selected="selected" {% endif %}> {{post.title}} - {{post.created}} </option> {% endfor %} </select> <br> <button name="filter" id="filter" class="btn btn-primary" type="submit">Apply Filter</button> <button name="clear" id="clear" class="btn btn-primary">Clear Filter</button> <br> </form> <div style="overflow-y:auto;max-height: 500px;"> {% for comment in comments %} <div class="card container py-1"> … -
How do you embed a webpack ReactJs bundle file in Django templates html file?
I used webpackJs to generated a dist folder with an index.html and bundle.js. I then copied the bundle.js into my Django project, used django template language to embed the bundle.js into a django index.html file containing a root div. When the browser downloads the index.html and bundle.js files at the root localhost/index, only Django Site with ReactJs appears. I dont understand, how are you suppose to run ReactJs in production? index.html file serving ReactJs Bundle from Webpack The bundle.Js is located in a static folder in the Django application <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> {% load static %} <script src="{% static '/Core_CRUD/bundle.js' %}" type="text/javascript"></script> </head> <body> <h1>Django Site with ReactJs</h1> <div id="root"></div> </body> </html> Tried debugging, didnt work -
Django admin page - open 'VIEW SITE' in a new tab?
In admin portal of my Django app (v. 3.1), is it possible to configure the "VIEW SITE" link in the site header so that it will open in a new tab, target="blank"? I'm referring here to the link whose href can be configured via admin.site.site_url... I'd like to give my admin users quick and easy access to the site linked there, but I don't want them to be navigating away from their authenticated admin session. I currently have this value set to a custom configuration in urls.py like so protocol = 'https' domain = 'mysite.com' if os.environ.get('DJANGO_DEVELOPMENT'): protocol = 'http' domain = 'localhost:8080' admin.site.site_url = f'{protocol}://{domain}' as this URL actually needs to point at an application running on a different server. -
Is there a way to make a Form table that submits all the values?
In my django project, I have the following code that ideally the user to could edit modify an then submit, sending the all of the values to my views.py via forms.py (or any other possible way) so I can perform some calculations on the values. I have only gotten the code to work when it sends one value that has been changed then submitted but I need all of the values in the table. Any suggestions on how to do this would be greatly appreciated. function edit(element) { var tr = jQuery(element).parent().parent(); if (!tr.hasClass("editing")) { tr.addClass("editing"); tr.find("DIV.td").each(function() { if (!jQuery(this).hasClass("action")) { var value = jQuery(this).text(); jQuery(this).text(""); jQuery(this).append('<input type="text" value="' + value + '" />'); } else { jQuery(this).find("BUTTON").text("save"); } }); } else { tr.removeClass("editing"); tr.find("DIV.td").each(function() { if (!jQuery(this).hasClass("action")) { var value = jQuery(this).find("INPUT").val(); jQuery(this).text(value); jQuery(this).find("INPUT").remove(); } else { jQuery(this).find("BUTTON").text("edit"); } }); } } .table { display: table; border-collapse: separate; border-spacing: 2px; } .thead { display: table-header-group; color: white; font-weight: bold; background-color: grey; } .tbody { display: table-row-group; } .tr { display: table-row; } .td { display: table-cell; border: 1px solid black; padding: 1px; } .tr.editing .td INPUT { width: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="thead"> <div class="tr"> <div class="td">Column … -
Assign registered User to Customer Model
I want to assign a new registered User to my customer model. At the moment user is successfully registered into the back end but is not assigning to a new Customer model, When redirected to home page after registration the following error occurs: Exception Value: User has no customer. The error is pointing to this utils model: def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, order_status='P') items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} Customer Model: class Customer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) User Register and Login Views: def UserRegister(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, ("Registration successful, you are now logged in...")) return redirect('home') else: form = UserRegisterForm() return render(request, 'authenticate/register.html', {'form': form}) def UserLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You were successfully logged in...")) return redirect('home') … -
What service should I use to deploy my Django App? [closed]
I'm about to deploy my django web app and I've been doing research on what service to use. My only requirements is that it be reliable, be able to host images, and somewhat scalable to 10k+ users, and host database. An fantastic extra is that it would also be easy. I've previously used Heroku and I loved the fact that it was so easy to deploy, but the downside was that it couldn't save any images. I'm looking for a long term scalable solution. Does anybody have suggestions on what to use? So far after my research the top choices seem to be Railway.app and AWS Lambda. I'm a bit scared of AWS because it's so incredibly confusing, but I am starting to lean towards it since it seems everybody is using it and seems like it will be around for a long time. But I'm hoping the more seasoned developers will have a better recommendation or solution to this. -
how to create a vite and django project?
I worked with WebPack and found a lot of issues. I would like to give it a shot using Vite as a frontend. I followed this guide and a bunch of YouTube videos but i didn't understand much and nothing is working. What is the best way to create a Vite(React) + Django app? -
crispy forms adding is-invalid class to my fields before form submission
I am using Django. I have created my forms as below forms.py class PostForm(forms.Form): title = forms.CharField(max_length=50, required=True) body = forms.CharField(max_length=10000, required=True,widget=forms.Textarea(attrs={"rows":"5"})) from_location = forms.CharField(max_length=50, required=True) to_location = forms.CharField(max_length=50, required=True) views.py def create_post(request): if request.user.is_authenticated: post_form = PostForm(request.POST) print('printing title..') if request.method == 'POST': if post_form.is_valid(): post = Post.objects.create(title = request.POST['title'], body=request.POST['body'], from_location=request.POST['from_location'], to_location=request.POST['to_location'], author = request.user, uuid = uuid.uuid4()) message = messages.success(request, f'Your post has been created!') return redirect(reverse_lazy('posts:post')) else: post_form = PostForm() return redirect(reverse_lazy('posts:post')) context = { 'post_form':post_form } return render(request, 'posts/create_post.html', context) I am getting a red border on all the form fields. I realized that crispy-forms has added the class is-invalid to all the fields making this. If I make required=False in forms, the error is gone. Current output expected output is the image above without the red borders and warnings I tried removing the class from dev tools and it worked. I asked chatGPT and tried its methods, but it did not help -
Pass title of product into order in Django Admin
I want to be able to view the title of a product that has been ordered rather than having to cross reference order ids from different fields. I have tried using ForeignKey but it doesnt automatically set the product title. I have to manually select from dropdown list. PRODUCT/PHOTO class Photograph(models.Model): photo = models.ImageField(null=False, blank=False, upload_to="photos/", default="default.png") title = models.CharField( max_length=100, null=False, blank=False, default="") description = models.TextField() ORDER *class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] customer = models.ForeignKey( Customer, on_delete=models.PROTECT, null=True, blank=True) order_id = models.IntegerField(null=True) order_date = models.DateTimeField(auto_now_add=True) order_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING ) def __str__(self): return str(self.id)* -
how to run manage.py migrate on docker everytime is up
I'm trying to figure out how to use docker with a django+postgress application, but I can't manage to make my django_app connect to it and apply the initial migrations docker-compose.yml version: "3" services: database: image: postgres:11.18-bullseye ports: - "5432:5432" volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_HOST_AUTH_METHOD=trust backend: build: ./backend volumes: - ./backend:/app depends_on: - database frontend: build: ./frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx_backend_server ports: - 8000:8000 depends_on: - backend volumes: backup_data: I have called my container "database", so on my settings.py, I'm trying to connect to the host database, not sure if it's correct settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'database', 'PORT': 5432, } } and the Dockerfile on my backend looks like this: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r req.txt RUN python manage.py makemigrations CMD python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi When I hit docker-compose up, this is my log from my database: database_1 | waiting for server to start....2023-03-26 18:12:13.705 UTC [50] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" database_1 | 2023-03-26 … -
When adding to the cart, if the user is not logged in, it is added to the wishlist. Django Ajax JavaScript
I want my system to remember not only products of authorized people, but also those who are not authorized. I made a similar cookie system for cart and wishlist that works until you log out. In addition, I can say that both buttons of the add behavior (to cart, to wishlist) both behave like adding to cart, in the state of an unauthorized user. For example, a wishlist has a limit of 1 product of the same type, but if you go out and add to cart, which will result in being added to the wishlist, you can make an infinite number of additions as in the cart. The same goes for the wish list button. I think it's in the behavior of js, what, perhaps, I need to add or change? wishlist.js add button var updateBtns = document.getElementsByClassName('update-wishlist') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserWish(productId, action) } }) } order update function updateUserWish(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_wish_item/' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) … -
Image front changes from system to system
I tried to convert pdf file to image using python package pdf2img. On my local ubuntu system it is working fine But when i deployed to the aws linux system after the pdf gets converted to img its font changes. I tried manually uploading my specific font to server and specifying it in linux connfig config but still my server loads different font while converting pdf to img. this is the code i used, I doubt it will be of any use but still putting it down images= convert_from_bytes(pdf_content) # Save the first page of the image as PNG to BytesIO img_byte_arr = io.BytesIO() images[0].save(img_byte_arr, format='WEBP') # Set the BytesIO cursor position to 0 to read from the beginning img_byte_arr.seek(0) self.delete_pdf(f"/tmp/{self.user_id}_deal_or_order_receipt.pdf") return [img_byte_arr.getvalue(), img_byte_arr] can anyone tell if I am missing something? Really trying to figure it out from three days. -
displaying and processing a django form
I am newbie. I have some kind of online store. I need that after clicking on the buy button, which is located on the product page, the user is redirected to a page with a checkout form that contains the fields: phone number, mail and the product itself. URLS.PY from django.urls import path from first.views import productsHTML, productHTML, products_category, product_buy urlpatterns = [ path("productsHTML/<str:uuid>/buy", product_buy, name = "product_buy"), path("products_category/<str:id_category>", products_category, name = "products_category"), path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML"), ] FORMS.PY class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['email', 'phone_number'] widgets = { 'email': forms.EmailInput(), 'phone_number': forms.TextInput(), } VIEWS.PY def product_buy(request, uuid): if request.method == 'GET': product = Product.objects.get(id=uuid) form = OrderForm() return render(request, 'product_buy.html', {'product': product, 'form': form}) if request.method == 'POST': try: if form.is_valid(): product = Product.objects.get(id=uuid) email = form.cleaned_data['email'] phone_number = form.cleaned_data['phone_number'] order = Order.objects.create(email=email, product=product,phone_number=phone_number) return redirect('productsHTML') except: return render(request, 'productHTML.html', uuid = uuid) I use a construction try except so that in case of creating an order, the user is redirected to the page with all the products, and in case of failure: to the page of the product that he wanted to buy. PRODUCT_BUY.HTML {% extends 'products.html' %} … -
Can I used python programming for searchin rooms instead of javascripts
I am developing an Hotel booking website using django frameword how will created the search page can i used html value and pass to my view, or I will have to used javascript.(but I am not so good in js:|) I am expecting to used python and pass the html value in view.py files -
"TemplateDoesNotExist at /" django react webpack project
I have a Django React app integrated using WebPack. File structure as follows: |--CSP |--api /*django side*/ |--CSP |--Settings.py |--urls.py |--frontend /*react side*/ |--dist /*The template*/ |--index.html |--bundle.js |--src |--components |--App.js |--index.js |--styles.css |--tailwind.config.js |--postcss.config.js |--urls.py |--views.py |--webpack.config.js Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'frontend.apps.FrontendConfig' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 (frontend) from django.shortcuts import render # Create your views here. def index(request, *args, **kwargs): return render(request, '/csp/frontend/dist/index.html') urls.py (frontend) from django.urls import path from . import views urlpatterns = [ path('', views.index) ] webpack.config.js const path = require('path') var webpack = require('webpack'); module.exports = { mode: 'development', entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, devServer: { static: { directory: path.resolve(__dirname, 'dist'), }, port: 3000, open: true, hot: true, compress: true, historyApiFallback: true, }, module: { rules: [ { test: /\.css$/i, include: path.resolve(__dirname, 'src'), use: ['style-loader', 'css-loader', 'postcss-loader'], }, { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV' : JSON.stringify('development') }) ], } Both react and django work perfectly …