Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why html buttons dynamically created by django cannot access my javascript function?
My Django application makes divs dynamically. Each div is a post of a blog post and also I have a like button on each div. Each button will automatically turn into unlike when a user clicks on it without reloading using javascript. I wrote a javascript function for this. Unfortunately, my javascript function works only the last post on a page (As I have pagination property). document.addEventListener("DOMContentLoaded",function(){ // const colon = document.createElement('div'); // colon.setAttribute('id','colon') // e.preventDefault() // const likebtn = document.createElement('button'); // likebtn.setAttribute('class','likebtn btn btn-primary'); // likebtn.setAttribute('class','likebtn'); // document.querySelector('.card-footer').appendChild(likebtn); // document.querySelector('.likebtn').innerHTML = "Like"; document.querySelector(`#likeform${posts_id}`).addEventListener('submit',(event) => { event.preventDefault(); like_function(); // return false; }) // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost')); }) // let is_like = "{{is_like}}"; // let num_like = "{{num_like}}"; function like_function(){ // document.createElement('button').innerHTML = "Love"; // console.log("Updated!") fetch(`/like/${posts_id}`,{ method:"POST", body : JSON.stringify({ "is_like" : is_like, "num_like" : num_like, }) }) .then(response => response.json()) .then(result => { if(result.is_like){ console.log("function is liked"); console.log(`${result.is_like} for post ${posts_id}`); let num_like = result.num_like; console.log(`Number of posts : ${num_like}`); document.querySelector(`#likebtn${posts_id}`).innerHTML = "Unlike"; num_like = num_like + 1; console.log(`Number of posts : ${num_like}`); document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} ` // location.replace("http://127.0.0.1:8000") } else{ console.log("function is unliked, back off!"); console.log(`${result.is_like} for post ${posts_id}`); let num_like = result.num_like; console.log(`Number of posts : ${num_like}`); … -
django pytest how to test a view with argument(id)
i have a question regarding using pytest. These are my very 1st tests. I have 2 views which i want to test (simplest possible way). Views: class MenuView(View): def get(self, request): return render(request, 'diet_app/menu.html') class CuisineDetailsView(View): def get(self, request, id): cuisine = Cuisine.objects.get(id=id) recipes = cuisine.recipe_set.all() return render(request, 'diet_app/cuisine_details.html', {'cuisine': cuisine, 'recipes': recipes}) Here are my tests: def test_menu(client): url = reverse('menu') response = client.get(url) assert response.status_code == 200 @pytest.mark.django_db def test_cuisine_details_view(client): url = reverse('cuisine-details') response = client.get(url) assert response.status_code == 200 Urls: path('menu/', MenuView.as_view(), name='menu'), path('cuisine_details/<int:id>/', CuisineDetailsView.as_view(), name='cuisine-details'), 1st test (menu view) is working properly 2nd test (cuisine details view) shows error .NoReverseMatch: Reverse for 'cuisine-details' with no arguments not found. 1 pattern(s) tried: ['cuisine_details\\/(?P<id> I know i should probably put somethere ID argument but tried few options and havent succeed. Will be grateful for any help/advise -
why is group a wrong alias in postgres + Django for auth_group table
Why is that the following simple query does not work (Using Django in the backend) # select group.name from auth_group as group; ERROR: syntax error at or near "." LINE 1: select group.name from auth_group as group; while the following works # select groupd.name from auth_group as groupd; name --------------- FO Admin Role admin alice bob (4 rows) What is wrong with using group as an alias ? -
Is there a default route in case of any invalid url in django?
I am not an expert on Django. I came across for the invalid url a lot in django. is there any defualt route to be configured instead of showing nothing or showing error page while debuging. like, we might configure one route that redirects in any case of invalid url or not data found or ... Hope i explained and made my point clear. -
How to install pyodbc on Dockerfile
I'm trying to install pyodbc on Django to access Sql Server but the Docker image had no be built. I get the error: => ERROR [16/16] RUN pip install --no-cache-dir -r requirements.txt 155.7s ------ > [16/16] RUN pip install --no-cache-dir -r requirements.txt: ... #20 93.38 Building wheels for collected packages: pyodbc, dj-static, static3, django-ckeditor, odfpy, anyjson, django-celery, pyftpdlib #20 93.38 Building wheel for pyodbc (setup.py): started #20 96.49 Building wheel for pyodbc (setup.py): finished with status 'error' #20 96.49 ERROR: Command errored out with exit status 1: #20 96.49 command: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/setup.py'"'"'; __file__='"'"'/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-_ty0puya #20 96.49 cwd: /tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/ #20 96.49 Complete output (13 lines): #20 96.49 running bdist_wheel #20 96.49 running build #20 96.49 running build_ext #20 96.49 building 'pyodbc' extension #20 96.49 creating build #20 96.49 creating build/temp.linux-x86_64-3.8 #20 96.49 creating build/temp.linux-x86_64-3.8/tmp #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138 #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src #20 96.49 gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPYODBC_VERSION=3.0.10 -DPYODBC_UNICODE_WIDTH=4 -DSQL_WCHART_CONVERT=1 -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include -I/usr/local/include/python3.8 -c /tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src/sqlwchar.cpp -o build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src/ sqlwchar.o -Wno-write-strings #20 96.49 gcc: … -
Cannot upload file to azure blob starage in Azure django app service
My django server was 1st time deployed to azure last autumn and after half year it suddenly stopped working. (It is still possible the there has been pipeline executions using different branches meanwhile). However when running the django server from on-prem host (i.e. using the same environment variables AZURE_ACCOUNT_NAME and AZURE_ACCOUNT_KEY) I can download and upload files from and to container's media directory 'poytakirjat'. But when running the code in azure I can just download files, but not upload into media directory 'poytakirjat'. When I try to upload something I get just Http error 502 and nothing else even tough I had DEBUG set to True. I don't even know how to get some log files. models.py: from django.db import models from custom_azure import AzureMediaStorage import datetime from html.parser import HTMLParser from tinymce import models as tinymce_models from django.core.mail import send_mail from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Tiedostot3(models.Model): otsikko = models.CharField(max_length=250) kuvaus = RichTextField(blank=True) paivitetty = models.DateTimeField(auto_now_add=True, verbose_name="Päivitetty") tiedosto = models.FileField(upload_to='poytakirjat', storage=AzureMediaStorage(), verbose_name="Tiedosto", blank = True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) class Meta: ordering = ['-paivitetty'] verbose_name = "tiedosto" verbose_name_plural="tiedostot" def __unicode__(self): return unicode(self.otsikko) class Liite3(models.Model): otsikko = models.CharField(max_length=250) tiedosto = … -
csrf missing error but csrf token is present there i have checked it by inspecting it it is happen in cpanel deployment
Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. More information is available with DEBUG=True. In my django project when i deploy it to c panel its form submission giving me error i have already inclued the csrf token and also it is working perfectly fine during the development i did some research they were talking about the render function i have used redirect and i had to use -
How to use pytest third-party fixtures in my tests?
I am using postmarker in a Django project to send emails. I am using Pytest for testing, and I would like to mock all outgoing emails that I am sending using Postmarker. I found in Postmarker documentation indication for some predefined Pytest fixtures to do so, but I am not sure how I can use them in my Unit tests. Here is the source code of said Pytest fixtures: https://github.com/Stranger6667/postmarker/blob/master/src/postmarker/pytest.py I've ended up just copying those Pytest fixtures code with the mock statements, but was wondering if there is a cleaner way of using them. -
Is there any python library to plot a static map with a specific country in Django?
I have previously used some python libraries like folium, matplotlib etc. These libraries render nice, dynamic maps in Django template, but take a lot of time to load. Also, I want the static map for a specific country where places can be marked with their respective latitudes and longitudes. The map should be something like this: So, is there any python library that renders static maps in Django template with relatively less loading time than those by folium, matplotlib? -
Python Return a Variable in the file
I have tuple variables which are France, Germany. I'm trying to give a value to my bring_cities function and if it's France or Germany, I like to see the France and Germany tuple objects. Is there any shortcut to not use if loops like I did in the below ? France = ( ('Paris', 'Paris'), ('Lyon', 'Lyon'), ) Germany = ( ('Frankfurt', 'Frankfurt'), ('Berlin', 'Berlin'), ) cities = (('', ''),) + France + Germany def bring_cities(country): if country == 'France': return France if country == 'Germany': return Germany ... -
Django: get all permissions on template separated by groups
I have an admin site, I want to edit and add roles to it. It looks like this I can get all the permissions using the POST method by calling every name but I have many permissions and groups. But by using that I can only save one group at a time. Is there a way to get the permissions separated by groups when the save button was clicked? For example: {'Super Admin':['permision1','permision2'], 'Admin':['permision1'], 'CSM':['permision2]} -
Defaultlist in Django
I used defaultlist in my Django App but my output is not good .html {% for key, value in results.items %} <tr> <td>{{ item.key }} </td> <td>{{ item.value }} </td> </tr> {% endfor %} my output: defaultdict(<class 'list'>, {'List of auto blue': ['wolss', 'jaguar', 'bmw', 'tys', 'toyota', 'List of auto red': [jwdwoi, dede, dsd, dsa]}) views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df =results1(file_directory,file_directory2) return render(request,"results.html",{"results":results,"output_df":output_df,}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) if d> t: results_list["List of bleu auto :"].append(s_id) if len(p_index) > 1: results_list["List of red auto:"].append(s_id) results_list what is wrong please ? How i can give an output like this : List of auto blue: -wolss -jaguar -bmw -tys -toyota List of auto red: -jwdwoi -dede -dsd -dsa -
Black formatter in does not work correctly
i work in Django project and in it we use Black formatter but i have problem with this .we have a 'pyproject.toml' file like this picture but with configuration black does not work and i have this error Usage: black [OPTIONS] SRC ... Try 'black -h' for help. Error: Invalid value for '--exclude': Not a valid regular expression: bad escape \e at position 68 (line 7, column 5) but when i delete line 4-18 it work correctly (when i delete exclude part ).what is wrong in exclude part ?can anyone help me? thanks a lot -
Upload images/files in user specific folder in Django
I want to upload images in a folder ( Where folder name is currently logged in username). I am using django login forms. for example: currently user is logged in as 'user99'. now i gave functionality where he can upload his images. and when he upload a image, this should save in my local system in his username folder i.e user99. uploaded image- demo.jpg target dict - Media/user99/01-02-2022.jpg In model.py instead of using instance.title , I want to use instance.user. but when i do that i am getting this error. mysite.models.Image.user.RelatedObjectDoesNotExist: Image has no user. Django version 2.2.5, Python 3.7.11, Please guide me. Thank you my model.py is: def upload_path(instance,title): today = str(date.today()) name = instance.user return f'{name}/{today}.jpg' class Image(models.Model): title = models.CharField(max_length=20, choices=CROP_CHOICES) image = models.ImageField(upload_to=upload_path, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.title and views.py is: def upload(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() img_obj = form.instance return render(request, 'mysite/upload.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'mysite/upload.html', {'form': form}) forms.py : class ImageForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'image') -
KeyError: at 'role_type' while using request.session in Django 3.0
I am trying to fetch role_type when user is login to the server , when user login immediately i am getting this issue Here i am using Django 3.0 and python 3.7 Here is my views.py def get_context_data(self): dashboard_data = {} is_worker = self.request.session['role_type'] in [ 'Job Worker', 'Job Worker with documents'] dashboard_data['is_worker'] = is_worker ... ... return dashboard_data here is my error traceback Traceback (most recent call last): File "/home/abc/xyz/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/abc/xyz/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abc/xyz/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abc/xyz/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/abc/xyz/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/abc/xyz/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/abc/xyz/lib/python3.7/site-packages/django/views/generic/base.py", line 158, in get context = self.get_context_data(**kwargs) File "/home/abc/test/dev-1.8/mcam/server/mcam/dashboard/views.py", line 116, in get_context_data is_worker = self.request.session['role_type'] in [ File "/home/abc/xyz/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 64, in __getitem__ return self._session[key] KeyError: 'role_type' How could i solve this error -
Queryset Many to many 'ManyRelatedManager' object is not iterable
I'm using Forms to filter the choices of a many to many relationship to only show the ones following a queryset. This is how my Form looks like class ContractAdminForm(forms.ModelForm): class Meta: model = Contract fields = '__all__' def __init__(self, *args, **kwargs): super(ContractAdminForm, self).__init__(*args, **kwargs) self.fields['client_year_periods'].queryset =ClientYearPeriod.objects.filter( Q(contract_id__isnull=True) | Q(contract_id=self.instance.id) & Q(client__in=self.instance.client_entity)) Error: 'ManyRelatedManager' object is not iterable The issue is being caused by Q(client__in=self.instance.client_entity)) I need to filter the model years using the client legal model that is connected to Client Ops. See here how is it built [ Models class ClientLegal(models.Model): name = models.CharField(max_length=350, verbose_name='Client Name') countries = models.ManyToManyField(Country, blank=True) operations_code = models.ManyToManyField(Client) class ClientYearPeriod(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT, null=True) [...] class Contract (models.Model): legal_client= models.ManyToManyField(ClientLegal) client_year_periods = models.ManyToManyField(ClientYearPeriod, blank=True) [...] class Client(models.Model): code = models.CharField(max_length=3, verbose_name='Client Code') name = models.CharField(max_length=250, unique=True) -
"Page undefined of undefined" in the pdf using the wkhtmltopdf library
i have used the wkhtml2pdf library, I want to set the numbering of page on my pdf But i didn't reach my goal yet, it always show me "Page undefined of undefined", Here is the code i have go to tag head and make this properties for the div contain the number of pages: <style> div.footer { display: block; text-align: center; position: running(footer); @page { @bottom-center { content: element(footer) } } } </style> then in the body, I have go and add the div with javascript code: <body style="border:0; margin: 0; min-height: 1123px"> <div id="div-body"> #code </div> <div class='footer'> Page <span id='page'></span> of <span id='topage'></span> <script> var vars={}; var x=window.location.search.substring(1).split('&'); for (var i in x) { var z=x[i].split('=',2); vars[z[0]] = unescape(z[1]); } document.getElementById('page').innerHTML = vars.page; document.getElementById('topage').innerHTML = vars.topage; </script> </div> </body> How i can resolve that, thanks in advance. -
How to convert django.utils.timezone.now() into iso 8601 format string?
2022-02-20T06:07:00-0700 What type of date format is it and how to convert django.utils.timezone.now() to this format? -
there a way to use count on single forloop in django template
Hi I want to know how many elements there are numerically within each cycle I do. I tried {{forloop.counter}} but the problem is that they are not in order but scattered. is there a way to use count on single forloop ie dayone? {% if integratori %} {% for dayone in integratori %} {% if giorno >= dayone.inizio and giorno <= dayone.fine %} <h4 class="text-danger">{{ dayone.count }}</h4> <!-- {% if forloop.counter > 3 %} <p>si</p> {% endif %} --> <div class="integrazione"> <div> <img src="{% static 'img/integratori.svg' %}" class="img-fluid"> <h6 class="m-0">{{ dayone.integratore }}</h6> </div> </div> {% endif %} {% endfor %} {% endif %} -
Django ordering by random when using union
I have one Django app when I'm doing random ordering it's working using order_by('?') But not working when I apply random ordering on union queryset. queryset = (queryset.filter(town__istartswith=location).order_by('?')). union(queryset.filter(Q(town__icontains=location) | Q(post_code__icontains=location) | Q(post_area__icontains=location) | Q(street__icontains=location) | Q(country__icontains=location) | Q(agency__operating_areas__icontains=location)).order_by('?')) In my case, if I search with city Helsinki then if it comes in city field then its record display first but in a random order, another record also comes from other fields it is also set random order. For example*: Searching with "Helsinki" city. Then there are four records in which agency city is "Helsinki" then it will come always first but in random order all time and for other record come in random order. [{ "id": 1, "city": "Helsinki", "Name": "Abhishek", }, { "id": 2, "city": "Helsinki", "Name": "Urvesh", }, { "id": 3, "city": "Helsinki", "Name": "Dhruvil", }, { "id": 4, "city": "Helsinki", "Name": "Akshat", }, { "id": 5, "town": "Helsinki", "Name": "Akshat", }, { "id": 6, "country": "Helsinki", "Name": "Akshat", }, { "id": 7, "street": "Helsinki", "Name": "Akshat", }, { "id": 8, "town": "Helsinki", "Name": "Akshat", }] Please help me in this how can I do a random search in the union, Please give me the best solutions … -
Checking if a field in model is modified and creating instance of another model
I have two models Project Model class Project(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey("WorkflowType", null=True, blank=True, on_delete=models.SET_NULL) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name Workflow Instance Model class WorkflowInstance(models.Model): workflow_step = models.ForeignKey('WorkflowStep', null=True, blank=True, on_delete=models.CASCADE) project = models.ForeignKey('Project', null=True, blank=True, on_delete=models.SET_NULL) I want to check if the value of workflow field in "Project" models is added or changed for a particular project. I am approaching the problem in following manner: Checking if the previous and the new value of the "workflow" field in a project are different. If yes (modifies), then create the new instance of a project. @receiver(pre_save, sender=Project) def projectToBeUpdated(sender, instance, **kwargs): if instance.id is None: pass else: previous = Project.objects.get(id=instance.id) if previous.workflow != instance.workflow: print("workflow value modified. Please create a WorkflowInstance") Problem: The comparison for previous and new value of the "workflow" field are happening in "pre_save" signal. But my new instance creation for workflowInstance is to be created in "post_save" signal. How can I do this? Also, ideally I would like to store the previous value of workflow field in "pre_save" and get the new value of the field in "post_save". Reason being, save() method might fail for any reason, … -
File "C:\django\2proj\authentication\utils.py", line 2, in <module> from six import text_type ModuleNotFoundError: No module named 'six'
Am trying to import module six in my utils.py but its not working from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type from django_six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active) + text_type(user.pk) + text_type(timestamp)) account_activation_token = AppTokenGenerator() but i get this error " File "C:\django\2proj\authentication\utils.py", line 2, in from six import text_type ModuleNotFoundError: No module named 'six'" Am using django 4.0.2 -
Adding new fields to the Object Change History model (Django)
I'm writing my todo in django. I want to add not just the entry "task changed" to the "history" tab, but also two additional fields: "was" - "became". How can I do this? -
How to create range slider filter in django
I want to create a range slider filter in Django where If I change the price from the slider by increasing the range, it should show the servers that have the same price in order. but I tried to create that slider also I researched on google, StackOverflow I couldn't find the answer between I'm using the API instead of models stuff Here's the website sample: https://www.hetzner.com/sb?price_from=30&price_to=380 my code: def index(request): headers = { "User-Agent": "...", "Accept-Encoding": "*", "Connection": "keep-alive" } url = "https://www.hetzner.com/a_hz_serverboerse/live_data.json" response = requests.get(url, headers=headers) data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj, } return render(request, 'index.html', context) -
ImportError: Could not import 'authentication.backends.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
I am following the example given here : https://www.django-rest-framework.org/api-guide/settings/#accessing-settings. Once I open the django shell using python manage.py shell and run the following command from rest_framework.settings import api_settings print(api_settings.DEFAULT_AUTHENTICATION_CLASSES) I am getting the following error Traceback (most recent call last): File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\django_project\.venv\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 225, in __getattr__ val = perform_import(val, attr) File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 168, in perform_import return [import_from_string(item, setting_name) for item in val] File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 168, in <listcomp> return [import_from_string(item, setting_name) for item in val] File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 180, in import_from_string raise ImportError(msg) ImportError: Could not import 'authentication.backends.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'authentication.backends' Does someone know what's going on? P.S: I have a very big django project which is failing with the same error, hence I am pinpointing to only the main setting which is failing in this example.