Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Session variables don't hold across API calls
This is the API function that's being called, so the request.session['uid'] doesn't hold its value when the react server makes another request to another call that utilizes the same session variable. The django server is hosted on local and then the calls are made using that IP so localhost:8000/postSignIn. def postsignIn(request): email = request.POST.get('email') pasw = request.POST.get('pass') request.session['email'] = email cursor = connection.cursor() cursor.execute("SELECT U.user_id FROM \"User\" U WHERE U.email = '{0}' ".format(str(email))) useridfetch = cursor.fetchone() request.session['uid'] = useridfetch[0] try: user = firebaseauthenticator.sign_in_with_email_and_password(email, pasw) return HttpResponse(request.session['uid']) except: message = "Invalid Credentials" return render(request, "Login/Login.html", {"message": message}) -
Adding unique id to new dynamically created form using django htmx
I am trying to create a dynamic form where the user can create as many questions as they want and at the same time add answers to each questions as many as they want(max number of answer is 4). I am using htmx to add new question and answer. I am able to add more questions when clicking the 'Add Question' button and more answers when clicking the 'Add Answer' button. However, when i tried to add more answers on Question 2 or 3, it will add a new answer form in Question 1 only. I want the answer to be added to their respective questions. Do help me with this issue. add_quiz_questions.html {% load crispy_forms_tags %} <div class="container-fluid"> <!-- Main Content Here --> <form method="POST" enctype="multipart/form-data"> <div class="card shadow mb-4"> <!-- <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary ">Post Your Announcements</h6> </div> --> <div class="card-body"> {% csrf_token %} {{ questionform.question|as_crispy_field}} <div> {{ answerform.answer|as_crispy_field}} {{ answerform.correct_answer|as_crispy_field}} <div id="addanswer"></div> </div> <button hx-get="{% url 'add_quiz_answer' %}" hx-swap="beforeend" hx-target="#addanswer" class="btn btn-info">Add Answer</button> <button type="submit" class="btn btn-primary">Save</button> </div> <div id="addquestion"></div> </div> <button hx-get="{% url 'add_quiz_question' %}" hx-swap="beforeend" style="margin-bottom:30px" hx-target="#addquestion" class="btn btn-info"> Add Question</button> </form> </div> create_question.html {% load crispy_forms_tags %} {% csrf_token %} <div … -
Unable to connect to Postgres DB living in one docker-compose file with django app in separate docker-compose file
I have a large monorepo Django app that I want to break into two separate repositories (1 to handle external api requests and the other to handle my front end that I plan on showing to users). I would still like to have both django apps have access to the same db when running things locally. Is there a way for me to do this? I'm running docker for both and am having issues with my front end facing django app being able to connect to the Postgres DB i have set up in a separate docker-compose file than the one I made for my front end app. External API docker-compose file (Postgres DB docker image gets created here when running docker-compose up --build) --- version: "3.9" services: db: image: postgres:13.4 ports: - "5432:5432" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres api: restart: always build: . image: &img img-one command: bash start.sh volumes: - .:/app ports: - "8000:8000" depends_on: - db env_file: - variables.env Front end facing docker-compose file (This is the one I want to be able to connect to the DB above): --- version: "3.9" services: dashboard: restart: always build: . image: &img img-two volumes: - .:/code ports: … -
Getting the latest entries for every group
I am trying to build a simple storage example in django 4.0 where stuff is inserted to a storage table defined like this: class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount = models.IntegerField(null=True) price = models.FloatField(null=True) timestamp = models.DateTimeField(default=timezone.now) To retrieve the latest entry for every material within this table I need something looking like this in SQL: SELECT material_id, amount, price, MAX(timestamp) FROM assetmanager_material_storage GROUP BY material_id Since I'm new to Django, I haven't managed to recreate this query yet. I found some threads suggesting solutions like: material_storage.objects.values('material').annotate(latest_record=Max('timestamp')) but that's not working in my case, instead throwing an error "name 'Max' not defined". The other approach would be to go like this: material_storage.objects.all().latest('timestamp') but this would only return the latest object in the whole table and I couldn't figure out for now how to apply "latest" on every material instead of all records. So I am kinda stuck now. If somebody could tell me what I'm missing, I would be grateful. thx in advance. -
autobahn.exception.Disconnected: Attempt to send on a closed protocol
I have a web server uploaded on a server that receives messages from a Windows app and sends them to a front end in the browser Its late there is a slight delay in receiving and sending and when I checked the django logs I get this message from time to time 2022-03-03 21:04:54,257 ERROR Exception inside application: Attempt to send on a closed protocol Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/local/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/usr/local/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/app/backend/server/./script/consumers.py", line 242, in chat_message await self.send(text_data=json.dumps({ File "/usr/local/lib/python3.8/site-packages/channels/generic/websocket.py", line 209, in send await super().send({"type": "websocket.send", "text": text_data}) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 81, in send await self.base_send(message) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line … -
Book.objects.all() doesnt return anything although books exist in the database Django
I have a books page that shows all books in the database but it doesn't show any books although books do exist in the database and on the admin page and I don't know why. the model for the book is: book_status = [ ('Available', 'Available'), ('Borrowed', 'Borrowed'), ] id = AutoField(primary_key=True) title = models.CharField(max_length=250) author = models.CharField(max_length=250, null=True, blank=True) borrowing_period = models.IntegerField(null=True, blank=True) publication_year = models.IntegerField(null=True, blank=True) isbn = models.IntegerField(null=True, blank=True) status = models.CharField(max_length=50, choices=book_status, null=True, blank=True) slug = models.SlugField(_("slug"), null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Book, self).save(*args, **kwargs) the views function: def books(request): searchf = Book.objects.all() if request.method == 'POST': cat = request.POST['category'] if cat == 'ISBN': isbn = None if 'search' in request.POST: isbn = request.POST['search'] if isbn: searchf = searchf.filter(isbn__icontains=isbn) elif cat == 'Title': title = None if 'search' in request.POST: title = request.POST['search'] if title: searchf = searchf.filter(title__icontains=title) elif cat == 'Author': author = None if 'search' in request.POST: author = request.POST['search'] if author: searchf = searchf.filter(author__icontains=author) elif cat == 'Year': Year = None if 'search' in request.POST: Year = request.POST['search'] if Year: searchf = searchf.filter(publication_year__icontains=Year) return render(request, 'books.html', { 'books': searchf, 'category': Category.objects.all() }) … -
Passing Json from Django view to template Javascript
I'm trying to pass a json response from a view to javascript. For some reason I can't access any keys inside javascript. I can only access the whole json object, but none of the nested keys attached to it. Json(simplified for the purpose of reading): { "protected": [ { "category": "nmtd", "name": "NMTD", "userId": 257 } ] } views.py: def index(request): request_pr = requests.get('https://endpoint-address', cookies = request.COOKIES) pr_colors = json.dumps(request_pr.json()) context = { 'pr_colors': pr_colors } return render(request, 'index.html', context) Javascript: <script type="text/javascript"> var received_data = "{{ pr_colors }}" console.log(received_data) </script> There are two different kinds of problems. If I set JSON.parse("{{ praga_colors }}") I get Uncaught SyntaxError: Unexpected token & in JSON at position 1 If I just try to access the element directly without JSON.parse() I get all the values as undefined. If I try to access by position praga_colors[1], I get a letter by letter string. What is the proper way to handle this? -
Wagtail page promote tab - "Show in Menu" - How does it work?
The default Wagtail page model includes the "Show in Menu" option on the promote tab. I've been searching through the documentation for awhile now trying to find more information about how this works and I don't see anything. What is this option used for, and how do I hook into that field so that I can build a simple list of links to be used is some arbitrary template like a footer? Am I supposed to just build my own queryset of admin models and then filter on that value, or is there a simpler utility include with Wagtail that I can use directly? -
Cascading Multiselect Option List using Javascript
I have found a code online that satisfies my need of cascading option list. But I also need to make multiple selections. When I add multiple to select tag it allows me to make multiple selections however it shows as if only 1 option was choosed. Here is the code I am using: Javascript: var root_1_Object = {{ url_categories|safe }} window.onload = function() { var root_1_Sel = document.getElementById("root_1"); var root_2_Sel = document.getElementById("root_2"); var root_3_Sel = document.getElementById("root_3"); for (var x in root_1_Object) { root_1_Sel.options[root_1_Sel.options.length] = new Option(x, x); } root_1_Sel.onchange = function() { //empty root_3_S- and root_2_S- dropdowns root_3_Sel.length = 1; root_2_Sel.length = 1; //display correct values for (var y in root_1_Object[this.value]) { root_2_Sel.options[root_2_Sel.options.length] = new Option(y, y); } } root_2_Sel.onchange = function() { //empty root_3_S dropdown root_3_Sel.length = 1; //display correct values var z = root_1_Object[root_1_Sel.value][this.value]; for (var i = 0; i < z.length; i++) { root_3_Sel.options[root_3_Sel.options.length] = new Option(z[i], z[i]); } console.log(root_3_Sel); } } Html: <select name="root_1" id="root_1" multiple required/> <option value="" selected="selected"></option> </select> <br><br> <select name="root_2" id="root_2" multiple required/> <option value="" selected="selected"></option> </select> <br><br> <select name="root_3" id="root_3" multiple required/> <option value="" selected="selected"></option> </select> <br><br> -
Django Model verbose_name as API rows response names
As I can't save special characters in fields in django model I have to bypass it. For example: I would like to have "km/h" field. So I'm using it like: class Unit(models.Model): kmh = models.FloatField(null=True, db_column='km/h', verbose_name='km/h') then I have example serializer: class UnitSerializer(serializers.ModelSerializer): class Meta: model = Unit fields = ['kmh'] and when I'll use it with APIViews response which will include the field will look like: { "kmh":10, } I would like to make it look like my verbose_name so: { "km/h":10 } How can I do it? -
Multiple Image Upload with Preview in JS does not work to upload images to the database
I just implemented a Multiple Image Upload with Preview, it was the easiest option I had as I don't know JS. The point is that I am using it with my project in Django. The question is, how do I save those images to my database? For example, the Multiple Image Upload With Preview has a button that says "browse" that, when clicked, serves as an input where the preview of the images appears, but it does not work like this: <input type="file" name="guarantee" class="form-control" multiple="" accept="image/*" required="" id="id_guarantee"> and I want that "browse" button to do what the input (called "Elegir archivos") I put above does so that it loads the images to the database -
StaticFiles vs MediaFiles
What is the difference between static files and media files? Django says that the SATIC_ROOT and MEDIA_ROOT must be different. I just know that in static folder we can have css files and images or other files to be uploaded goes to media folder. I have directory as static |-->images |-->css in settings.py >> STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Is the ROOT and URL for static and media files are okay or not? -
Writing custom ASC recommendations using Azure Python SDK
I am trying to write custom recommendations into Azure Security Center from my own product but I can't find any real reference in the SDK documentation to say how to do this. I can see references to IoT but not "normal" recommendations. Has anyone else managed to do this? -
How can I save requests when using login_required in django
I am making community site with django. I required login for creating answer. However when I answed with non-login user it required login and next redirect to first answer page but already written answer disappeared. So I want to save requests before login_required decorator. Here is the code @login_required(login_url='common:login') def answer_create(request, question_id): question = get_object_or_404(Question, id=question_id) if request.method == "POST": form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.author = request.user answer.create_date = timezone.now() answer.question = question answer.save() return redirect('pybo:detail', question_id=question_id) else : form = AnswerForm() context = {'question':question, 'form':form} return render(request, 'pybo/question_detail.html', context) -
Is there a way to automatically generate a whole system for different users
I am done with a hostel management system in Django which consist of payments, users registering for rooms, etc. But with this, i want it in a way that, when a user or a hostel manager wants to buy such a system, they buy it from our website so it automatically generates the whole hostel management system for him or her in which it will be different from another person also buying the same system from us. and also if in case i will want to add a yearly subscription how will it be done. Thank you for your help -
Django js tabs keep selected tab on page refresh
I'm working with js tabs in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. I found this example but it doesn't work https://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php This is the script I'm using: {% extends "bioinfointerface/base.html" %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Keep Selected Bootstrap Tab Active on Page Refresh</title> <script> $(document).ready(function(){ $('a[data-toggle="tab"]').on('show.bs.tab', function(e) { localStorage.setItem('activeTab', $(e.target).attr('href')); }); var activeTab = localStorage.getItem('activeTab'); if(activeTab){ $('#myTab a[href="' + activeTab + '"]').tab('show'); } }); </script> </head> <body> <div class="m-3"> <ul class="nav nav-tabs" id="myTab"> <li class="nav-item"> <a href="#sectionA" class="nav-link active" data-toggle="tab">Section A</a> </li> <li class="nav-item"> <a href="#sectionB" class="nav-link" data-toggle="tab">Section B</a> </li> <li class="nav-item"> <a href="#sectionC" class="nav-link" data-toggle="tab">Section C</a> </li> </ul> <div class="tab-content"> <div id="sectionA" class="tab-pane fade show active"> <h3>Section A</h3> <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p> </div> <div id="sectionB" class="tab-pane fade"> <h3>Section B</h3> <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p> </div> <div id="sectionC" class="tab-pane fade"> <h3>Section C</h3> <p>Nullam hendrerit justo non leo aliquet...</p> </div> </div> </div> </body> </html> {% endblock %} In base.html I load: <!-- Bootstrap core JS--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS--> <script src="{% static 'bioinfointerface/js/scripts.js' %}"></script> <link … -
Customer registration with dynamic forms django
By entering the phone number in the customer registration form , if the customer already exists then should fill the rest of the fields by fetching it from the backend. if the user does not exists then have to register. help me with the script used for this this is the model i have. class Customers(models.Model): customer_id = models.AutoField(primary_key=True) cname = models.CharField(max_length=100) cnumber= models.IntegerField() caddress= models.CharField(max_length=100) I m using the modelform here. class CustForm(forms.ModelForm): class Meta: model=Customers fields = '__all__ this is my view def customer(request): form=CustForm() if request.method=='POST': form = CustForm(request.POST) form if form.is_valid(): form.save(commit=True) messages.success(request,'successfully customer added') return render(request,'hello.html') else: messages.error(request,'Invalid') return render(request,'custdata.html',{'form':form}) This is my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% block content %} <div> <center><h2><b>Add Customer</b></h2></center> <p><form method='post'> {% csrf_token %} <center> {{form.as_p}} <button type="submit" style="width:200px; height:30px; font-size: 20px;">ADD</button> </center> </form> </div> {% endblock %} </body> </html>``` -
Django template | safe filter behaving differently on different environments
In the template I have <div>{{ my_var | safe }}</div>, where my_var is being set as my_var = format_html("<p>my variable</p>") and rendered using render_to_string function. In the production environment, the result is produced as &lt;p&gt;my variable&lt;/p&gt;. It works correctly in the local environment. I understand format_html produces safe string which shouldn't be escaped by the template, even providing | safe filter isn't solving the issue. The baffling thing is it behaves correctly on staging/local env but not on prod -
Testing Django Wagtail - assert that a child of the given Page type can be created under the parent, using the supplied POST data
I've defined a custom page model (a blog post) as a child of a parent model (a blog index page) and I want to test that the child can be created under its parent. The BlogPage and BlogIndexPage models are copied from the wagtail "basic blog" example in the documentation, and works as expected. I'm trying to follow the documentation but I get the following validation error: AssertionError: Validation errors found when creating a cms.blogpage: E date: E This field is required. E intro: E This field is required. E slug: E This field is required. E title: E This field is required. I suspect that I'm defining my fixture incorrectly, but I am not what the correct form is. Any help is greatly appreciated! Can someone explain why it isn't working? fixture (apps.cms.tests.fixtures.blogPage.json): [ { "model":"wagtailcore.page", "pk": 1, "fields":{ "date":"2022-02-28", "intro":"intro to the post...", "slug":"slug/", "title":"the title", "body":"body of the post...", "categories":[ 1 ], "content_type": ["cms", "blogpage"], "depth": 2 } }, { "model": "cms.blogpage", "pk": 1, "fields": {} } ] the test class (apps.cms.tests.test_pages.py): class MyPageTests(WagtailPageTests): def setUp(self): self.login() page = BlogIndexPage(title="Home page", slug="home", path="foo", depth=1) page.save() def test_create_blog_post(self): cwd = Path.cwd() root_page = BlogIndexPage.objects.first() with open(f"{cwd}/lettergun/apps/cms/tests/fixtures/BlogPage.json") as json_file: … -
Nginx WebServer and API Server
A system I am designing is composed of a Django application that serves a web page for the user, and a Flask server that exposes a set of REST API that are meant to be used from other external programs. For deployment I would like to make both web page and API use HTTPS protocol. To achieve this in test environment I started an Nginx instance and make it communicate with Django through uwsgi help, then configured Nginx to listen on a port in ssl mode. I guess I should do something very similar with Flask, but I am not confident what is the best way to do it. -
How to enable POST,PUT for django rest framework viewset
I have simple viewset like this in views.py class MyFileViewSet(viewsets.ViewSet): http_method_names = ['post','get','put'] def list(self, request): queryset = MyFile.objects.all() serializer = MyFileSerializer(queryset, many=True) return Response(serializer.data) models.py from xml.dom.minidom import DOMImplementation from django.db import models class MyModel(models.Model): name = models.CharField(verbose_name='NAME', max_length=30) file = models.FileField(upload_to='file/%Y/%m/%d') is_transfer_finish = models.BooleanField(default=False) created_at = models.DateTimeField(verbose_name='created', auto_now_add=True) Now I can see the list of MyModel. However I want to set post and push for this model, I set http_method_names = ['post','get','put'] But currently, there is only 'GET' on html. I want to enable POST or PUT to create new entry. Is it possible? how can I make this? -
Django or flask which is easier to learn first [closed]
I am new in python I would like to learn django but some of my friends told me that I should learn flask before learning Django. what should i do? -
Django widget for sensitive fields
I am working on a Django website that presents users a form to store their API keys and API secrets. At the moment both fields are showing as CharField generated by django-crispy-forms so both the API key and API secrets are visible. I would like a behaviour where by default the fields are showing ****** or ●●●●●● when not focused and revealing the content when focused. I have tried making this field a PasswordInput() widget in forms.py with self.fields["my_field"].widget = forms.PasswordInput() However this brings a couple of problems: Browsers consider the API keys and an API secrets as actual passwords and save them at the browser level When the field is focussed, the contents of the fields are not shown Is creating a custom widget the only solution for this? -
Trying to load a simple html in Django but it appears GET /homepage/ HTTP/1.1" 500 145
I'm quite new in Django development. I did the Tutorial for the polling app on the official Django web page and everything worked out fine. Since I already have some HTML from my old website I wanted to reuse some of that. I decided to create an app called "homepage" for the main page you get when you visit the page (if this is bad practice, let me know). Since the main page is more or less just some introductory text and a navigation menu without any fancy functionality I did not create a DB (models) in this case. Furthermore I was sure that Django is able to simply deliver some plain static html without a database provided. The urls.py in the hompage app folder looks like: from django.urls import path from . import views urlpatterns = [ path('', views.index1, name='index1'),] and the view.py like this from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Hello, world. You're at the polls index.") Everything works out fine. As soon as I try to load a html file (here a simple one just to check if it works) I get the error message. The new view.py looks like in the … -
Could not import 'rest_framework_jwt.authentication' when running python manage.py migrate
Following a tutorial to use JWT to handle user authentication through tokens. I have got as far as making changes to my Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) my urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_jwt.views import obtain_jwt_token router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) # router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token-auth/', obtain_jwt_token) When I try to run python manage.py migrate I get the error: ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (C:\Users\15512\anaconda3\lib\site-packages\django\utils\encoding.py). I already pip installed djangorestframework-jwt