Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the latest version of a all previously distinctable objects within a single query in django?
I have a model with a version field. class Workflow(models.Model): ... process_id = models.CharField(null=False, max_length=100) # not unique! version = models.IntegerField(default=1) enabled = models.BooleanField(default=True, null=False) I'm trying to find the latest version for each process_id within a single query. Basically, I want to do the following: class WorkflowFilterSet(django_filters.FilterSet): ... only_latest_versions = django_filters.BooleanFilter(method='get_only_latest_versions') def get_only_latest_versions(self, queryset, field_name, value): if value: workflows = [] for worflow in queryset.distinct('engine_bpmn_process_id'): workflow_ = queryset.filter(engine_bpmn_process_id=worflow.engine_bpmn_process_id, enabled=True).latest('version') workflows.append(workflow_) return workflows # even if I wanted to do like this I can't because I must return a QuerySet return queryset How can I do the above with a single query? Thank you very much! -
Django app request not found after changing site URLs
I have a webpage that does an async request on startup to fetch a JSON file: controller.js $.ajax( { url: '/get_lines/', data_type: 'json', success: function(data) { fillLinesMenu(JSON.parse(data)) $("#form-lines option:eq(1)").attr("selected","selected"); $("#form-lines").selectmenu("refresh") } } ) project/field_plot/urls.py urlpatterns = [ url(r'^get_lines/$', views.get_lines, name='get_lines'), url(r'^get_plot/$', views.get_plot, name='get_plot'), url(r'', views.index, name='index'), ] project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('sky_map/', include('sky_map.urls')), path('', include('field_plot.urls')), ] This has been working fine for quite a while. As you can see, I've been working on field_plot - hence the empty url, to simplify page loading - but now I need to assign this app to its specific project-level URL: project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('sky_map/', include('sky_map.urls')), path('field_plot/', include('field_plot.urls')), ] Now I need to load http://localhost:8000/field_plot/, as predicted, but changing the last path breaks /get_lines/ and other URLs I use for AJAX requests. What am I missing? -
How to receive context data in django template and work with it in javascript
I am trying to receive context data in django template and work with it in javascript. Currently i am receiving the data but as a string and it looks gibberish. my code: {% extends "base.html" %} {% block content %} {% if search_list %} <!-- do something --> {% endif %} <!-- javascript code --> {% block script %} <script > let data = '{{search_list}}' console.log(data); </script> {% endblock script %} {% endblock %} If i remove the quote in the variable search_list in javascript it shows me error. i have used jsonify and safe tag it doesn't work. How do i get the data as an object here? -
Transform dict in nested dict
How to transform a dictionary with str keys separated by '__' into a nested dictionary, for example, transform from that { age:1, name__first:'jhon', name__last:'wick', location__street:'avenue', location__coordinates__latitude:222, location__coordinates__longitude:222, } to that { age:1, name:{ first:'jhon', last:'wick', } location:{ street:'avenue', coodinates:{ latitude:222, longitude:222, } } } -
How to perform Outer Joins using Django ORM?
I have the following models: class Partner(models.Model): partner_name = models.CharField(max_length=50) class Allocation(models.Model): partner = models.ForeignKey( Partner, related_name='partner_allocations', on_delete=models.CASCADE ) is_allocated = models.BooleanField(default=False) By using Django ORM, I need the joined tables with columns as ['partner_name', 'partner_id', 'is_allocated']. All partner names(unrelated too), and related data from Allocation model. SQL = SELECT partner.id, allocation.partner_id, allocation.is_allocated FROM Partner LEFT OUTER JOIN Allocation ON Partner.id=Allocation.partner_id or SQL = SELECT partner.id, allocation.partner_id, allocation.is_allocated FROM Allocation RIGHT OUTER JOIN Partner ON Allocation.partner_id=Partner.id The output for the above SQL using Django ORM. The syntax for SQL queries might be wrong here, but they give the overall idea. I want to use raw SQL only as the last option. Please, can someone help. -
Not getting results from mysql using query in views in django
I am using MySQL database which and try to filter data according to date but while using filter I am getting nothing.While i uncomment this line print(searchresult.Date) then it will show error 500. Here is my view.py from sales.model import Mar21 def show(request): if request.method == 'POST': fromdate = request.POST.get('startdate') todate = request.POST.get('todate') # date = Mar21.objects.only('Date') print(fromdate) print(todate) searchresult = Mar21.objects.filter(date__lte = fromdate,date__gte = todate) # print(searchresult.Date) return render(request,'front.html',{'data':searchresult}) else: data = Mar21.objects.all() # print(data) return render(request,"front.html",{'data':data}) Here is my model from django.db import models class Mar21(models.Model): id = models.IntegerField(db_column='Id', blank=True, null=True) # Field name made lowercase. date = models.DateField(db_column='Date', blank=True, null=True) # Field name made lowercase. sales_channel = models.TextField(db_column='Sales Channel', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. sales_order_id = models.FloatField(db_column='Sales order ID', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. ship_to_name = models.TextField(db_column='Ship to name', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. sku = models.TextField(db_column='SKU', blank=True, null=True) # Field name made lowercase. normal_sku = models.TextField(db_column='Normal SKU', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. vendor = models.TextField(db_column='Vendor', blank=True, null=True) # Field name made lowercase. quantity = … -
LoginTestListView is missing a QuerySet. Define LoginTestListView.model, LoginTestListView.queryset, or override LoginTestListView.get_queryset()
Why such a mistake? Request Method: GET Request URL: http://127.0.0.1:8000/auth/login/ Django Version: 2.2.18 Exception Type: ImproperlyConfigured Exception Value: LoginTestListView is missing a QuerySet. Define LoginTestListView.model, LoginTestListView.queryset, or override LoginTestListView.get_queryset(). Exception Location: C:\Users\isp06\Documents\test\geekshop-server\venv\lib\site-packages\django\views\generic\list.py in get_queryset, line 35 Python Executable: C:\Users\isp06\Documents\test\geekshop-server\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: ['C:\Users\isp06\Documents\test\geekshop-server\geekshop', 'C:\Users\isp06\Documents\test\geekshop-server\geekshop', 'C:\Program Files\JetBrains\PyCharm ' '2020.3.3\plugins\python\helpers\pycharm_display', 'C:\Users\isp06\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\isp06\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\isp06\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\isp06\AppData\Local\Programs\Python\Python39', 'C:\Users\isp06\Documents\test\geekshop-server\venv', 'C:\Users\isp06\Documents\test\geekshop-server\venv\lib\site-packages', 'C:\Program Files\JetBrains\PyCharm ' '2020.3.3\plugins\python\helpers\pycharm_matplotlib_backend'] Server time: Fri, 26 Mar 2021 17:18:20 +0000 enter code here class LoginTestListView(ListView): template_name = 'authapp/login.html' form_class = UserLoginForm def get_context_data(self, **kwargs): context = super(LoginTestListView, self).get_context_data(**kwargs) context['title'] = 'GeekShop - Авторизация' return context enter code here urlpatterns = [ path('login/', LoginTestListView.as_view(), name='login'), path('register/', register, name='register'), path('profile/', profile, name='profile'), path('new-logout/', new_logout, name='new_logout'), enter code here class UserLoginForm(AuthenticationForm): class Meta: model = User fields = ('username', 'password') def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['placeholder'] = 'Введите имя пользователя' self.fields['password'].widget.attrs['placeholder'] = 'Введите пароль' for fild_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control py-4' -
Django doesn't load build/static files ReactJS
Hello I have try make a website using ReactJS and Django with RESTAPI. When i run npm start and python manage.py runserver separatly that work perfectly. But when i try to render the index.html with django from the react/build. It doesn't work. It render a blank page with the error that follow. There is the error. There is my files. settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zn(=yq@vvasu)(-1qqj*q(ubl6gwxpl)ff8vs+lqpvuq!d(3(q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ "127.0.0.1" ] # 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', 'rest_framework.authtoken', 'rest_auth', 'polluser.apps.PolluserConfig', 'restapi.apps.RestapiConfig', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', ] SITE_ID = 1 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', ] ROOT_URLCONF = 'template.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'static'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'template.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'essaitest', 'USER': 'pass', 'PASSWORD': 'pass', … -
Can anyone tell me what this pseudocode means?
Can anyone please explain to me what the pseudocode is all about as it'll be really helpful as I need to create a function in python for this Fuzzy Yara Rules Pseudocode -
Is it bad if I have a lot of options in my model choice field?
I created cities.py file which contains all cities of my country (it's 20 kb of data) in list CITY_CHOICES. I have a model with city row, I imported CITY_CHOICES and set it as choices for this row: city = models.CharField(max_length=63, choices=CITIES_CHOICES, blank=False, null=True) Is it too much? Will I experience performance issues? Sorry, if it's a dumb question. By the way I use MySQL. -
Can I know everything about python?
I've recently started learning Django. I am picking up the syntax and everything seems to be going on well. I have taken full python courses (including college) before diving into Django. However, every day I see something new in python that I don't know. I do get overwhelmed that my knowledge in Python is not just yet good enough and have to read a lot. Can I know everything about python?? -
How to query self referencing queries in Django for multiple objects
Sorry for the bad title. I hope I can elaborate it better here. I have a model class as below class Employee(models.Model): name = models.CharField(max_length=10) manager = models.ForeignKey('Employee', null=True, on_delete=models.DO_NOTHING) I want to make a query to find all the employees managed by a list of managers. Something like this SELECT r.name FROM employee l JOIN employee r ON l.id = r.manager_id WHERE l.name in ('manger_1', 'manager_2'); How can I achieve this with Django ORM? -
How to insert excel table in django app and create relationships between it's variables?
first time posting here so excuse any mistakes in formating and phrasing. I am making a django-rest app with react frontend into which I have to import excel tables of this type. The purpose of the app will be to accept variable1 (height) and variable2 (width) from the user. Look at the table and return to the user the variable3 (price) that corresponds to their choice. My questions are: What would be a good way to insert the excel tables into django instead of manually typing them Would it be possible to avoid hardcoding every possible combination of the 3 variables and instead create a relationship between them that works thusly: Receive variable1 from user > Return a list of possible variable2 > Receive variable2 from user > Return appropriate variable3 (My question regards the backend, a way for django to process the excel table and how the views and models could be structured. Frontend isn't an issue) I know the question is pretty broad and I hope it is within the scope of stackoverflow. Any and all answers will be greatly appreciated, thanks for your time! -
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
I'm trying to run python manage.py runserver on my linux CLI. In my virtual environment, when I run sqlite3 --version I get 3.28.0 but when I run "python", then "import sqlite3", then "sqlite3.sqlite_version", I get 3.7.17. I understand that there is a path file issue but I can't seem to force it to use the newer version of sqlite3. I've tried: django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17)) How to use the latest sqlite3 version in python -
ValueError: Field 'id' expected a number but got 'john.smith@gmail.com'
I am trying to create custom user model for authentication. I did everything as in Django documentation but when I am trying to create super user with command line, I get the error. I tried to delete database and migrations and run them again, did not help. Here is my model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db.models.deletion import CASCADE from django.utils import timezone from django.utils.translation import gettext_lazy # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, Email, Name, Surname, Password = None, **other_fields): if not Email: raise ValueError(gettext_lazy('You must provide email address')) email = self.normalize_email(Email) user = self.model(email, Name, Surname, **other_fields) user.set_password(Password) user.save(using=self._db) return user def create_superuser(self, Email, Name, Surname, Password = None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(Email=Email, Name = Name, Surname = Surname, Password = Password, **other_fields) class Customer(AbstractBaseUser, PermissionsMixin): Email = models.EmailField(gettext_lazy('email address'), max_length=256, unique=True) Name = models.CharField(max_length=64) Surname = models.CharField(max_length=64, null=True) Birthday = models.DateField(auto_now=False, null=False,blank=True) PhoneNumber = models.CharField(max_length=16, unique=True, blank=True) Address = models.CharField(max_length=128, blank=True) RegistrationDate = models.DateTimeField(default=timezone.now, editable=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ['Name', 'Surname'] def __str__(self): return self.Name + " " + self.Surname def … -
Django channels- Websocket error on heroku
On a local server when i try to connect to make a websocket connection, it successfully runs, But, when i try to connect to websocket on heroku after deploying, i face the following issue 2021-03-26T16:44:22.786720+00:00 app[web.1]: 10.102.191.252:18515 - - [26/Mar/2021:16:44:22] "WSCONNECT /ws/webhooks/586310f018131c1214ff9ece33669e0ebfef2a47/" - - 2021-03-26T16:44:24.018995+00:00 app[web.1]: 2021-03-26 16:44:24,018 ERROR Exception inside application: Expecting value: line 1 column 1 (char 0) 2021-03-26T16:44:24.019005+00:00 app[web.1]: Traceback (most recent call last): 2021-03-26T16:44:24.019006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/sessions.py", line 183, in __call__ 2021-03-26T16:44:24.019006+00:00 app[web.1]: return await self.inner(receive, self.send) 2021-03-26T16:44:24.019007+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/middleware.py", line 41, in coroutine_call 2021-03-26T16:44:24.019007+00:00 app[web.1]: await inner_instance(receive, send) 2021-03-26T16:44:24.019007+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__ 2021-03-26T16:44:24.019008+00:00 app[web.1]: [receive, self.channel_receive], self.dispatch 2021-03-26T16:44:24.019008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch 2021-03-26T16:44:24.019009+00:00 app[web.1]: await dispatch(result) 2021-03-26T16:44:24.019010+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch 2021-03-26T16:44:24.019010+00:00 app[web.1]: await handler(message) 2021-03-26T16:44:24.019028+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/generic/websocket.py", line 196, in websocket_receive 2021-03-26T16:44:24.019029+00:00 app[web.1]: await self.receive(text_data=message["text"]) 2021-03-26T16:44:24.019029+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/generic/websocket.py", line 259, in receive 2021-03-26T16:44:24.019030+00:00 app[web.1]: await self.receive_json(await self.decode_json(text_data), **kwargs) 2021-03-26T16:44:24.019031+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/generic/websocket.py", line 277, in decode_json 2021-03-26T16:44:24.019031+00:00 app[web.1]: return json.loads(text_data) 2021-03-26T16:44:24.019031+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 348, in loads 2021-03-26T16:44:24.019032+00:00 app[web.1]: return _default_decoder.decode(s) 2021-03-26T16:44:24.019032+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/json/decoder.py", line 337, in decode 2021-03-26T16:44:24.019033+00:00 app[web.1]: obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 2021-03-26T16:44:24.019033+00:00 app[web.1]: File … -
icon badges showed if other users logged in in django
how to show green dot badge if others users are logged in from their ph or computer. similar like facebook, If users are active in my friends list we see a green dot badge in their profile. how to do it. -
how to build a full stack app with load balancer react native react and django (system design)
I am building an app that has django (DRF) as backend framework, React for the front end and React Native for mobile. I am using Docker and Nginx as Load balancer. Now my issue, I read about API gateway, since I intend to deploy my app on AWS, is the system design below the best approach for a small app then could potentially scale without slowing down the app from the start if i ever have a lot of users? Mobile (maybe port 3000) ----> NGINX (Load balancer) * API Gateway -----> backend (Django) Desktop (maybe port 9000) Do I really need the API Gateway, if YES should this be from NGINX or AWS I am looking forward to your advises to make an educated decision. Thank you -
Django create Postgres Enumerated Types fields from models
Does django support postgres enumerated types? I'm creating a model as follows, which generates the following migration. When I run the migration I would expect these types would be enforced at the db level, but it appears they are not. At a high level I'm trying to do run CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy') using the django modeling. Model class Person(models.Model): class Mood(models.TextChoices): Sad = 'sad' Ok = 'ok' Happy = 'happy' name = models.CharField() mood = models.CharField(choices=Mood.choices) Generated Migration class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('mood', models.CharField(choices=[('sad', 'Sad'), ('ok', 'Ok'), ('happy', 'Happy')], max_length=10)), ], ), ] -
Page not found (404) : When try to view a page in django
am new to django , so i wrote a simple program to go to Page2 from Page1 using a link in Page 1 and from Page2 to Page 1 using another link in Page 2, but it is showing Page Not Found . urls.py from django.contrib import admin from django.urls import path from website import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Index,name='IndexPage'), path('darkmode', views.darkmode,name='darkmode'), ] views.py def Index(request): return render(request,'Page1.html') def darkmode(request): return render(request,'Page2.html') Page1.html <div data-url="{% url 'darkmode' %}" class="dark-mode-switcher cursor-pointer shadow-md fixed bottom-0 right-0 box dark:bg-dark-2 border rounded-full w-40 h-12 flex items-center justify-center z-50 mb-10 mr-10"> <div class="mr-4 text-gray-700 dark:text-gray-300">Dark Mode</div> <div class="dark-mode-switcher__toggle border"></div> </div> Page2.html <div data-url="{% url 'Index' %}" class="dark-mode-switcher cursor-pointer shadow-md fixed bottom-0 right-0 box dark:bg-dark-2 border rounded-full w-40 h-12 flex items-center justify-center z-50 mb-10 mr-10"> <div class="mr-4 text-gray-700 dark:text-gray-300">Dark Mode</div> <div class="dark-mode-switcher__toggle dark-mode-switcher__toggle--active border"></div> </div> and am not able to figure put why this happened , Can anyone help me to figure this out -
CommandError: Unable to serialize database
I've checked every solution but can't get it. Actually, I'm new to Django. python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 4 > project_dump.json this is suggested by the instructor so I use it but whenever I enter this code I got this error you can see the error in this image Can anyone know what to do? -
Why is my form text input value POSTing as list?
My form field value is being received as a list and I can't figure out why. I need it to just be a string. form <form id="design-brief-3" name="design-brief-3" data-name="Design Brief 3" class="contact-form" method="POST" action="{% url 'project-design' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-field-container"> <label for="business_slogan" class="form-field-label">Business Slogan/Tagline/Mission Statement</label> <input type="text" class="form-field w-input" maxlength="256" name="business_slogan" data-name="business_slogan" placeholder="If we say 'Just Do It' you know what we mean." id="business_slogan" required=""/> </div> <div class="form-field-container"> <label for="essential_content" class="form-field-label">Essential Content</label> <textarea required="" maxlength="5000" id="essential_content" name="essential_content" data-name="essential_content" placeholder="Please include any content you have, it can be as long as you want." class="form-field message w-input"></textarea> </div> <div class="form-field-container"> <label for="logo" class="form-field-label">If you have a logo, upload it here.</label> <input type="file" class="form-field w-input" name="logo" data-name="logo" placeholder="Who is your ideal client?" id="Logo"/> </div> <div class="form-field-container"> <label for="#id_file" class="form-field-label">Additional files, such as page copies & additional images, you can upload multiple.</label> <input type="file" class="form-field w-input" name="#id_file" data-name="#id_file" id="#id_file" multiple="multiple"/> View: def projectdesign(request): if request.POST: print(request.POST) return render(request, 'users/projectdesign.html', context) Output: <QueryDict: {'csrfmiddlewaretoken': ['9p3NTDraxyssQZNdavUSrUaJaT1rQTIImn5rMnjm1F'], 'business_slogan': ['Just do it'], 'essential_content': ['sdsdsad'], 'logo': [''], '#id_file': ['']}> -
Django Customize read-only view in ModelAdmin
I have an ModelAdmin that, with a certain condition, makes has_change_permission equal to false. This makes all fields read-only when attempting to edit a model instance. But how am I able to customize these read-only fields? In particular, in this read-only view, I want: To be able to see a field that is excluded from the creation form (with exclude=[field]). To be able to make certain character fields hyperlinks. -
I want to preserve line breaks in CharField in Django REST framework
I'm using a CharField in the Django REST framework to store text, but how can I preserve line breaks in the API? In the case of Django templates, I think line breaks are possible with {{ value|linebreaksbr }}, but what about the Django REST framework? I would appreciate it if you could tell me how to do this. -
Django Rest-Framework-Simplejwt not working with modheader
I am working on some projects and trying to the list view of the book. I used Django Rest-Framework-Simplejwt to generate tokens and mod header for authentication. When I tried to request a token for a user such as the admin user, and enter it into the mod header, the request is still unauthorized. I tried to do it a couple of times, but still not working. Views.py from rest_framework import generics, permissions from rest_framework.permissions import IsAuthenticated from rest_framework.exceptions import ValidationError from django.contrib.auth.models import User from .models import Book from .serializers import ( BookSerializer, RegistrationSerializer ) class BookCreateView(generics.CreateAPIView): """Create a Book""" queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) class BookListView(generics.ListAPIView): """Show all books""" serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Book.objects.filter(user=user) class BookDetailView(generics.RetrieveAPIView): """Show detail of the book""" serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Book.objects.filter(user=user) class BookUpdateView(generics.RetrieveUpdateDestroyAPIView): """update detail of the book""" queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def delete(self, request, *args, **kwargs): book = Book.objects.filter(user=self.request.user, pk=kwargs['pk']) if book.exists(): return self.destroy(request, *args, **kwargs) else: raise ValidationError('Book is not yours!') def perform_update(self, serializer, **kwargs): book = Book.objects.get(pk=self.kwargs['pk']) if self.request.user != book.user: …