Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search by id not primary key not working django, no data is shown
I have one model and I want to search by patientid (not a primary key) when the id match the ids in the database list all the objects related to this id. I tried many ways but it is not working not showing anything when i search can someone tell me the issue ?? def search_bar(request): if request.method=='GET': searchbox=request.GET.get['searchbox'] if searchbox: prodctuts=Item.objects.filter(Name__icontains=searchbox) return render(request,'project/showData.html',{'prodctuts':prodctuts}) else: print("No information to show") return render(request,'project/showData.html',{}) Showdata.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'assets/css/external/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/external/normalize.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/external/all.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/showData.css' %}"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css'"> <title>Show Data</title> </head> <body> <!-- ---------------------------start navbar----------------- --> <nav class="navbar navbar-expand-lg "> <a class="navbar-brand" href="#"> <img src="{% static 'assets/images/logo/logo.png' %}" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav m-lg-auto"> <a href="#" class="close-icon d-lg-none"><i class="fas fa-times"></i></a> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Doctor</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Register <span … -
how can I change css Request url in nginx wit django
Below is my Nginx config location /static { alias /srv/django_site/mysite/static/; } when I approach www.mysite.com/admin browser request css file 'www.mysite.com/admin/css/~.css' But when I approach www.mysite.com browser request css file like below www.mysite.com/static/styles.css so I got 404 error. I want to change this request url like this www.mysite.com/static/home/static How can I fix this? Below is my url.py and settings.py urlpatterns = [ path('', include('home.urls')), path('accounts/signup', lambda requests: redirect('')), path('activate/', lambda requests: redirect('')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ### home/url.py urlpatterns = [ path('', views.MainView.as_view(), name = 'homepage'), STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Passing values to child class which inherits from PageNumberPagination from drf
I have to use PageNumberPagination (from drf) in many of my views, I used to define a custom class inheriting PageNumberPagination in each of my views.py, like - from rest_framework.pagination import PageNumberPagination class CustonmPageNumberPagination(PageNumberPagination): page_size = 3 page_query_param = "pageNumber" class MyViewSet(viewsets.ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() pagination_class = CustonmPageNumberPagination Now I'm trying to define a helper class in project level file and call this class whenever required. so my custompagination.py file is - from rest_framework.pagination import PageNumberPagination class CustomPageNumberPagination(PageNumberPagination): page_size = 3 page_query_param = "pageNumber" and then I can use it like - from backend.pagination import CustomPageNumberPagination class MyViewSet(viewsets.ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() pagination_class = CustonmPageNumberPagination But I also want to pass the value of page_size to my CustomPageNumberPagination whenever the class is called from my views, so as to get exact page size for each of my views. I understand class takes arguments in the init method so when I try something like class CustomPageNumberPagination(PageNumberPagination): def __init__(self, count): self.count = count page_size = 3 page_query_param = "pageNumber" and when trying to call this class pagination_class = CustomPageNumberPagination("gh") it gives an error 'CustomPageNumberPagination' object is not callable. Any help on how can I pass values? -
Django AuthenticationForm giving error "NameError: name 'UsernameField' is not defined"
I am trying to implement Login Form using AuthenticationForm , but I am getting error NameError: name 'UsernameField' is not defined, I dont understand , why it is giving this error. from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.contrib.auth.models import User class CustomerRegistrationForm(UserCreationForm): password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={"class":"form-control"})) password2 = forms.CharField(label="Confirm Password (again)",widget=forms.PasswordInput(attrs={"class":"form-control"})) email = forms.CharField(required=True,widget=forms.EmailInput(attrs={"class":"form-control"})) class Meta: model = User fields = ["username","email","password1","password2"] labels = {"email":" Email"} widgets = {"username":forms.TextInput(attrs={"class":"form-control"})} class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField(label=("Password"),strip=False,widget=forms.PasswordInput(attrs={"autocomplete":"current-password","class":"form-control"})) -
How to redirect to main page from any url
I've set up a link using an anchor tag which is connected to a template. Now when I click on the link I am redirected to (http://127.0.0.1:8000/blogpost/TopTenBestSellinggamesof2021) in which blogpost is the template and afterwards is the slug. And then when I go to the link of the navbar of the template to home I am directed to (http://127.0.0.1:8000/blogpost/index) but I want to go to (http://127.0.0.1:8000/index) instead. *My app's urls patterns - My app's urls patterns My project's urls patterns - My project's urls patterns I'm a beginner so I don't know much please help me I'm stuck at it for 2 hours!! -
How columns are connected in posgresql and data autopopulate in between tables?
I have to tables that I created through models.py in Django models and connect it to postgresql db. I have a common columns in two table Departments(DepartmentName) and Employees (Department) and say we want to add new row to Employees table. The thing that confuses me since those two columns are DepartmentName and Department are same how can we make sure when the new recors are generated in Employees table how the records are auto populated in Departments table? "models.py" from django.db import models # Create your models here. class Departments(models.Model): DepartmentId = models.AutoField(primary_key = True) # Autoincremented department id DepartmentName = models.CharField(max_length = 500) class Employees(models.Model): EmployeeId = models.AutoField(primary_key = True) # Autoincremented department id EmployeeName = models.CharField(max_length = 500) Department = models.CharField(max_length = 500) DateofJoining = models.DateField() PhotoFileName = models.CharField(max_length = 500) After inserting new records to Employees Table in postgresql table insert into public"Employees" values (1, 'Bob', 'IT', '2021-12-12', 'anonyms.png') Departments Table in when we inserted new records to So my questions are How can we connect those two tables when new records created in one of them the other gets populated with the data ? In this case DepartmentName data in Departments table. -
Does using/calling method having calculating queryset in another method hits the database multiple times
I'm working on a DRF project to learn about ContentType models. I created a post model and comment model(ContentType) and then added comments to the post. Everything was working fine until I added django-debug-tool and duplicated queries. I have the following questions: I've defined a method(children) and property(total_replies) on the comment model. Since total_replies just calling children method and count the size of queryset. Will it result in hitting the database two or more times in case I use the children method in some other methods or property? If the database is hitting multiple times, what solution two improve performance? After adding select_related the num of queries has been reduced drastically. Before using select_related After using select_related Is it good to use select_related at all places where Foreignkey has been used? Blog app models.py class Post(models.Model): title = models.CharField(verbose_name=_("Post Title"), max_length=50) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title @property def comments(self): instance = self #qs = Comment.objects.filter_by_instance(instance) #before qs = Comment.objects.select_related('user').filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type serializers.py class PostSerializer(serializers.ModelSerializer): author = UserPublicSerializer(read_only=True) status_description = serializers.ReadOnlyField(source='get_status_display') class Meta: model = Post fields = ( … -
Importing files modulenotfounderror
I have looked on multiple stackoverflow post but cannot find the answer. I have the following file structure i am also doing this in a django project crypto_api_site bitvavo_api bitvavowallet.py data.py main views.py Where data.py imports bitvavowallet.py and views.py imports data.py . But when executing python manage.py runserver I keep getting the error ModuleNotFoundError: No module named 'bitvavowallet' my import in views.py looks like this sys.path.append('crypto_api_site/bitvavo_api/') from bitvavo_api import data and my import in data.py looks like this import bitvavowallet.py Thanks in advance for any help -
Celery with rabbitMq and Django delay not working
I am using celery to send mails and that the execution is not in the main thread due to the high workload of this. Although I can send mail, when I try to use shared_task the function does not execute. When I check with celery -A myApp worker -l info what I get is that the userEmail task is received but there is not an output that is executed. What seems strange to me, following the documentation of celery is that it is not necessary to add any statement in settings.py How do I tell celery to use rabbitMq? init.py from .celery import app as celery_app __all__ = ('celery_app',) celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp.settings') app = Celery('myApp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Then there is a file call utils.py where there is this function: from celery import shared_task @shared_task(name="userEmail") def send_user_mail(randomNumber, email): subject = 'Validation' body="Your number is: "+str(randomNumber) send_mail(subject, body ,'xxxxxx.ssmtp@gmail.com', [email],fail_silently = False) return 1 -
How to take data from html with json to django
I cant make this work i want to take some data from html in a click of the button from html with json to django i dont want to use stripe. my html file `<form id="payment-form"> Billing address Emri klientit Emaili klientit Adresa Choose... {% for address in addresses%} {{address.address_line}} {% endfor %} Zgjidh nje nga adresat ose krijo nje te tille. ` my view `def add(request): basket = Basket(request) if request.POST.get('action') == 'post': order_key = request.POST.get('order_key') user_id = request.user.id baskettotal = basket.get_total_price() # Check if order exists if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name='name', address1='add1', total_paid=baskettotal, order_key=order_key) order_id = order.pk for item in basket: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response` -
How can I use paginator in search form in django
I'm trying to use paginator in my search form , everything works fine until I hit next page it shows a ValueError at /search/ views.py: def search_book(request): if request.method == "POST": searched = request.POST['searched'] # books = Book.objects.filter(title__contains=searched.upper()) paginator = Paginator(Book.objects.filter(title__contains=searched.upper()).order_by('title'),2) page = request.GET.get('page') books_list = paginator.get_page(page) return render(request,'search.html',{'searched':searched ,'books' : books_list}) else: pass form: <form class="search" action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search-box" id="search-book" type="text" placeholder="Search..." name="searched" > <input class="Search-button" type="submit" value="Search"> </form> -
forms.py can't validate proprely in django
def clean_name(self): valname = self.cleaned_data['name'] # if len(valname) < 3: # raise forms.ValidationError('name must be at least 3 characters') # return valname # return the value if no error if valname[0] == 'S': raise forms.ValidationError('name cannot contain the letter S') return valname # return the value if no error here I apply validation name that should start with S but when I enter a string that can't start with S so it will not give me Validation error. -
Django: Is there any way to acces the User models attribute using request.user.is_authenticated without hitting db?
I have created a middleware in which I have put some if conditions like, if request.user.is_authenticated and request.user.country: when I refresh the page my django debug toolbar shows me some duplicate and similar SQL queries that hits the DB while executing the middleware, so is there any way to access the attributes of the User model using the request.user without hitting the DB? -
AWS The request signature we calculated does not match the signature you provided
i linked s3 to my django app, but after uploading imagges from my website i try to access them i get this error The request signature we calculated does not match the signature you provided. Check your key and signing method. the images were uploaded succesfully to the bucket because i can already see them in the bucket dashboard but i can not access them through the website this is my CORS { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] -
No Category matches the given query
I am trying to update my products so users can create product and use the checkout to fill form for payment, but when i click on the checkout button i am getting this No Category matches the given query. Here is my code for the Order_create views def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() return render(request, 'products/products/created.html',{'order': order}) else: form = OrderCreateForm() return render(request, 'products/create.html') and here is the URLS for my projects urlpatterns = [ path('product/', include('products.urls', namespace='products')), ] and here is the Order URLS from django.urls import path from . import views app_name = 'products' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('create/', views.order_create, name='order_create'), ] When i clcick checkout, i got this error.... Page not found (404) No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/product/create/ Raised by: products.views.product_list -
Django Rest Framework API Performance
I have created an API I plan to list on RapidApi using Django Rest Framework and Heroku. This is my first time creating an API and I am wondering if there is anything I should be taking into consideration as far as performance goes. Do I need more worker dynos? If a lot of people are pulling data will it degrade my sites performance? Will data transfer be slow? I know this question really is opinion based but I am not sure as this is my first time. Thank you for your knowledge and help. -
IntegrityError at /users/create/ | NOT NULL constraint failed: users_post.author_id | Django Web App
I am following web app tutorials from codemy.com Youtube and CS50x. Now, I am trying to add a PostCategoryForm to my create function view for Post model in views.py. views.py def create(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse("users:login")) if request.method == 'POST': # create new post if request.POST.get('title') and request.POST.get('content'): form = PostCategoryForm(request.POST) form.save() post=Post() post.title = request.POST.get('title') post.content = request.POST.get('content') post.author = request.user post.category = form post.save() return HttpResponseRedirect("/users/posts/{id}".format(id= post.id)) else: form = PostCategoryForm() return render(request, 'users/create.html', { "form": form }) models.py class Post(models.Model): title = models.TextField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() category = models.CharField(max_length=255, default='uncategorized') post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('users:home') class PostCategory(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('users:home') forms.py choices = PostCategory.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class PostCategoryForm(forms.ModelForm): class Meta: model = Post fields = ['category'] widgets = { 'category': forms.Select(choices=choice_list) } is there any way to resolve this or should I change my view function to class view? Thanks in advance.. -
Django model field with switching type using Djongo
I want to create a Django model with one field being able to store multiple different types of data. E.g. from djongo import models class DataForms(models.Model): title = models.CharField(max_length=200) description = models.TextField(default=None) items = models.ManyToManyField(Item) class Item(models.Model): NUMERIC = "NUM" TEXT = "TEXT" BOOLEAN = "BOOL" DATE = "DATE" name = models.CharField(max_length=200) description = models.TextField(default=None) ITEM_TYPE_CHOICES = ( (NUMERIC, "Numeric value"), (TEXT, "Text or Characters"), (BOOLEAN, "Yes or No"), (DATE, "Date and Time") ) type = models.TextField( choices=ITEM_TYPE_CHOICES, default=TEXT value = ??????? Note that I am using djongo and a MongoDB at the backend so storing different types of values within the same document should not be an issue, right? In the end the user should be able to choose the type of item he or she wants to create and then add it to the data form. The value field should be either a models.FloatField() or models.TextField() and so on, depending on the choice the user makes. I thought about creating different types of classes inheriting from the Item class like: class NumericItem(Item): value = models.FloatField() And then creating instances of these classes based on the users choices. But it seems to me like this is unnecessary overhead. I … -
DJANGO - create a form that saves to different databases based on choices
I have a project to learn this langage : Create a website that allows their users to add books to a database. So a form with different data. And, according to a form data called "literary movement" the data books are registered in the literary movement category. Then have a page presenting all the literary movements and allow users to click on the different literary movements to have access to the books belonging to these literary movements. I already did the form but i really don't know how to save the data based on the choices of "literary movements". Theses are my codes : Forms.py from django.forms import ModelForm from django.utils.translation import gettext_lazy as _ from . import models class LivreForm(ModelForm): class Meta: model = models.Livre fields = ('titre', 'auteur', 'date_parution', 'nombre_pages','resume', 'mouvement_litteraire') labels = { 'titre' : _('Titre'), 'auteur' : _('Auteur') , 'date_parution' : _('date de parution'), 'nombre_pages' : _('nombres de pages'), 'resume' : _('Résumé'), 'mouvement_litteraire' : _('Mouvement Littéraire') } localized_fields = ('date_parution',) class MouvementForm(ModelForm): class Meta: model = models.Mouvement fields = ('mouvement_litteraire',) labels = { 'mouvement_litteraire' : _('Mouvement Litteraire') } Model.py from django.db import models mouvement_litteraire = ( ('','Nouveau Roman'), ('', 'Surréalisme'), ('','Symbolisme'), ('','Naturalisme'), ('','Réalisme'), ('','Romantisme'), ('','Lumières'), ('','Classicisme'), … -
Return session data from external microservice to Django
I am trying to link an external python script which is kind of like a function webscraping the other domain with the user login data sent from the django views. After the external script is sucessfully ran, the result data will be return back to the django views and show in the page. So far I can sucessfully done the above but as the external python script consist of a part of logging in an external domain and scrape the data. I want the logged-in session from the external script to be returned back to the django then the user can access the data from my page without needing to log in again. Here is my code This is my external python script which consist of using the Requests library def webscrape (email, pwd, dj_req): # use the data from django views to login the other domain and webscrape URL = 'www.login.com' payload = { 'name': email, 'pwd': pwd, } s = dj_req.session() #Trying to utilize the user's request data r1 = s.post(URL, data=payload) list1 = r1.text return list1,s #Return the logged-in session to django views This is my django view from ... import webscrape def inputdata(request): if request.method == … -
Django nested serializer get request shows value from an other model
I would like to create transactions with product quantities, I have this 3 models: class Products(models.Model): name = models.CharField(max_length=100) barcode = models.CharField(max_length=100) price = models.IntegerField(blank=True, default=1) quantity = models.IntegerField(blank=True) def __str__(self) -> str: return self.name class ProductCount(models.Model): barcode = models.ForeignKey( Products, null=True, blank=True, on_delete=models.CASCADE) transaction = models.ForeignKey( Transactions, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(blank=True, default=1) class Transactions(models.Model): staff = models.ForeignKey( Staff, blank=True, null=True, on_delete=models.CASCADE) services = models.ManyToManyField( Services, through='ServiceCount', related_name="transactions") products = models.ManyToManyField( Products, through='ProductCount', related_name="transactions") costumer = models.ForeignKey( Costumers, blank=True, null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) Serializers: class TransactionSerializer(serializers.ModelSerializer): products = ProductCountSerializer(many=True) services = ServiceCountSerializer(many=True) class Meta: model = Transactions fields = ('id', 'staff', 'products', 'services') def create(self, validated_data): product_data = validated_data.pop('products') validated_data.pop('services') transaction = Transactions.objects.create(**validated_data) for data in product_data: print(data) ProductCount.objects.create(transaction=transaction, **data) transaction.products.add(product_data) return transaction class ProductCountSerializer(serializers.Serializer): quantity = serializers.IntegerField() barcode = serializers.PrimaryKeyRelatedField( queryset=Products.objects.all()) # barcode = ProductSerializer() class Meta: model = ProductCount fields = ['barcode', 'quantity', 'transaction'] class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ('name', 'price', 'quantity', 'barcode') I do a post request on postman with this data: { "staff": 1, "products": [{"barcode":1 , "quantity":5}, {"barcode":1 , "quantity":3}], "services": [] } This works, but if I want to do a get request on transactions I get this … -
Django KeyError at 'HTTP_HOST'
In my Django project sometimes I get two kinds of errors by mail and I don't know where they are coming from. So far I can see, the user is not logged in. First kind of error: Internal Server Error: / KeyError at / 'HTTP_HOST' File "./core/views/iam.py", line 45, in prepare_django_request 'http_host': request.META['HTTP_HOST'], Exception Type: KeyError at / Exception Value: 'HTTP_HOST' Request information: USER: AnonymousUser Second type of error: Internal Server Error: / OneLogin_Saml2_Error at / SAML Response not found, Only supported HTTP_POST Binding File "var/www/schoolbox/venv/lib64/python3.6/site-packages/onelogin/saml2/auth.py", line 139, in process_response OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND Exception Type: OneLogin_Saml2_Error at / Exception Value: SAML Response not found, Only supported HTTP_POST Binding Request information: USER: AnonymousUser But users are able to login but, or maybe only some, I don't know where this error is coming from. Maybe I need to post more code in order to help me. Any help will be appreciated. -
DRF JSON format
I have created API for News model: models.py class News(models.Model): title = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = [ "id", "title", "created_at", ] views.py class NewsViewSet(ModelViewSet): serializer_class = NewsSerializer queryset = News.objects.all() The current result of this API which is below: [ { "id": 1, "title": "testing1", "created_at": "2022-04-02T16:05:08.353708Z", } ] And my question is there any ways to change the response format like below? I can not figure out how to make with Django DRF. { "status": 0, "message": "Success", "data": { "updatedAt": "2020-08-31 17:49:15", "serverTime": "2022-03-23 15:10:11", "news": [ { "id": 1, "title": "testing1", "created_at": "2022-04-02T16:05:08.353708Z", } ] } } -
after login django-allauth login page doesn't show good?
On my django project,I added django-alluth for google login.But after click google login button in my login.html,the page which will login is: after I clicked continue button google login the page is shownn at the bottom: I want to from here,At my login template when I clicked to login with google button directly second piture will be shown.How can I do that? Because first picture doesn't look good.I want to directly jump the other image. -
React fetch request is blocked by Django backend due to "origin forbidden"
I have a Django view that processes a contact message which I want to call via a fetch request from my React frontend. However, it returns the following error: Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /send-contact-message/ # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'applications.api', 'applications.core', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] I also tried CORS_ORIGIN_ALLOW_ALL = True which returns the same error. ContactForm.js const ContactForm = () => { const [formData, setFormData] = useReducer(formReducer, {}); const [submitting, setSubmitting] = useState(false); const submitHandler = event => { event.preventDefault(); setSubmitting(true); fetch('http://127.0.0.1:8000/send-contact-message/', { method: 'POST', body: JSON.stringify({ formData }), headers: { 'Content-Type': 'application/json' }, }) .then(res => res.json()) .then(json => setSubmitting(false)); } ...