Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to initialize a GraphQL Client inside Django App
I'm building an API with Django, I want to query the Github GraphQL API, and I found this GraphQL client for python that suits my needs. But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure: . ├── LICENSE ├── README.md ├── api │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── setup.py Thanks in advance! -
Why does an axios post request to django get empty data?
Returns a 404 error Here is a request with react const addItemToBasket = (item) => { dispatch({type: ADD_ITEM_TO_BASKET, payload: item}) console.log(item.id, store.get('email')) axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' axios.post("http://localhost:8000/cart/add", { uid: item.id, amount: 1, email: store.get('email') }) .then((response) => { console.log(response.data) }) .catch((error) => { console.log(error); }); } Here is the django function -
How exactly should I be linking in NPM modules?
I'm updating all of my CSS and JS libraries, but I want to make sure I do it the right way this time. Let's take jQuery for example. First, I install with NPM. $ npm i jquery # from project root Then, I create symlinks to be included in my static directory. $ cd home/static/lib/js # also from project root $ ln -s ../../../../node_modules/jquery/dist/jquery.js $ ln -s ../../../../node_modules/jquery/dist/jquery.min.js Next, in that same js directory, I generate hashsums. $ openssl dgst -sha384 -binary jquery.js | openssl base64 /LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E $ openssl dgst -sha384 -binary jquery.min.js | openssl base64 ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2 Finally, I add to the head of my Django template (HTML). <head> <!-- jQuery JS (compressed) --> <script src="{% static 'lib/js/jquery.min.js' %}" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" ></script> <!-- jQuery JS (uncompressed) --> <!-- <script src="{% static 'lib/js/jquery.js' %}" integrity="sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E" ></script> --> </head> I comment out the uncompressed file to make page loading faster, but I leave the static URL for developers to see. It's hosted on the server, but it's not included in the head tag. Are there any steps I'm missing? Should I include an external link to a CDN? Should I actually include the compressed file instead of just a comment of it? Any … -
update formset with class based view
i've created web blog with django 2.2 each post has multiple images , but when i try to update the post images wont updated i use class based view class Post(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) title= models.CharField(max_length=100) #others class PostImage(models.Model): post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images') media_files = models.FileField(upload_to=random_url) and this my forms.py class PostImageForm(forms.ModelForm): class Meta: model = PostImage fields = [ 'media_files' ] class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = [ 'title','description',#and others ] my views.py PostImageFormSet = inlineformset_factory( Post,PostImage,form=PostImageForm,extra=1,can_delete=True,can_order=False ) class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Post form_class = PostUpdateForm template_name = 'posts/update_post.html' def get_context_data(self,**kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['images'] = PostImageFormSet(self.request.POST or None,self.request.FILES,instance=self.object) else: data['images'] = PostImageFormSet(instance=self.object) return data def form_valid(self,form): context = self.get_context_data() images = context['images'] with transaction.atomic(): if form.is_valid() and images.is_valid(): self.object = form.save() images.instance = self.object images.save() return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.username == post.user.username: return True return False def get_success_url(self): return reverse_lazy('post:post-detail',kwargs={'slug':self.object.slug}) my templates <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{images.management_form }} {{ form|crispy }} {% for img in images %} <label>{{img.media_files.label}}</label> {{img.media_files}} {% endfor %} <button type="submit" class="btn btn-block btn-primary">update</button> </form> i'm wondering why didnt update the posts image !? thanks for replay .. -
Python and django: how to set a filter value with a form
I have created the following model that give me the possibility to get all daily income: class Ricavi(models.Model): quantita=models.DecimalField() data_contabile=models.DateField() After that I have created a views.py that give me the possibility to collect my data in yearly and monthly view as following: ricavi = dict() total_ricavi=dict() for year, month, totale in(Ricavi.objects.values_list( 'data_contabile__year', 'data_contabile__month'). annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('ricavo')*(1+F('iva'))), output_field=FloatField())).values_list('data_contabile__year', 'data_contabile__month', 'totale')).filter(data_contabile__year=2019): if id not in ricavi.keys() : ricavi[id]=list(defaults) index=month-1 ricavi[id][index]=totale total_ricavi={'Ricavi Lordi': [sum(t) for t in zip(*ricavi.values())],} Now I have fixed the data_contabile__year equal to 2019 ad example. But I want to have the possibility to choose the year (ad example using a selection form). How could I get this result? -
django-private-chat /dialogs is empty
I followed the steps in guide in https://django-private-chat.readthedocs.io/en/latest/readme.html: base.html: {% block extra_js %}{% endblock extra_js %} settings.py: INSTALLED_APPS = ( ... 'django_private_chat', ... ) CHAT_WS_SERVER_HOST = 'localhost' CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'ws' urlpatterns = [ "other urls" url(r'^', include('django_private_chat.urls')), ] After starting the server I go to http://127.0.0.1:8000/dialogs/some-of-the-users and there is no result whatsoever, the page is empty. The console displaying: Uncaught ReferenceError: $ is not defined at username:128 django version= 3.0.6 python version= 3.7.6 and the latest version of django-private-messaging It's my first time implementing a chat app so I hope I'm not missing anything fundamental. Have a nice day! -
comparing DateField with timezone.now().date()
I am trying to compare DateFIeld with timezone.now().date() but its not giving the desired output: models.py: class Holiday_List(models.Model): name=models.CharField(max_length=30) holi_day=models.DateField(default=timezone.now()) def __str__(self): return '{}---{}'.format(self.name, self.holi_day) admin.py: def refresh(): flag=0 din=Holiday_List.objects.all() for aaj in din: if aaj.holi_day==timezone.now().date(): flag=1 break; if(flag==0): # some code to be executed I have objects with today's date in the Holiday_List but still the flag value is not being set to 1 and the code gets executed after calling the function. -
How to create a custom log middleware in django?
I want to keep track of every records which are done by the user in my system. For this I used the django admin LogEntry model and created log like this. It works but in my app there are hundreds of view for create,update, delete so this process will be very long so I think writing the middleware will be better idea but I got no idea how can i write logic in middleware for this? Any small help will be greatful. views if form.is_valid(): form.save() # creating log LogEntry.objects.log_action(user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(Category).pk, object_id=category.pk, object_repr=force_text(category), change_message='Category updated.', action_flag=2 ) return redirect('list_categories') middleware class LogMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response -
I am new to django. I tried using django-taggit-autosuggest but autosuggestion doesn't show up in template. Please help me. Thank you
IN http://127.0.0.1:8000/taggit_autosuggest/list/ -> I am able to see list of tags In my installed apps: INSTALLED_APPS = [ 'taggit', 'taggit_autosuggest', ] urlpatterns = [ url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), ] base.html <head> <link href="{% static 'jquery-autosuggest/css/autoSuggest-upshot.css'%}"> <script src="{% static 'jquery-autosuggest/js/jquery.autoSuggest.minified.js'%}"> </script> </head> models.py from taggit_autosuggest.managers import TaggableManager class Discussions(models.Model): txt = models.TextField(blank=True, null=True) tags = TaggableManager() def __str__(self): return self.txt forms.py class DiscussionsForm(forms.ModelForm): class Meta: model = Discussions fields = ('txt', 'tags') def __init__(self, *args, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) self.fields['txt'].widget.attrs['class'] = 'form-control' self.fields['tags'].widget.attrs['class'] = 'form-control' -
Are both the raw queries same for left join?
While working with left join I wanted to have a search string - which would be dynamic. So, I had two queries Query 1: songs = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id ) as songs left join (select song_id, votes, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join (select core_blocksong.song_id from core_blocksong where core_blocksong.unblock_flag = 'f' and core_blocksong.client_id=%s) as c on c.song_id = songs.id where c.song_id is null and songs.name ilike %s or songs.artist ilike %s limit %s offset %s''', [request.anon_user.id, restaurant.client.id,restaurant.client.id,search_string,search_string,limit,offset,]) Query 2: songs = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join (select song_id, votes, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id where songs.name ilike %s or songs.artist ilike %s limit %s offset %s left join (select core_blocksong.song_id from core_blocksong where core_blocksong.unblock_flag = 'f' and core_blocksong.client_id=%s) as c on c.song_id = songs.id where c.song_id is null''', [request.anon_user.id, restaurant.client.id,search_string,search_string,limit,offset,restaurant.client.id,]) … -
"Cannot read property 'product' of undefined". how to get rid of that problem in javaScript
Want to add products to cart but displaying product is undefined. How to fetch values from data-property and i've also tried $(this).data('data-product) but this one is also not working <button data-product = {{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> var updateBtns = document.getElementsByClassName('update-cart'); for (var i = 0; i < updateBtns.length; i++) { updateBtns[i]=addEventListener('click',function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) }) } -
Is it possible to create a Model that creates sub models in Django?
Please excuse my way of asking the question, but what I mean is this: Is there a way to create a Model in Django, that acts as a "Mother Model" in which I can create sub models.? In my particular example, I am working on a sales website portal in Django, in which I want to create a class called Sales_Process as the "Mother Model" and then Negotiation, Deal and Quote as "Sub Models" that get created using Sales_Process. The user should be able to add more "Steps" to its Sales Process on the admin panel. Thank you so much in advance. -
GeoDjango setup issue
Error: OSError: /usr/local/lib/libgdal.so: caanot open shared object file: No such file or directory unable to load app 0 (mountpoint='') (callable not found or import error) As i see many solutions for this problem but nothings Works for me, From last 2 days i am trying to set up the GeoDjango Project. but did'nt succeed GDAL VERSION: gdal-3.1.0 PROJ VERSION: proj-7.0.1 GEOS VERSION: geos-3.8.1 here below is my django setting library Path:- GDAL_LIBRARY_PATH="/usr/local/lib/libgdal.so" GEOS_LIBRARY_PATH="/usr/local/lib/libgeos_c.so" my Ubuntu Version is 18.04, as When I check this Path, there will be the file present by the name of libgdal.so, libgeos_c.so . But while compile time it will always show the error , No such file or directory According to the Below link Solution I set the Path of inside ld.so.conf , But nOthings works for me GeoDjango - GDAL library giving error As i set the library Path also , in the /etc/ld.so.conf/ , See below :- include /etc/ld.so.conf.d/*.conf /usr/local/lib And After that sudo ldconfig But it will again Show me the Error when I do my docker-compose up Any help will be Highly Appreciated , as I am stuck in this problem from last two days -
Getting rid of useless digits like the 0 in 7.0 or 10.0 in python
I am working with Django and I have a project where I define a Student object that has the fields of grade 1 and grade 2, in this class, I build a function that gives back the grade of the student in question although I encountered a problem, the useless digit when I've got an integer number. That is because I am adding and dividing two float numbers but I want to make the function so that it returns an integer if the result is also one but I don't know how. This is what I've got so far: PS. The class Student inherits from Person, a class that contains credentials about a person like name email and so on but I don't think that really matters here. class Student(Person): grade_1 = models.FloatField(validators=[validate_grade], null=True, blank=True) grade_2 = models.FloatField(validators=[validate_grade], null=True, blank=True) study_field = models.CharField(max_length=50) year = models.PositiveIntegerField(validators=[validate_year], blank=True, null=True) remarks = models.TextField(max_length=300, blank=True, null=True) def get_grade(self): if self.grade_1 is None and self.grade_2 is None: return "No grades yet" elif self.grade_2 is None: return self.grade_1 elif self.grade_1 is None: return self.grade_2 else: return (self.grade_1 + self.grade_2)/2 -
Date detail view error " NoReverse match at orderlist "
I have two models Order and Date. I'm trying to create a view function where a user can click on view URL and will able to see the date details of a specific order.But I'm keep on getting this error "Reverse for 'date-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['dates/(?P[0-9]+)/$']" from order_list.html view URL tag Models: from django.db import models from django.conf import settings from django.contrib.auth.models import User class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date = models.ForeignKey('Date', null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ) status = models.CharField(max_length = 100, choices = status_choices) def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) URLS: from django.urls import path,include from django.contrib.auth import views as auth_views from .views import order_list,create_order,update_order,delete_order,login_page,logout_page, simple_upload, upload_ingredients, update_profile,dateDetailView app_name = 'accounts' urlpatterns = [ path('dates/<int:pk>/', dateDetailView, name='date-detail') ] Views: def dateDetailView(request, pk): date = Date.objects.get(pk=pk) orders = Order.objects.filter(date = … -
How to filter querysets dynamically with ajax and dropdown menu
I have in my views the following code: def stato_patrimoniale(request): now=datetime.datetime.now() now=now.year ... if Ricavi.objects.count()>0: for year, month, totale in(Ricavi.objects.values_list( 'data_pagamento_acconto__year', 'data_pagamento_acconto__month'). annotate(totale=ExpressionWrapper(Sum(F('acconto')), output_field=FloatField())).values_list('data_pagamento_acconto__year', 'data_pagamento_acconto__month', 'totale')): if id not in incassi.keys() and year == now: incassi[id]=list(defaults) index=month-1 incassi[id][index]=totale The now variable is used to filter my data in the queryset, where my ricavi is the following models: class Ricavi(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True, blank=True) # numero_lavorazione acconto=models.DecimalField() data_pagamento_acconto=models.DateField() Now I want to replace the now variable witha a form that give me the possibility to choose the year and update my views. I have created another app with the following model that with a form gives the possibility to add new year: class Timing(models.Model): reference_year = models.DecimalField(max_digits=4, decimal_places=0, default="2020") Now I want to create a dropdown button that contains all the reference_year filled and when the client click on one of them, the now variable in my def stato_patrimoniale(request): is updated. How could I get this aim? -
Get 404 1668 in CMD and can't connect my css file im html
Here's my script in base.html, the left of the picture is about my tree. I checked the href should be correct and I've load static at very top of the html file. However I still cannot connect the css file anyone can help he here? Thanks! href="{% static 'css/master.css' %}" for refer, please see the picture since idk why I can't post a picture yet, thanks! https://i.stack.imgur.com/JuJvW.png -
Django Tutorial - install the previously cloned copy of Django
I was following this tutorial when this error occurred. I would appreciate it if anyone could tell me what is going wrong here. https://docs.djangoproject.com/en/3.0/intro/contributing/ (djangodev) (base) XXXX@XXXX-MacBook-Air hello_django % python -m pip install -e /path/to/your/local/clone/django/ ERROR: /path/to/your/local/clone/django/ is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with svn+, git+, hg+, or bzr+). -
Use Django Forms just to verify HTML form data and not for rendering
Im my project I have used normal html forms with custom formatting and in various places included CRUD operation using table also. I was wondering is there any way to pass the data from my html forms to Django Forms for validation, as I can't use Django Forms for rendering the forms on my page due to the complexity of the project but I still would like to use the built in validations of Django Forms before I insert the data into Database. -
How to set optional parameters using Django?
I need to set optional parameters using Django. I try a method saw on Stack Overflow but it didn't work. My code : views.py : def get(self, request, id_document, optional_parameters = 'owner'): #code here urls.py : url(r'^getdoclist/(?P<id_document>[^/]+)/$', Get_DocumentList.as_view()), url(r'^getdoclist/(?P<id_document>[^/]+)/(?P<owner>[^/]+)/$', Get_DocumentList.as_view()), it didn't work using this method :( Thanks if you could help me -
child error in inlineformset only display the error if parent has error
i'm trying to display error child message in inline formset , but it show the error if my parent class has an error as well , if the parent has not any error it will save the form!? this my template <form method="POST">{% csrf_token %} {{formset.management_form}} <p> {{form.name| add_class:'col-12 text-center d-inline text-center'}} {% if form.name.errors %} <div class="error mx-auto"> {{form.name.errors}} </div> {% endif %} <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <tbody class="tbody tb1 "> {% for content in formset.forms %} <tr class="p-0 col-12"> <td class=""> {{content.title| add_class:'col-12 text-center'}} {% if content.title.errors %} <div class="error mx-auto"> {{content.title.non_field_errors}} {{content.title.errors}} </div> {% endif %} </td> <td class=""> {{content.note| add_class:'col-12 text-center'}} {% if content.note.errors %} <div class="error mx-auto"> {{content.note.non_field_errors}} {{content.note.errors}} </div> {% endif %} </td> </tr> </tbody> <tfooter> {% if form.number.errors %} <div class="error mx-auto"> {{form.number.errors}} </div> {% endif %} </body> my inline formset MyInlineFormSet = inlineformset_factory( Parent,Child,form=ChildForm,fields=('title','note'),extra=1) but it only display to title and note error if parent (number , name) has an error !? thanks for reply , -
need to make my create post FBV not include the user currently signed in
hi guys so I just started studying django about 1.5 weeks ago so im like really new but I'm finally starting to understand the gist of everything and I wanted to test myself by making a blog app w/o help on tutorials on youtube and I did finish the app (like everything works) but theres one part thats really bugging me. So in my create_post FBV, I wanted to make it so that when the signed in user makes a post, my postform doesn't show the username, but only the title and the content to create. but when I first excluded it, the post wouldn't create since the computer doesn't know who the user is. I tried looking stuff up for the longest time and what to do and not searching on youtube, but the best thing I could find was passing it initial. After i finished everything else I saw someone did it by using a CBV but i only just started reading the source code and documentation for like two days so I'm no where near comfortable with them. This is my code: @login_required def create_post(request): form = PostForm(initial={'author':request.user}) if request.method == 'POST': form = PostForm(request.POST, initial={'author':request.user}) if … -
get count of a Subquery
I want to annotate a count field in my queryset with a subquery filter: My code: module_attempts = Subquery(ModuleProgressAttempt.objects.filter( module_progress__module__id=OuterRef('pk')).only('pk')) real_instances = VirtualClassRoomModule.objects.filter( id__in=[vc.id for vc in vc_classrooms]).annotate( attendees_count=Count(module_attempts), ) Here module_progress__module__id is the id of the current VirtualClassRoomModule of the annotation iteration. The count is basically the length of the ModuleProgressAttempt filtered queryset. Currently the count is always 1 , eventhough the ModuleProgressAttempt.objects.filter( module_progress__module__id=<Current-module-id>) returns more than one object. -
How to query the objects having all the given objects in Many To Many Field?
I was trying to find out one way where I can query all the objects of one table which are having the given objects as ManyToMany Field. Please take below example: class Post(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') author = models.CharField(max_length=30) mail = models.EmailField() class Tag(models.Model): name = models.CharField(max_length=15) posts = models.ManyToManyField(Post, related_name="tags") Here I want to fetch all the posts having both "python" and "django" in the tag list. I can do that at the python level by fetching all the Posts and then checking their tags. is there any way we can directly fetch it from the DB? Using the DJango QuerySet. Any help would be appreciated!! Thanks in Advance!! -
Authorization Token in Headers not showing up in the Unit Test
I have been unit-testing my views in Django. After searching through Stack Overflow, I figured I can add token in the request header like so: access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjMifQ.7oLMOMBCGc46Wt_lQhjwQWoTDh6gJVsTusTAgibv1Kw' class MainPageViewTest(TestCase): def setUp(self): client = Client(HTTP_AUTHORIZATION=access_token) topic1 = Topic.objects.create(name='one') pin = Pin.objects.create(name='one', paragraph1='one') social = Social.objects.create(name='google') user = User.objects.create(nickname='tom', id=3, social_service=social) pin.topic.add(topic1) user.topics.add(topic1) def tearDown(self): Pin.objects.filter(name='one').delete() Topic.objects.filter(name='one').delete() User.objects.filter(nickname='tom').delete() def test_get_main_view_pins(self): response = self.client.get('') self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['pins'][0]['text1'], "one") However, when I test it, it keeps throwing me an error. The error code is 402 which is set by myself to indicate the absence of the header token. Let me show you the decorator through which the request goes: def login_required(func): def wrapper(self, request, *args, **kwargs): header_token = request.META.get('HTTP_AUTHORIZATION') if header_token == None: return JsonResponse({"message": "THE TOKEN IS EMPTY"}, status=402) decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['id'] user = User.objects.get(id=decoded_token) user_id = user.id kwargs['user'] = user kwargs['user_id'] = user_id try: if User.objects.filter(id=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "THE USER DOES NOT EXIST"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except KeyError: return JsonResponse({"message": "KEY ERROR"}, status=405) except User.objects.filter(id=decoded_token).DoesNotExist: return JsonResponse({"message": "USER NOT FOUND"}, status=406) return wrapper So, as the decorator proves, 402 means I have no token in the headers. I thought you …