Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
peerjs call.on("close") doesnt work. Can anyone help me?
I am developing a django project using with peerjs to make a video call and voice call..In my project everything works fine but if other user reject the my call , call.on("close",...) does not triggered. So I can not close calling modal from screen. document.getElementById("endCallButton").click(); and endCall(); does not work . Can anyone help me to fix that? const peer = new Peer(); var currentCall; peer.on("open", function (id) { $.ajax({ type: "GET", url: "/createPeerIdToUser", data: { 'peerId': id, }, }); }); async function callUser() { // get the id entered by the user const peerId=otherUserPeerId; const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true, }); document.getElementById("chatPart").style.display = "none"; document.getElementById("videoCallPart").style.display = "block"; document.getElementById("video2").srcObject = stream; document.getElementById("video2").play(); // make the call const call = peer.call(peerId, stream); call.on("stream", (stream) => { document.getElementById("video1").srcObject = stream; document.getElementById("video1").play(); document.getElementById("endCallButton").click(); }); call.on("data", (stream) => { document.querySelector("#video1").srcObject = stream; }); call.on("error", (err) => { console.log(err); }); //this part doesnt't triggered call.on("close", () => { document.getElementById("endCallButton").click(); endCall(); }); currentCall = call; } peer.on("call", (call) => { let nameOfuser="" let isSuccess="false"; $.ajax({ type: "GET", url: "/getOtherUserByPeerId", dataType: 'JSON', data: { 'peer': call.peer, }, success: function(data) { document.getElementById("comingRequestButton").click(); document.getElementById("comingRequestName").textContent=data.username; nameOfuser=data.username; isSuccess="true"; }, error: function(err) { console.log(err); }, }); document.getElementById("comingRequestYellow").addEventListener("click", function() { … -
How do I call my Django REST API endpoint with CURL?
I want to call my Django REST Framework API using cURL, but it doesn't do anything. My URL is like "https://MYURL/api/seedevents?secret=SECRET". In postman this works and returns a 201 Created HTTP response. If I call using CURL for example "curl -XGET 'https://MYURL/api/seedevents?secret=SECRET', then it doesn't do anything at all. I can see the request come in in the logs, but it just doesn't do anything. Please can someone advise me what I can do? -
property method and other methods in django models
I have been using the property method every now and then and understand its uses. It basically acts the same as the field but without actually creating a column in db, and can be easily accessed within the serializer as model fields. But how can the other methods be accessed just like this baby_boomer function of Person model here below? How can it be accessed in serializer and also in the views or queryset?? class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" @property def full_name(self): "Returns the person's full name." return '%s %s' % (self.first_name, self.last_name) -
My Models info wont appear on new page but it does on the previous one
Within my Django implementation I created a model that would show my information that I stored on the admin in the website. I managed to create the public page to have links of name attribute within the model but when I try to do the same on the viewpara page after going to it from the links I can't manage to get any of the attributes of the model to appear on this page and I am confused as to why. models.py class Parasite(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=100000) image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Parasite, self).save(*args, **kwargs) def __str__(self): return self.name views.py def public(request): c = Parasite.objects.all() context = {'c': c} return render(request, 'parasites_app/public.html',context) def view_parasite(request,parasite_name_slug): context_dict = {} try: parasite = Parasite.objects.get(slug=parasite_name_slug) context_dict['parasites'] = parasite except Parasite.DoesNotExist: context_dict['parasites'] = None return render(request, 'parasites_app/viewpara.html', context = context_dict) urls.py path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('admin/', admin.site.urls), path('', views.public, name='public'), path('public/', views.public, name='public'), path('private/', views.logged_in_content, name='private'), path('viewpara/',views.public,name='viewpara'), path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'), path('<slug:post_name_slug>/', views.show_post, name='show_post'), public.html <!DOCTYPE html> {% extends 'parasites_app/base.html' %} {% load static %} {% block content_block %} <h1>Public Page</h1> <h2>Information based on series of Parasites</h2> {% for p … -
Django can't find page to redirect after adding data
I want to add data in my admin panel, but cannot find the page to redirect. The bus is working correctly when I check it with httppresponse but it doesn't redirect after adding the data My directory structure is as follows: AppName/ app/ views.py templates/ admintemplates/ adminpage/ page.html adminurls.py: app_name = "upadmin" urlpatterns = [ path(r'', views.index, name="anasayfa"), path(r'login', views.login, name="login"), path('firma', views.firma_views, name="firma"), path(r'firmaekle', views.firmaekle, name="firmaekle") ] views.py def firmaekle(request): if request.method == 'POST': form = FirmaForm(request.POST) context = { "form":form } if form.is_valid(): firmaek = form.save(commit=False) firmaek.lisanstarihi = datetime.now() firmaek.save() messages.success(request, "Kayıt Başarılı!") return redirect('upadmin:firma') -
Retrieve all data from query
I keep struggling with Django Model, Managers' relations. I have a Profile model, Product Model, and Holding model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) products = models.ManyToManyField(Product, blank=True, through='Holding') def __str__(self): return str(self.user) class Product(models.Model): product_name = models.CharField(max_length=255, blank=False, unique=True) product_slug = models.CharField(max_length=50, blank=True,null=True) product_symbol = models.CharField(max_length=50, blank=True,null=True) product_price = models.FloatField(blank=True,null=True) def __str__(self): return str(self.product_name) class Holding(models.Model): product_name = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product_holding = models.FloatField(max_length=50, blank=True, null=True) def __str__(self): return str(self.product_name) I'm trying to retrieve the data from a user (Profile) for a Product within Holding Basically I want to show the amount of a product a user is currently holding. I'm doing this in my view def show_product_details(request, product_name): product = product.objects.get(Product_name=product_name) ... profile = Profile.objects.get(user = request.user) product_holding = profile.holding_set.get(product_name__product_name = product_name) return render(request, 'productdetails.html', {'product_holding':product_holding ...} But this isn't returning all the data, but instead just the product_name. What am i doing wrong.? :( -
Basic practice for throwing exception/error from function
For example I have script like this def form_valid: temp = form.save(commit=False) try: temp.contents = makecontents() except: messages.error(self.request, error) return self.render_to_response(self.get_context_data(form=form)) messages.success(self.request, self.success_message) return super().form_valid(form) def makecontents(): if (if works well): return "this is my contents" else: return "this is error!!" So, my basic idea is when makecontents() success it returns the string s and set this as member of model instance. However makecontents() failed , I want to return the error to form_valid. So, maybe ,, I should change return "this is error!!" somehow.. Is it possible? , or my idea is wrong?? -
Django Error sub-select returns 3 columns - expected 1
My problem is 2 fold What I'm trying to do I'm trying to create a profile edit form for the teachers profile I'm trying to assign query_sets to the request.POST dictionary and I'm getting this error when I try to filter I noticed that the output of request.POST['course_teaching'] is always the last item in the list instead of all the items in it e.g if request.POST['course_teaching'] = ['1','6'] it gives only 6 The model class ClassLevel(models.Model): readonly_fields = ('id',) level = models.CharField(max_length=100) def __str__(self): return str("{} - {}" .format(self.id, self.level)) # School profile class SchoolProfile(models.Model): school = models.OneToOneField(School, default=1, on_delete=models.CASCADE) classLevel = models.ManyToManyField(ClassLevel) def __str__(self): return "{}" .format(self.school) # Course is list of courses class Course(models.Model): course_name = models.CharField(max_length=100) class_level = models.ForeignKey(ClassLevel, on_delete=CASCADE) def __str__(self): name_level = "{}, {}" .format(self.course_name, self.class_level) return name_level # Teacher Profile class Teacher(models.Model): readonly_fields = ('id', 'course_taught') user = models.OneToOneField(User, default=1, on_delete=models.CASCADE) class_teaching = models.ForeignKey(ClassLevel, null=True, on_delete=models.CASCADE) course_teaching = models.ForeignKey(Course, null=True, on_delete=models.CASCADE) school = models.OneToOneField(School, null=True, max_length=200, on_delete=models.CASCADE) status = models.BooleanField(default=True) The form class profileForm(forms.ModelForm): school = forms.ModelChoiceField(queryset=models.SchoolProfile.objects.all()) class_teaching = forms.ModelMultipleChoiceField(queryset=models.ClassLevel.objects.all()) course_teaching = forms.ModelMultipleChoiceField(queryset=models.Course.objects.all()) class Meta: model = Teacher fields = ['school', 'class_teaching', 'course_teaching',] labels = {'class_teaching':'class_teaching', 'course_teaching':'course_teaching', 'school':'school',} The view def profile_edit(request): form = … -
How to generate a Django one-time download link with expire time
I am uploading files using the filefield model on media-root. Well, now I have a link like this : domain.com/media/file_name.file_extension.I'm asking about the best way to generate a one-time link with expire time from this main link for each user who clicks on file to download it. class files(models.Model): title = models.CharField(max_length=50) picture = models.ImageField(upload_to='imges') desc = models.TextField() created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) download = models.FileField(upload_to='files') def __str__(self): return self.title this is my views: def download(requset ,title): file = get_object_or_404 (files , title=title) try : file = files.objects.filter(title = title) except : raise Http404 context ={ 'file' :file, } return render( requset,'download.html',context) this is my template: <div class="fix download_button"><a href="{{f.download.url}}"></a></div> this is my url: path('download/<str:title>/' , views.download , name='download'), -
IntegrityError at /register/ NOT NULL constraint failed: auth_user.description
I'm in the last stages of deploying my django application onto a web server, but recently have been getting this error when trying to register a new user IntegrityError at /register/ NOT NULL constraint failed: auth_user.description I re-ran the error with DEBUG turned on and it says that the direct cause of the problem is in line 17 in the register section of my views.py file, which looks like this: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit= False) username = form.cleaned_data.get('username') is_teacher = form.cleaned_data.get('is_teacher') if is_teacher == True: user.is_staff = True user.save() *LINE 17* else: user.is_staff = False user.save() messages.success(request, f'Tu cuenta se ha creado correctamente, ahora puedes iniciar sesión') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) The problem is that I don't understand why it's saying that's the problem, since I had tested that feature many times in my local server. Any kind of help would be greatly appreciated. -
Django Allauth block domain
I am currently working on Google and LinkedIn authentication with Django Allauth on the project. When a user wants to register via Google or LinkedIn, I need to prevent registration requests with gmail.com and ensure that they only register with business mail. As far as I understand, Allauth cannot provide me with this directly. What is the best practice to do that? -
Django Rest Framework change admin form
I want to change forms of admin page of DRF. below link shows how it can change the form. https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#a-full-example But the sample can affect only Django, not DRF? How can I change the DRF admin page form? -
Django template doesn't display the model items
sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model. The views, the template and the path (urls) were bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view. blog/models.py from django.shortcuts import render from blog.models import Article, Category # Create your views here. def list(request): articles = Article.objects.all() return render(request, 'articles/list.html', { 'title' : 'Articles', 'articles': articles } ) blog/urls.py from django.urls import path from . import views urlpatterns = [ path('list/', views.list, name='list_articles'), ] blog/views.py from django.shortcuts import render from blog.models import Article, Category # Create your views here. def list(request): articles = Article.objects.all() return render(request, 'articles/list.html', { 'title' : 'Articles', 'articles': articles } ) blog/list.html {% extends 'layouts/layout.html' %} {% block title %} {{title}} {% endblock %} {% block content %} <h1 class= "title">{{title}}</h1> {% for article in articles %} <article class="article-item"> {% if article.image != 'null' and article.image|length … -
How to add overwrite unique data using django-import-export?
I need to overwrite existing data from Microsoft Excel file & If the data is not in Database it should get added using Django Admin & Django Import Export. -
How can I get image url in queryset.values()?
I have a user model like this: class CustomUser(AbstractUser): ... email = models.EmailField(unique=True) profile_pic = models.ImageField(null=True, blank=True, upload_to=content_file_name) def content_file_name(obj, filename): ext = filename.split('.')[-1] filename = "profile_pic_{0}.{1}".format(str(obj.user.id), str(ext)) return os.path.join(filename) I know I can get the profile_pic image media path using user.profile_pic.url. But, how can I get the image media path in queryset.values()? I tried this queryset.values("profile_pic_url") and queryset.values("profile_pic__url") but It doesn't work. I can annotate the profile_pic using F-Objects and add the media path as a prefix using f-string like below users = queryset.annotate(image_path=F("profile_pic")).values("image_path") and then I can add prefix like f"/media/{user.image_path}" -
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image. I want to store that returned image in my Local Directory and then display it on the user interface. This is the Code of views.py that takes in an image and sends it to the Yolo Model, def predictImage(request): # print(request) # print(request.POST.dict()) fileObj = request.FILES['filePath'] fs = FileSystemStorage() filePathName = fs.save(fileObj.name, fileObj) filePathName = fs.url(filePathName) testimage = '.'+filePathName # img = image.load_img(testimage, target_size=(img_height, img_width)) img = detect_image(testimage) filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR filePathName = fs.url(filePathName) This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image, import numpy as np import cv2 def detect_image(img_path): confidenceThreshold = 0.5 NMSThreshold = 0.3 modelConfiguration = 'cfg/yolov3.cfg' modelWeights = 'yolov3.weights' labelsPath = 'coco.names' labels = open(labelsPath).read().strip().split('\n') np.random.seed(10) COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8") net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights) image = cv2.imread(img_path) (H, W) = image.shape[:2] #Determine output layer names layerName = net.getLayerNames() layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()] blob = cv2.dnn.blobFromImage(image, 1 / 255.0, … -
How to include ManyToMany Fields in DjangoRestFramework Post Request?
I have this serializer (there are more fields in entity model, but they're irrelevant since the only problem i have is with the M2M) class EntityServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' class EntityCreateSerializer(serializers.ModelSerializer): entity_service = EntityServiceSerializerThrough(read_only=True, source='serviceschedule_set', many=True) class Meta: model = Entity fields = '__all__' Model looks like this class Entity(models.Model): entity_service = models.ManyToManyField(Service, through='ServiceSchedule') class ServiceSchedule(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, on_delete=models.CASCADE) class Service(models.Model): service_name = models.CharField(max_length=256, null=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, default=None) The thing is, when i put in body "entity_service": [1,2] in the response i still get = []. Even though i have in my database Services with pk 1,2,3,4. Do you know how can i make it work? -
How to Implement CSP for Ckeditor in Django
I'm not using CDN or any link for CKEditor but I have PIP installed it using pip install django-ckeditor. I have added all necessary CSPs and CKEditor configurations in settings.py file but CKEditor is not working in html. In settings.py CSP_DEFAULT_SRC = ("'self'", ) CSP_BASE_URI = ("'none'", ) CSP_FRAME_ANCESTORS = ("'none'", ) CSP_FORM_ACTION = ("'self'", ) CSP_STYLE_SRC = ("'self'", 'cdnjs.cloudflare.com','fonts.googleapis.com', 'stackpath.bootstrapcdn.com', 'getbootstrap.com') CSP_SCRIPT_SRC = ("'nonce-value'", 'cdn.ckeditor.com','ajax.googleapis.com', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'unpkg.com', 'cdnjs.cloudflare.com', 'code.jquery.com', 'getbootstrap.com') CSP_IMG_SRC = ("'self'", 'cdn.ckeditor.com' ,'cdn0.iconfinder.com', 'media.giphy.com','res.cloudinary.com') CSP_FONT_SRC = ("'self'",'cdnjs.cloudflare.com','fonts.googleapis.com', 'fonts.gstatic.com') CSP_INCLUDE_NONCE_IN = ("script-src", "style-src") -
django.core.exceptions.FieldError: Cannot resolve keyword 'date' into field. Join on 'date' not permitted
Here, is my model serializer. class DailyCustomerBuySellAPIView(APIView): def get(self, request): customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by( 'date__date').annotate(available=Count('date__date')) serializer = CustomerBuySellSerializer(customer_buy_sell, many=True) return Response({"customer_buy_sell": serializer.data}) -
Django error: ModuleNotFoundError: No module named 'mydjangoprojstudentsstudents'
This is the error in my git bash console. I'm just beginning Django hence don't know where to search for the error. My settings.py file My urls.py file My apps Please let me know if I need to provide any more info. Any help would be appreciated. Thanks in advance. -
how to fix moduleNotfoundErreor on deplying Django app to Heroku?
I have been trying to deploy my django project on heroku but Heroku is not tracking my project app name as presented in the Procfile. Honestly django_profile_viewer is the excact name of the project that has my settings file... #My procfile web: gunicorn django_profile_viewer.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate #Heroku logs 2022-02-13T10:46:43.042362+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-02-13T10:46:43.042362+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-02-13T10:46:43.042363+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-02-13T10:46:43.042363+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_profile_viewer' 2022-02-13T10:46:43.042446+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-02-13T10:46:43.054936+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-02-13T10:46:43.154082+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [INFO] Shutting down: Master 2022-02-13T10:46:43.154125+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-02-13T10:46:43.344541+00:00 heroku[web.1]: Process exited with status 3 2022-02-13T10:46:43.459875+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-13T10:52:53.470088+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=profile-viewer-app.herokuapp.com request_id=430d2f5f-4ba3-4780-8cf8-ce1990237951 fwd="197.239.4.35" dyno= connect= service= status=503 bytes= protocol=https 2022-02-13T10:52:59.973950+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-13T10:53:04.200202+00:00 heroku[web.1]: Starting process with command `gunicorn django_profile_viewer.wsgi:application --log-file - --log-level debug` 2022-02-13T10:53:05.838609+00:00 heroku[web.1]: Process exited with status 3 2022-02-13T10:53:05.951233+00:00 … -
"FIELD_ENCRYPTION_KEY must be defined in settings" - encrypted_model_fields error
Python 3.8.10 Django 4.0.2 django-encrypted-model-fields: 0.6.1 I am using encrypted_model_fields to encrypt a model field. The field I am encrypting is a password used to access a user account for another app via an api. According to the docs I need to import the module and then wrap the model field as follows: Models.py from encrypted_model_fields.fields import EncryptedCharField account_password = EncryptedCharField(models.CharField(max_length=20, blank=True)) In addition to that I need to add a FIELD_ENCRYPTION_KEY to settings.py, which I have done, as per the docs. Settings.py FIELD_ENCRYPTION_KEY = os.environ.get('FIELD_ENCRYPTION_KEY') I have also added 'encrypted_model_fields' to installed apps in settings.py and the encryption key to .env, which is in place of the placeholder below..env: export FIELD_ENCRYPTION_KEY=my_encryption_key_place_holder When I run makemigrations I receive the following error: django.core.exceptions.ImproperlyConfigured: FIELD_ENCRYPTION_KEY must be defined in settings I have defined it - so why is it not found? -
Does anyone know how to use Django and Brownie libraries together (python)?
Does anyone know how to use Django and Brownie libraries together (python)? Thanks for any information. -
Django: background image it does not appear after Generating a PDF from HTML in my Django project
Hi people there i want to set a background image for my printout pdf , I have already rendered it from html to pdf. I have tried much solutions but it doesn't work with me to set a background (It doesn't appear); Here are my tries: First Try: go to models.py: and write this method: def image_as_base64(image_file, format='png'): if not os.path.isfile(image_file): return None encoded_string = '' with open(image_file, 'rb') as img_f: encoded_string = base64.b64encode(img_f.read()) return 'data:image/%s;base64,%s' % (format, encoded_string) then go to the class of the model that am working with and write this method : with specifying on the path of the image: Here is the code: class Formulaires(models.Model): def get_cover_base64(self): return image_as_base64('/home/diva/.virtualenvs/django-projects/example/static/img/background.png') then I have go to the template.html and call the method "get_cover_base64" that contain the path on the tag "div" from the body (background-image:) <body style="font-size: 12px; "> <div id="divid" style="padding: 0.01rem; background-image: "{{ post.get_cover_base64 }}";" class="container"> PS: 2nd try: i have tried storing online my image - background and call with url and also it doesn't work ; here is the code: <body style="font-size: 12px; background-image: url('https://....');> 3rd try: using the staic files <body style="font-size: 12px; background-image: url('{% static "img/background.png"%}');> --> it doesn't work with … -
Django 4.0.2 | Python 3.9.7 | TypeError: __init__() missing 1 required positional argument: 'get_response'
I wrote a custom authentication and added a csrf check middleware in the authentication process. I am calling the below function in the authentication function. def enforce_csrf(self, request): """ Enforce CSRF validation """ check = CSRFCheck() check.process_request(request) reason = check.process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise PermissionDenied('CSRF Failed: %s' % reason) The CSRFCheck() function is a custom middleware and it looks like this. class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): return reason Now when I am trying to process the request, which requires authentication, I am getting the error: TypeError: init() missing 1 required positional argument: 'get_response' the same code is working perfectly in Django 3.2 Now, as far as I was able to debug, the CSRFCheck function is expecting a get_response method which I don't know where it is coming from.