Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to connect two models having same foreign key inside django template?
I have 2 models. The models are given. Both of these models use User as foreign key. class Comment(models.Model): text = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') date_published = models.DateTimeField(auto_now_add=True) reply_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.text class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=100) city = models.CharField(max_length=100) postal_code = models.CharField(max_length=20) phone = models.CharField(max_length=20) profile_picture = models.ImageField(upload_to=path_and_rename) occupation = models.CharField(max_length=100) organization = models.CharField(max_length=100) def __str__(self): return self.user.username Now I want to access the profile picture from comment objects inside my django template. I have tried this. <img alt="" src="{{comment.author.profile.profile_picture.url}}" class="avatar avatar-120 photo" height="120" width="120"><span But it doesn't get the url of the image. I don't understand how can I make a relation between these two models inside the template. -
Is there a way to convert django-filter result to pdf
I am using Django-filter to filter out data and export to csv table I want to export the same data to pdf but I am having trouble using xhtml2pdf and reportlab I tried xhtml2pdf but it convert the whole page to pdf with filtering the data and with report I can’t pass the database data to the context -
Paginate data without a queryset in Django?
The Django Pagination object takes a QuerySet to query the database. I have some information I can generate, but it doesn't come directly from the database. Instead, it is derived. Is there an object that can help me paginate it, or should I just re-implement my own pagination? In this sort-of related question, they just made their own paginator. -
MultipleObjectsReturned at /add-to-cart/ get() returned more than one Cart -- it returned 2
MultipleObjectsReturned at /add-to-cart/ get() returned more than one Cart -- it returned 2! @login_required def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') if Cart.objects.filter(product=product_id).exists(): prod_id = request.GET['prod_id'] try: product = Cart.objects.get(product=prod_id) except Cart.DoesNotExist: product = None c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) c.quantity += 1 c.save() user = request.user cart = Cart.objects.filter(user=user) amount = 0 for p in cart: value = p.quantity * p.product.discounted_price amount = amount + value totalamount = amount + 300 print(prod_id) data = { 'quantity': c.quantity, 'amount': amount, 'totalamount': totalamount } return redirect('/cart') else: pass product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect('/cart') I tried, please help me. The product does not want to be added to the user if it is in the basket of another. -
How to use backup db.sqlite3 after delete the current file by accident
I accidentally deleted my db.sqlite3, however, I have a backup of this file yesterday. I tried to copy the backup file and run showmigrations but I don't know why there is a lot of migrations that were not applied. Even from yesterday, I didn't create and migrate any migrations. Could you please help me explain that and tell me what to do now? Thank you. P/S: I know that I didn't create a backup file correctly, what I did is just copy the db.sqlite3 to the backup folder :( Is it possible to use only the backup file to recover all the data? Thanks. -
Using Docker Django Alpine MSSQL pyobdc
I am trying to run a docker container that can run a Django application with the mssql-django to connect to MSSQL server. However I cannot get the dependency of pyodbc to install correctly. Any help appreciated :) requirements.txt Django>=4.0.5,<4.1 uWSGI>=2.0.18,<2.1 mssql-django>=1.1.3,<1.2 Dockerfile FROM python:3.8-alpine COPY ./requirements.txt /requirements.txt RUN apk add python3 python3-dev g++ unixodbc-dev RUN python3 -m ensurepip RUN pip3 install pyodbc --no-binary pyodbc RUN pip3 install --user -r /requirements.txt RUN apk update Error django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: Error loading shared library libodbc.so.2: No such file or directory (needed by /usr/local/lib/python3.8/site-packages/pyodbc.cpython-38-x86_64-linux-gnu.so) I have found the following reference and implemented but I am still receiving the error message noted above. https://github.com/mkleehammer/pyodbc/wiki/Install -
How to log webpage access information in django
I trying to log URLs accessed by user to the database. For this I have implemented django middleware as explained here. Below I have reproduced the relevant code: Model for logging class UserPageTracking(models.Model): """ Page hits with user info """ id = models.AutoField(db_column='ID', primary_key=True) user_id = models.CharField(db_column='USER_ID', max_length=8, default="") url = models.URLField(db_column='URL') date_visited = models.DateTimeField(db_column='DATE_VISITED', auto_now_add=True) class Meta: managed = True db_table = 'page_views' The middleware from .models import UserPageTracking class UserPageTrackingMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user_id = request.user.username # not every request will have a http_referer, so when it doesn't just ignore it and don't save anything to_url = request.META.get('HTTP_REFERER') if to_url: user_page_tracking = UserPageTracking.objects.create( url=to_url, user_id=user_id ) user_page_tracking.save() return response settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # ... 'app.middleware.user_page_tracking.UserPageTrackingMiddleware' ] This is working, but somewhat not as expected. I am running react client in one docker container accessible at http://127.0.0.1:9001/ and my django server is running in another docker container accessible at http://0.0.0.0:3000/. So the middleware is not actually logging web page urls that are accessed, but it ends up logging REST end points accessed which are exposed by django at http://0.0.0.0:3000/. Most webpages have at least one REST request. … -
Template Syntax for images [closed]
[[enter image description here] [enter image description here] enter image description here Hi i am New to django and while I am learning and do this by my own i am getting this error I need solution which may be easy to use and easy to learn can anyone help me in this problem in settings.py is correct -
How can I run my django project in server to run strongest?
What is the run command in django project when will run in server? I have tried run with command python manage.py runserver --insecure. But I am not sure it is good idea for project run strong and it's normal run project with --insecure for serve static files. -
Fatal error in launcher: Unable to create process using Virtual environment pip error
The following error occurs when pip is used in a virtual environment. (env) PS C:\Users\xxx\Documents\プログラミング\project_users4_Croppie_complete_challenge_2> pip install django Fatal error in launcher: Unable to create process using '"C:\Users\xxx\Documents\???????\project_users4\env\Scripts\python.exe" "C:\Users\xxx\Documents\???????\project_users4_Croppie_complete_challenge_2\env\Scripts\pip.exe" install django': ?????????????????? Outside the virtual environment, pip can be used without any problem. How can I solve this problem? -
Node.js and/or npm is not installed when running "docker-compose up"
I am trying to Dockerize a Django app with tailwind to deploy to lightsail. I followed two tutorials. Their githubs are: https://github.com/LondonAppDeveloper/tutorial-django-aws-lightsail https://github.com/timonweb/django-tailwind Both work individually. Now I am trying to combine the both. I started with the django-tailwind guide, then added the code from the first tutorial to it. When I run docker-compose build it builds (19/28) of the commands, I assume. When I run docker-compose up I get the error gmo-django-lightsail-tailwind-1 | CommandError: gmo-django-lightsail-tailwind-1 | It looks like node.js and/or npm is not installed or cannot be found. gmo-django-lightsail-tailwind-1 | gmo-django-lightsail-tailwind-1 | Visit https://nodejs.org to download and install node.js for your system. gmo-django-lightsail-tailwind-1 | gmo-django-lightsail-tailwind-1 | If you have npm installed and still getting this error message, set NPM_BIN_PATH variable in settings.py to match path of NPM executable in your system. gmo-django-lightsail-tailwind-1 | gmo-django-lightsail-tailwind-1 | Example: gmo-django-lightsail-tailwind-1 | NPM_BIN_PATH = "/usr/local/bin/npm In my settings.py I have "NPM_BIN_PATH = r"C:\Program Files\nodejs\npm.cmd" included. Here is my Dockerfile: FROM python:3.11.1-alpine3.17 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache \ postgresql-client \ build-base \ postgresql-dev \ musl-dev \ zlib \ zlib-dev \ linux-headers WORKDIR /gmo RUN apk add --no-cache \ musl-dev \ curl \ nodejs RUN python -m venv … -
STRIPE ERROR: stripe.error.InvalidRequestError: Request req_Z2KfeZdvlmvT: Missing required param: business_profile
In stripe it is mentioned that buisness_profile is required but the child parameters are option and I am still getting this error stripe.error.InvalidRequestError: Request req_Z2KfeZdvlmvT: Missing required param: business_profile. Here's the link. response = stripe.billing_portal.Configuration.create( business_profile={ 'headline': None, 'privacy_policy_url': None, 'terms_of_service_url': None }, features={ 'customer_update': { 'allowed_updates': ['name', 'email', 'address', 'phone'], 'enabled': True }, 'invoice_history': { 'enabled': True }, 'payment_method_update': { 'enabled': True }, 'subscription_cancel': { 'cancellation_reason': { 'enabled': True, 'options': ['too_expensive', 'switched_service', 'unused', 'other'] }, 'enabled': True, 'mode': 'immediately', 'proration_behavior': 'create_prorations' }, 'subscription_pause': { 'enabled': False }, 'subscription_update': { 'default_allowed_updates': [], 'enabled': False, 'proration_behavior': 'always_invoice' } }, login_page={ 'enabled': True, } ) what is the possible reason for this error? -
How to test a mixin for a
Inside a project I am working on is a Django "app" with a few of mixins/base classes that work together with DRF's ModelViewSets to handle everything related to soft deleting. The app is at the very bottom the dependency hiearchy and does not contain any routes. I would like not to have to use any models, viewsets, serializers or routes from any other app. Rather I would like to create a set of temporary models, viewsets, serializers, and routes that only exist while the test is running. So far I have the following: from datetime import datetime from django.db import models from rest_framework import viewsets from rest_framework import serializers from rest_framework import routers from rest_framework.test import APITestCase from soft_delete.mixins import SoftDeleting from soft_delete.models import SoftDelteable class TestModel(SoftDelteable): name = models.CharField(max_length=255) class TestSereializer: class Meta: model = TestModel fields = "__all__" class TestViewSet(SoftDeleting, viewsets.ModelViewSet): queryset = TestModel.objects.all() class TestSoftDelete(APITestCase): def setUp(self): self.router = routers.DefaultRouter() self.router.register(r"test", TestViewSet) self.d1 = TestModel.objects.create(name="D1", deleted_at=datetime.now()) self.d2 = TestModel.objects.create(name="D2", deleted_at=datetime.now()) self.a1 = TestModel.objects.create(name="A1") self.a2 = TestModel.objects.create(name="A2") def test_cant_list_deleted(self): response = self.client.get("/test/") self.assertEqual(len(response.data), 2) def test_can_retrieve_deleted(self): id = self.d1.id response = self.client.get(f"/test/{id}") self.assertEqual(response.status_code, 200) When I try to run this I get: TestModel doesn't declare an explicit app_label … -
Django Rest-Framework `ImproperlyConfigured - Could not resolve URL for hyperlinked relationship using view name "<model>:detail"`
I have this exception when I try to access to the endpoint named /clients/ : django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "client-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I have tried a lot of solutions seen online, but no one works : Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail" Django Rest Framework, improperly configured lookup field You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField For the context, each client is a user (django user) and to know if a user is a client, it has to be in the table client in my database. So I want when I use the endpoint /clients/ to have informations about the user linked to the client (I use this system because I will have two types of user, the 2th isn't created yet). There is my code : user/models.py : class UserManager(BaseUserManager): use_in_migration = True def create_user(self, mail, name, … -
Does Nginx get blocked by JS await?
In my project I have Nginx, Django and JQuery. I'm using JQuery post requests to call Django functions and sometimes it takes awhile to complete. The problem is it looks like when I'm using async/await function with post, it blocks Nginx entirely until the task is completed. I can't even open a new tab or open my project on another computer How can I fix that? Or should I use Celery instead? JS function example: async function very_long_function(params) { // some code await $.post(post_params).done(function (data) { // some code with data Django returned }) // some code that has to be after } -
How to properly re-initiate django-autocomplete-light after htmx get request
I am successfully using HTMX to create and edit content without reloads on my pages (I am following this method: https://blog.benoitblanchon.fr/django-htmx-modal-form/). For my model, I use django-autocomplete-light to select multiple colors conveniently. This works fine the first time. However, when I close the modal and re-open it (recreate it with an HTMX get request), the multi-select element is shown twice, once how it is not supposed to be shown and once as expected, see screenshot here: https://i.stack.imgur.com/eArEE.png. I fixed similar JS issues by re-initiating relevant Javascript code with the htmx.onLoad(function(content) { function. Can you help me understand what I need to put there to re-initiate the django-autocomplete-light element? Thanks a lot! -
Django-recurrence widget not working without staff permissions
The superuser can access the widget and use it fine but a user which signed up using the website can't, when they click on it nothing happens. I've tried all the other solutions on here but nothing works including adding form.media using the JavaScript catalogue. Forms.py: class RecurringAbsencesForm(forms.ModelForm): class Meta: model = RecurringAbsences fields = ['ID','Recurrences'] def clean(self): cleaned_data = super().clean() class Media: js = ('/admin/jsi18n', '/admin/js/core.js',) HTML: {% extends 'Base.html' %} {% load bulma_tags %} {% block title %}Create Recurring Absence{% endblock %} {% load static %} {% block content %} <head> <script type="text/javascript" src="/admin/jsi18n"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> {{form.media}} </head> <div class="main container column is-3"> <h1 class="title has-text-centered"> Create Recurring Absence </h1> <form method="POST" class="post-form"> {% csrf_token %} <div class="container has-text-weight-bold"> {% csrf_token %} {% if message %} {% include "messages.html" %} {% endif %} {{ form }} {{ form.media }} {% for error in form.errors %} {% endfor %} <div class="pt-6 pb-3"> {{ form2 | bulma }} </div> <button id="submit" type="submit" class="button is-fullwidth is-link">Submit</button> </div> </form> </div> {% endblock %} Included in Urls.py url(r'^jsi18n', JavaScriptCatalog.as_view(), js_info_dict), -
I have trouble connecting my Django REST api to Flutter mobile app
I'm making an Android application, that has Django REST api. Didn't have any trouble setting up the api, but I can't connect it to my application. I'm really new to it, so... I tried running my app through Chrome browser. I have already disabled web security, but still I get this error: unawaited(xhr.onError.first.then((_) { // Unfortunately, the underlying XMLHttpRequest API doesn't expose any // specific information about the error itself. completer.completeError( ClientException('XMLHttpRequest error.', request.url), StackTrace.current); })); No success in Android emulator either, right now I'm reinstalling it. I have created database through Django models and admin. Right now it's quite simple, I need my app to get the title, annotation and image url from Shows model. At for(var v in data) line I get an error type 'String' is not a subtype of type 'Iterable<dynamic>' This is my api_handler: class APIHandler { static Future<List<ShowsModel>> getAllShows() async { var uri = Uri.http( BASE_URL, "/show", ); var response = await http.get(uri); var data = jsonDecode(jsonEncode(response.body)); List tempList = []; for (var v in data){ tempList.add(v); } return ShowsModel.showsFromSnapshot(tempList); } This is my Shows model: import 'package:flutter/material.dart'; class ShowsModel with ChangeNotifier { int? id; String? name; String? annotation; List<String>? image; ShowsModel({this.id, this.name, this.annotation, … -
Getting no results from an IBM Cloud Function that uses IBM Cloudant
My cloud function is meant to return all documents in the dealerships database, but I am getting {}. In the activation log its showing that all records have been sent successfully. The problem occurs at dealers = json_result["entries"] because json_result is an empty object. Tried to Expecting value: line 1 column 1 (char 0). The serverless function is at the bottom of the file. def get_dealerships(request): if request.method == "GET": url = "serverless-func-url" context = { "dealerships": get_dealers_from_cf(url), } # Prints {} evry time print(f'test {context["dealerships"]}') return render(request, 'djangoapp/index.html', context) def get_dealers_from_cf(url, **kwargs): results = [] # Call get_request with a URL parameter json_result = get_request(url) if json_result: # Get the row list in JSON as dealers # Error dealers = json_result["entries"] # For each dealer object for dealer_doc in dealers: # Create a CarDealer object with values in `doc` object dealer_obj = CarDealer( address=dealer_doc["address"], city=dealer_doc["city"], full_name=dealer_doc["full_name"], id=dealer_doc["id"], lat=dealer_doc["lat"], long=dealer_doc["long"], short_name=dealer_doc["short_name"], st=dealer_doc["st"], zip=dealer_doc["zip"], ) results.append(dealer_obj) return results def get_request(url, **kwargs): print(kwargs) print("GET from {} ".format(url)) try: # Call get method of requests library with URL and parameters response = requests.get( url, headers={'Content-Type': 'application/json'}, params=kwargs) except: # If any error occurs print("Network exception occurred") status_code = response.status_code print("With status {} ".format(status_code)) … -
Accessing browser IP address in django
I want to log an IP address from where particular url is accessed. I am implementing this functionality in django middleware. I tried obtaining IP address using method given in this answer: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip I debugged this method and found that request.META.get('HTTP_X_FORWARDED_FOR') was None. and request.META.get('REMOTE_ADDR') was 10.0.0.2. However, I dont understand from where this IP 10.0.0.2 came from. I am running django inside docker container on my laptop and accessing the website iniside the browser on the same laptop using address: http://127.0.0.1:9001/. So I thought ideally the address should be at least 127.0.0.1. The IP address allotted to my laptop by router is 192.168.0.100. The website will be used inside LAN. So I feel it will be more apt to log this IP address. But I checked all keys inside request.META dictionary and found none to contain IP address 192.168.0.100. Also following two keys inside request.META contain local IP: 'HTTP_ORIGIN':'http://127.0.0.1:9001' 'HTTP_REFERER':'http://127.0.0.1:9001/' Q1. From where the IP 10.0.0.2 obtained? Q2. What request.META key should I access to log IP address from which the website is accessed. -
How can I update user's data which is present in the Database(Mysql)[Django Framework]
I am working on a project where every user has a wallet as a field in their database model, when a button is pressed by the user in the frontend the wallet field should be incremented by a value which is present in another database model and that wallet field should get updated. How can I implement in the code, should I use onclick() function or any other functions like AJAX. I want someone to explain the methods and process to achieve this functionality. -
How Can I add Extra Login Field to Django App and use session to identify User
I am working a Django Real Estate Management website where I want users to choice their Categories (Landlord, Agent, Prospect) upon registration and login. For the Registration I did it but for the User login I am unable to add extra user login field for successful login. Django Form Code: USER_TYPE_CHOICES = ( ('landlord', 'Landlord'), ('agent', 'Agent'), ('prospect', 'Prospect'), ) class UserLoginForm(forms.Form): user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES, widget=forms.Select(attrs={'class': 'form-control left-label'})) Django Login View code: class MyLoginView(LoginView): template_name = 'account/login.html' authentication_form = UserLoginForm def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['user_type'] = forms.ChoiceField( label='User Type', choices=[('landlord', 'Landlord'), ('agent', 'Agent'), ('prospect', 'Prospect')], widget=forms.Select(attrs={'class': 'form-control left-label'}) ) return form def form_valid(self, form): user = form.get_user() user_type = form.cleaned_data['user_type'] # Check if the selected user type matches the user's actual user type if user_type == 'landlord' and not user.profile.landlord: messages.error(self.request, 'Invalid user type for this user.') return self.form_invalid(form) elif user_type == 'agent' and not hasattr(user, 'agent'): messages.error(self.request, 'Invalid user type for this user.') return self.form_invalid(form) elif user_type == 'prospect' and not hasattr(user, 'prospect'): messages.error(self.request, 'Invalid user type for this user.') return self.form_invalid(form) login(self.request, user) self.request.session['user_type'] = user_type return super().form_valid(form) Anytime I try loading the login page this is the error: init() got an unexpected keyword argument 'request' … -
Django module 'home.views' has no attribute 'IndexView'
Django newbie going through a tutorial, broke my site. It was working but now it's not and I have no idea what I've done wrong. My url is here, returning an error message: My urls.py file looks like this: from django.contrib import admin from django.urls import include,path from django.views.generic import TemplateView urlpatterns = [ path('', include('home.urls')), path('polls/', include('polls.urls')), path('hello/', include('hello.urls')), path('home/', include('home.urls')), path('admin/', admin.site.urls), ] Specifically path('', include('home.urls')), strikes me as the line of code of interest. Therefore I look in my home/urls.py and see the following: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.IndexView.as_view(), name='index') ] I changed the code above to the following: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.IndexView.as_view(), name='IndexView'), path('', views.IndexView.as_view(), name='index') ] But get the same error. Thank you for helping the newbie :) -
why star rating is not saving?
so i have wrote this code problem is when i click on stars it should be saved but it doesnt save when i check database i tried submit button too but didnt work it doesnt give any errors too :( this is my model class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) class Rating(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='ratings') stars = models.IntegerField(default=0, validators=[MinValueValidator(1), MaxValueValidator(5)]) and this is my view def rate_comment(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) stars = request.POST.get('stars') if stars: Rating.objects.create(comment=comment, stars=stars) return redirect('blog/blog-detail.html', pk=comment.post.pk) this is url.py path('<id>/', rate_comment, name='rate_comment'), blog-detail.html: <div> <!-- start rating system --> <div> {% for rating in comment.ratings.all %} {% for i in "12345" %} {% if i|add:"-1" < rating.stars %} <span class="fa fa-star checked"></span> {% else %} <span class="fa fa-star"></span> {% endif %} {% endfor %} {% endfor %} <div class="rating" style="text-align:center;" > <input type="radio" id="star5" name="stars" value="5" /> <label for="star5" class="fa fa-star"></label> <input type="radio" id="star4" name="stars" value="4" /> <label for="star4" class="fa fa-star"></label> <input type="radio" id="star3" name="stars" value="3" /> <label for="star3" class="fa fa-star"></label> <input type="radio" id="star2" name="stars" … -
Accessing logged in user name inside django middleware
I am trying to access request.user.username inside following django middleware: class MyMiddleware(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user_id = request.user.username # ... I ensured that MyMiddleware appears after SessionMiddleware and AuthenticationMiddleware in the settngs.py: MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # ... `my_app.my_py_file.MyMiddleware` ) But still the request.user.username turns out to be an empty string. Q1. Why is it so? I also tried adding @authentication_classes([TokenAuthentication,]): from rest_framework.authentication import TokenAuthentication # <-- from rest_framework.decorators import authentication_classes # <-- @authentication_classes([TokenAuthentication,]) # <-- class MyMiddleware(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user_id = request.user.username # ... But no help. I also tried making class APIView (though it looks stupid as middleware is not a REST API): from rest_framework.authentication import TokenAuthentication # <-- from rest_framework.views import APIView # <-- class MyMiddleware(APIView): # <-- authentication_classes = [TokenAuthentication] # <-- def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user_id = request.user.username # ... Still, it did not work. Then I came across this answer. It says: If you use simple_jwt, it's not possible to directly use request.user in a middleware because authentication mechanism works in view function. So you should …