Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update item quantity on django ecommerce project
I am trying to update the quantity of my cart when I use click the add to cart button. I have been trying to figure out the logic behind it but cannot seem to get it. I believe under my views.py I am adding an item to the cart but it is not working. Can anyone give me some direction on this? main.Html <button href="{% url 'add_cart'%}" class="btn btn-primary add-cart">Add to Cart</button> urls.py urlpatterns = [ path('add_cart', views.add_cart, name='add_cart') ] Views.py def add_cart(request, slug): product = get_object_or_404(Product, slug=slug) item = Item.objects.create(product=product) order = Order.objects.filter(user=request.user, ordered=False) if order.exists(): order = order[0] if order.items.filter(item_slug=item.slug).exists(): item.quantity += 1 item.save() else: order = Order.objects.create(user=request.user) order.items.add(item) return redirect('main') models.py class Product(models.Model): img = models.CharField(max_length=30) product_name = models.CharField(max_length=250, null=True) price = models.CharField(max_length=250, null=True) description = models.TextField() slug = models.SlugField() def __str__(self): return self.product_name class Shopper(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=250, null=True) email = models.CharField(max_length=250, null=True) def __str__(self): return self.name class Order(models.Model): shopper = models.ForeignKey( Shopper, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) trans_id = models.CharField(max_length=250, null=True) ordered = models.BooleanField(default=False) def __str__(self): return str(self.trans_id) @property def cart_total_items(self): total_items = self.item_set.all() cart_total_items = sum([item.quantity for item in total_items]) return cart_total_items def cart_total(self): total_items = … -
How to float text in the input box in javascript?
I want to text the code I wrote in JavaScript into the input box. However, there is a problem that the input box is not outputting text. The input box I want to print is in html. The content is as follows: <input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원 Is there a problem with my source code? I wonder why the text doesn't appear. Wise developers, please help me solve this problem I'm facing. script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('.item_price').getElementsByClassName("item_price").text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString()); } html " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원\n" + " </div>\n" + **All Sourcecode ** <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = parseInt($(this).find(':selected').data('price')); var hapgae = price + test if (checkValue … -
Is there a way to prevent Django from trimming leading white space in a text field?
Is there a way to prevent Django from trimming leading white space in models.TextField? I've been scouring the docs and haven't found anything. The database I'm using is PSQL. Any guidance would be appreciated. -
Is there a better way to get the created object?
I have this code and I want to store this created user and question in a variable in one line instead of doing it this weird way, is this even possible?: if UserProfile.objects.filter(discord_id=request.data['author_id']).exists(): profile = UserProfile.objects.get(discord_id=request.data['author_id']) else: x = UserProfile.objects.create(discord_id=request.data['author_id'], name=request.data['name']) profile = UserProfile.objects.get(discord_id=request.data['author_id']) Question.objects.create(title=request.data['title'], author=profile, points=int(request.data['points'])) question = Question.objects.filter(author=profile, title=request.data['title'])[0] -
Django duplicated query causing slow loading
I'm having trouble finding a solution for duplicated queries, I tried doing this. Code: for c in coupons: fname = Users.objects.filter( id=c['WhoReviewed']).values('first_name') lname = Users.objects.filter( id=c['WhoReviewed']).values('last_name') for f in fname: first = f['first_name'] for l in lname: last = l['last_name'] full = first + ' ' + last c['WhoReviewed'] = full Result: -
How to fix NoReverseMatch error in Django for the getting and displaying user specific data in ListView
Hey I have a video sharing webapp project with basic CRUD operations in it. Any user after successful login can post any number of videos and after login the user is redirected to home page of another app inside the django project. Home page shows all the videos uploaded by different users. Now I want place all the videos uploaded by the user at an seprate endpoint. If user clicks on this endpoint link in the nav-bar then the user should be directed to this endpoint containing all the videos uploaded by him/her. I am using builtin class based view ListView for this purpose and I have just one model of Video. But I am getting Noreversematch error after performing get_queryset() function and here is my error : part of views.py class UserUploads(LoginRequiredMixin, ListView): model = Video template_name = 'courses/user_uploads.html' context_object_name = 'videos' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Video.objects.filter(uploader=user).order_by('-date_time') def get_success_url(self): return reverse('courses:video-detail', kwargs={'pk': self.object.pk}) part of urls.py from django.urls import path, include from django.contrib import admin from . import views from .views import CreateVideo, DetailVideo, UpdateVideo, DeleteVideo app_name = "courses" urlpatterns = [ path('', views.Index.as_view(), name = "home"), path('user-uploads/<str:username>', views.UserUploads.as_view(), name = "user-uploads"), path('create-video', CreateVideo.as_view(), name='video-create'), path('<int:pk>/', … -
how to display list of LANGUAGES in django template
i'm trying to show languages label list in my template , but it only shows the original name of the language my settings.py LANGUAGES = ( ('en', _('english uk')), ('ar', _('arabic uae')), ('fa', _('Persian')), ) my template <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="fas fa-globe"></i> </a> <div class="text-center dropdown-menu dropdown-menu-lg dropdown-menu-right"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <a class="dropdown-item" href="/{{lang.code}}/"> {{lang.name_local}}</a> {% endfor %} </div> </li> is it possible please ? thank you for helping .. -
dynamic form in django using choiceField
I'm building my first web app with django and am having a hard time figuring out how to use dynamic form in order to have diffent output for different selected choice. for example for my mesure choice qualitative, I want the form be the same(no extra fields) but if the quantitative value is selected, I want my template to show tow more fields(value_min and Value_max) the first option when qualitative value is selected the second option when quantitative value is selected thank you for your help... -
How to get users back after deploying Django App to Heroku
I've deployed a React/Django app on Heroku and when I tried to login, I found out none of the users I had locally were present on the deployed App. I thought it could be that it didn't migrate so I did heroku run python manage.py makemigrations heroku run python manage.py migrate Got no migrations to apply so I now have an app without an Admin account and I don't know how I could create one nor access the one I had locally Ps: I'm using Sqlite database on it -
Filter objects of a manytomanyfield inside another model
I am a beginner programming learning django. I'm trying to build a contacts app much like google contacts. users have to log in to create contact groups and contacts. problem: when a user creates a group, it shows up in the form field for a different user. How do I restrict groups created by a user to only that user. Models.py from django.db import models from django.contrib.auth.models import User from uuid import uuid4 class Group(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, unique=True, editable=False) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, editable=False) group_name = models.CharField(max_length=255, verbose_name="Group Name") def __str__(self) -> str: return str(self.group_name) class Contact(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, unique=True, editable=False) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, editable=False) first_name = models.CharField(max_length=256, verbose_name='First Name', blank=True, null=True) last_name = models.CharField(max_length=256, verbose_name='Last Name', blank=True, null=True) other_names = models.CharField(max_length=256, verbose_name='Other Names', blank=True, null=True) nick_name = models.CharField(max_length=256, verbose_name='Nickname', blank=True, null=True) phone = models.CharField(max_length=256) groups = models.ManyToManyField(to=Group, null=True, blank=True) views.py from rest_framework import viewsets from rest_framework import permissions from django.contrib.auth.models import User from contacts.models import Group from contacts.models import Contact from contacts.serializers import GroupSerializer from contacts.serializers import ContactSerializer from contacts.serializers import UserSerializer class GroupView(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class = GroupSerializer def get_queryset(self): return Group.objects.all().filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) class ContactView(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class … -
How to change permission in Django view sub-class?
I have the following setup right now: class MyView(MyPermission1, MyPermission2, FormView): ... class MyChildView(MyView): ... The child view is inheriting from the parent, but I want to remove MyPermission1 and MyPermission2 from it and apply another class called MyPermissionChild. Is there a way to do this using the generic views available in Django? -
How to get the value of the foreign key field and count or other aggregation operations?
I have two models. How can i count and show results like below: Male 235 Female 240 Other 10 My models.py class student(models.Model): name = models.CharField(max_length = 200) gender = models.ForeignKey(gender, on_delete = models.SET_NULL, null = True, blank=True) def __str__(self): return '%s' % (self.name) class gender(models.Model): title= models.CharField(max_length = 200) def __str__(self): return '%s' % (self.title) My views.py def viewlist(request): mylist = student.objects.values('gender').annotate(total=Count('gender')).order_by('-total') -
Django render field json in template
i'm doing a project using the Django 3.1.2, this project needs a register logs. I created a model for logs: class Log(models.Model): Usuario = models.CharField('Usuário que fez a ação', max_length=100) Perfil = models.SmallIntegerField( 'Quem está sofrendo a ação', choices=PERFIL_CHOICE) Acao = models.CharField('Tipo de Ação Realizada', max_length=2, choices=ACAO_CHOICE) Resultado = models.JSONField('Resultado', null=True, blank=True) Processando = models.BooleanField('Processando', default=True) TituloProcesso = models.CharField( "Titulo do Processo", max_length=100, null=True, blank=True) DataAcao = models.DateTimeField('Data da Ação', auto_now_add=True) The model log has field "Resultado" that is of type JSONField, this field is working correctly. The data that is save in the field, is dynamic, so the json keys and values will not always be the same, so i needed it easier to dysplay this field in template. I was looking the "django-jsonfiel", not work in Django 3.1 Does anyone know any way to display this field already formatted dynamically? -
Pass parameters in URL to Django Admin add_view
I need to pass a parameter in the URL to the Django Admin add view, so that when I type the URL: http://localhost:8000/admin/myapp/car/add?brand_id=1, the add_view reads the brand_id parameter. I want to use this so that I can set a default value for the brand attribute of Car. def get_form(self, request, obj=None, **kwargs): form = super(CarAdmin, self).get_form(request, obj, **kwargs) form.base_fields['brand'].initial = <<GET['brand_id']>> return form Use case: I want this because in my BrandsAdmin, I have added a "+" button for each brand, that should add a Car with that Brand as FK. I've tried getting it from request in get_form, but when that code is executed, Django has already changed my URL as I guess it doesn't understand it as a "legal" parameter. Thanks a lot! -
How to serialize tthe foreign key field in django rest framework
I working on project with drf where I'm getting serializer data as follows which is absolutely fine: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": 2, "item": 1, "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } but I want to get as following: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": "user name", "item": "product name", "price: "3.44", "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } I tried using drf RelatedField and PrimaryKryRelatedField but in all these cases I need to make corresponding fields as read_only=True which I want to skip. Please if anyone can help, it would be greatly appreciated. Thanks -
Django render many to many attributes after query, display None
I am using slug to query the model, and render result in HTML. The code is unable to render actual name of region, it just return None Model class Region(models.Model): name = models.CharField(blank=False, unique=True) def __str__(self): return self.name class Theme(models.Model): name = models.CharField(blank=False, unique=True) slug = models.SlugField(default="", null=False) def __str__(self): return self.name class ETF(models.Model): ticker = models.CharField(max_length=6, blank=False, db_index=True, unique=True) full_name = models.CharField(max_length=200, blank=False) # many to many region = models.ManyToManyField(Region) theme = models.ManyToManyField(Theme) views.py def theme_etf(request, slug): # render ETFs with theme filter filtered_results = ETF.objects.filter(theme__slug=slug) return render(request, "etf/list_etf.html", { "ETFs": filtered_results }) Part of list_etf.html {% for ETF in ETFs %} <tr> <td>{{ ETF.ticker }}</td> <td>{{ ETF.full_name }}</td> <td>{{ ETF.region.name }}</td> # What should I use in this line </tr> {% endfor %} The code is unable to render actual name of region, it just return None Result | Ticker | Name | Region | | -------| -------------------------- |------- | | ARKF | ARK Fintech Innovation ETF |None | | ARKK | ARK Innovation ETF |None | | KEJI |Global X China Innovation |None | I would like to have this: | Ticker | Name | Region | | -------| -------------------------- |------- | | ARKF | ARK Fintech … -
Build MultipleChoiceField form based on view request with Django
I have a table named Appointment with : timeslot id ; student id; teacher id ; date ; timeslot (integer) ; I would like to create multiple rows in the table TimeSlot based on MultipleChoiceField form. But the choice of slot at a certain date is depending of the value in the table. For example, if there is a timeslot at a certain date, the choice for this timeslot to this date will not be displaying to the client. This is my code : TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '09:30 – 10:00'), ) class ChooseAvailabilities(forms.Form): timeslot= forms.MultipleChoiceField( required=False, widget=CheckboxSelectMultiple, choices=TIMESLOT_LIST ) class Appointment(models.Model): teacher = models.ForeignKey(Teacher, null = True, on_delete = models.CASCADE) student = models.ForeignKey(Student, null=True, blank = True, on_delete=models.CASCADE) date = models.DateField(null = True) timeslot = models.IntegerField(null = True) In the view, I want to call the ChooseAvailabilties form with a certain date in parameter so that the form is checking if there are overlapping date or timeslot in the Appointment table to not show the timeslot in which there are overlappings but only available timeslots to this date. Something like where I can choose the timeslots. Then the selected timeslots are stored in the Appointment … -
how not allow users to download files in Django
I'm building and online course web application. Is there any way to prevent users not to be able to download video or audio files in Django? -
Django celery - Restart the task when it's completed
@app.task def Task1(): print("this is task 1") return "Task-1 Done" Just take an example I want to restart the task when it's completed -
How to fix heroku app deployment? App runs locally but not online
I'm trying to deploy a dog breed classifier django app on heroku, but for some reason heroku doesn't seem to find the path to the exported pkl model file. Whenever I run locally, everything works fine. I'm using the "path" module's "exist()" method to check for the presence of the file first before importing the module, hence the reason for the exception thrown. Here's the stack trace for the error: Environment: Request Method: GET Request URL: https://mydogbreed.herokuapp.com/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', 'corsheaders', 'frontend'] Installed Middleware: ['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', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 556, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, … -
Is there a workaround for Django's `ModelDoesNotExist` error in a situation like this?
So I get a ModelDoesNotExist error when I run manage.py runserver because in a file in my directory, I make a query to a table which has not been populated yet. def __init__(self): self.spotify_object = SocialToken.objects.get(account__provider="spotify") The above is a class instantiated to perform some sort of authentication and the SocialToken table gets populated only after I login. Now, I was wondering if there was a way to escape the error by triggering this part of the code only after I login? I only use the class in an endpoint, and during that period, the table would have been populated but the fact that it is not populated before running the server is causing a DoesNotExist error. Is there a solution to this? Traceback File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\views.py", line 4, in <module> from .authentication import SparisonCacheHandler File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 43, in <module> cache_handler = SparisonCacheHandler() , File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 25, in __init__ self.spotify_object = SocialToken.objects.get(account__provider="spotify") File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site- packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site- packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( allauth.socialaccount.models.DoesNotExist: SocialToken matching query does not exist. In my views.py, I import the class which has the query and the error comes … -
How to display text in input in javascript?
I'm trying to save a price, but the price text doesn't appear in the input box. Where is the problem? How can I save the price? view price = form.cleaned_data['price2'] form price2 = forms.IntegerField(error_messages={'required': "1개 이상 선택 시 참여가 가능합니다."}, label="가격") script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('.item_price').text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString()); } ddd <div class="cart_total_price"> <h2 style="font-size: 25px;"><p style="font-size: 19px; margin-top: 35px; margin-bottom: -25px;"><b>총 가격</b></p> <input class="item_price" style="margin-left: 220px; font-size: 23px; margin-bottom: 20px;" name="price2" id="price2" value="0"><span style="font-size: 23px;">원</span></p></h2> </div> -
How can we keep only delete operation in django-simple-history
We can keep the history of insert/update/delete operation in any table with django-simple-history in a Django Application. Is there any setting or configuration to keep only the history of deletion operation in a table with django-simple-history? -
Replace html web page by ajax return data on Django 3.2
I managed to use ajax to change the content of my web page without updating it but the only problem is that I cannot replace the old content with the new one which I return, when I do consol.log (data ) I have the new html, but I can't change it for the user Ajax for send the form <script> $(function() { $("#show_type").submit(function(event) { // Stop form from submitting normally event.preventDefault(); let friendForm = $(this); // Send the data using post let posting = $.post( friendForm.attr('action'), friendForm.serialize() ); // if success: posting.done(function(data) { console.log(data) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< new html window.alert("success action"); // success actions, maybe change submit button to 'friend added' or whatever }); // if failure: posting.fail(function(data) { window.alert("fail action"); // 4xx or 5xx response, alert user about failure }); }); }); </script> Google chrome new html in console log: its that html i whant display in browser but i dont know how <div class="grid-container"> <div class="grid-item" start_at="10 août 2021 12:46" end_at="10 août 2021 17:45"> <span class="device-title">Dispositif nostart [ID]: C23</span> <div class="device-info"> <span class="left-text-icon map">Lieu: HIDE</span> <span class="left-text-icon start">Début: 10 août 2021 12:46</span> <span class="left-text-icon end">Fin: 10 août 2021 17:45</span> <span class="left-text-icon chief-go">Chef GO: cdcd chieffunc</span> <span class="left-text-icon dchief-go">Adjoin-Chef GO: did … -
Bad Request 400 - Django REST Framework
I have my api in Django and Django REST framework (DRF). Here is my settings file: DEBUG = False ALLOWED_HOSTS = ['http://localhost:3000', 'http://127.0.0.1:3000'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'MyApp.apps.MyappConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSESS': 'rest_framework.permissions.AllowAny', } # React's Port : 3000 CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ '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', 'corsheaders.middleware.CorsMiddleware', ] I am getting Bad Request (400) Error: I inspectd Chrome's network tab, here is what I got: Request URL: http://localhost:8000/api/list Request Method: GET Status Code: 400 Bad Request Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin Connection: close Content-Type: text/html Date: Wed, 11 Aug 2021 13:05:24 GMT Server: WSGIServer/0.2 CPython/3.8.1 X-Content-Type-Options: nosniff Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cache-Control: max-age=0 Connection: keep-alive Host: localhost:8000 sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92" sec-ch-ua-mobile: ?1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: none Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36 In React, I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/list/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. What is the …