Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django membership site with site-wide product discount
I want to create a membership site with Django where subscribed members will automatically have a site-wide discount on all products. The subscription plans will come from Stripe, but I'm not sure how to implement this site-wide discount in Django. Can anyone please help? -
Returning labels within validation errors in Django rest framework
When there are some validation errors on a request, DRF returns a dict object containing all the errors, something like this: { "first_name": [ "This field may not be blank." ], "last_name": [ "This field may not be blank." ], "email": [ "This field may not be blank." ] } Is there anyway to change this behavior and make it to automatically return field names in each error? something like this: { "first_name": [ "First name field may not be blank." # <<< The label of field: first_name ], "last_name": [ "Last name field may not be blank." ], "email": [ "Email field may not be blank." ] } or even a list: [ "First name field may not be blank.", # <<< The label of field: first_name "Last name field may not be blank.", "Email field may not be blank.", ] Note that I have more than of 80 end-points and serializers; I can't re-define all fields that are being automatically generated by ModelSerializers to add error_messages parameter. first_name = serializers.CharField( write_only=True, min_length=5, error_messages={ "blank": "First name field cannot be empty.", "min_length": "First name field is too short.", }, ) -
Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins
Help Reason given for failure: Origin checking failed - https://praktikum6.jhoncena.repl.co does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. -
Error 404 while creating page to upload csv file to django model
I am trying to create a page so I can upload csv files to django model- MODELS.PY from django.db import models class March(models.Model): name = models.CharField(max_length = 60, choices=name_choice) march = models.CharField(max_length = 60, blank = True) may = models.CharField(max_length = 60, blank = True) def __str__(self): return self.name VIEWS.PY import csv, io from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.shortcuts import render from django.http import HttpResponse from .forms import CustomerForm, CustomerForm222, CustomerForm45 from . import models @permission_required('admin.can_add_log_entry') def contact_upload(request): template = "contact_upload.html" prompt = { 'order': 'Order of CSV should be name, march, may' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): message.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter = ',' , quotechar = "|"): _, created = Contact.objects.update_or_create( name=column[0], march = column[1], may = column[2] ) context = {} return render(request, template, context) URLS.PY from django.urls import path from .views import contact_upload from . import views urlpatterns = [ path('', views.index, name="index"), path('book/<int:book_id>', views.book_by_id, name='book_by_id'), path('upload-csv/', views.contact_upload, name = "contact_upload"), ] HTML TEMPLATE: <form method="post" enctype = "multipart/form-data"> {% csrf_token %} <label>Upload a File </label> <input type … -
TypeError: argument cannot be of '__proxy__' type, must be of text type
from django.utils.safestring import mark_safe import bleach @register.filter() def safer(text): return mark_safe(bleach.clean(text, tags=_ALLOWED_TAGS, attributes=_ALLOWED_ATTRIBUTES)) -
How do I post jobs on social media platform like LinkedIn, monster.com, indeed etc. etc. using django rest api's
I have a Django model which stores jobs and its various fields. Now I want to post that jobs in social media's. Can anybody advise me or guide me to how to implement it using rest API's. Thank you! -
How do you modify manytomanyfield in form in django?
I was wondering how you can change the value of a many-to-many field in a django form. Preferably, I would like to change the value within the def form_valid of my Modelview. Here is a part of the form_valid in my view that I am having trouble with: lesson = Lesson.objects.all().first() for i in lesson.weekday.all(): form.instance.weekday.add(i) form.instance.save() Here, weekday is a many-to-many field. However, the form saves the "submitted" values of the weekday by the user, and not the changed one as shown in the above code. Interestingly, the below code works, although it is not a many-to-many field: form.instance.name = lesson.name form.instance.save() Thank you, and please leave any questions you have. -
Django Not able to add default value to VersatileImageField
class Product(models.Model): name=models.CharField(max_length=128) photo = VersatileImageField(blank=True,null=True,upload_to="Product/",default='default.jpg',ppoi_field='photo_ppoi') photo_ppoi=PPOIField() I am not able to bring default value and ppoi_field together. showing following error . Error: str object has no attribute ppoi Exception Location : versatileimagefield\widgets.py Seems like exception throwing while django trying to set ppoi value to string type ('default.jpg') which is set for my default image in media folder Is there any different way to set default value to versatileImage field . I am wondering ,It works for different projects I have worked on !! -
django-admin startproject myapp . gives me a big error
Traceback (most recent call last): File "/Users/x/Dev/tryDjango/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/init.py", line 371, in execute_from_command_line utility.execute() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/templates.py", line 117, in handle django.setup() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/init.py", line 16, in setup from django.urls import set_script_prefix File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/init.py", line 1, in from .base import ( File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/exceptions.py", line 1, in from django.http import Http404 File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/http/init.py", line 5, in from django.http.response import ( File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/http/response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/serializers/init.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/serializers/base.py", line 6, in from django.db import models File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/init.py", line 3, in from django.db.models.aggregates import * # NOQA File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/expressions.py", line 486, in class TemporalSubtraction(CombinedExpression): File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/expressions.py", line 487, in TemporalSubtraction output_field = fields.DurationField() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/fields/init.py", line 155, in init if isinstance(choices, collections.Iterator): AttributeError: module 'collections' has no attribute 'Iterator' -
get value from a django form using javascript
I was trying for a long time to figure out how to get the value from a django.form using javascript, however I didn't get any straight answer to it. here is my project: views.py: from django.shortcuts import render, redirect from .forms import TextForm from .Functions import GetData def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TextForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... print("is valid") text = form.cleaned_data['date'] x = GetData(text.day, text.month, text.year) x.getInfo() context = { 'text': text, 'form': form, } return render(request, 'index.html', context) # if a GET (or any other method) we'll create a blank form else: form = TextForm() print("not valid") return render(request, 'index.html', {'form': form}) forms.py from django import forms class TextForm(forms.Form): date = forms.DateField(widget=forms.SelectDateWidget(), label="inputDate") let's say the html file is very basic, like this: <form action=" " method="post" id="form"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> SO the main thing, that I need, is to get the date value from the form -
Celery running in asyncio context
I'm running a Django app that uses Channels and Celery. I am having a non-deterministic issue where sometimes my Celery tasks are being run from the asyncio event loop. I get errors like this: [2021-12-08 20:02:23,699: ERROR/MainProcess] Signal handler <function switch_schema at 0x7f1ce3c09d30> raised: SynchronousOnlyOperation('You cannot call this from an async context - use a thread or sync_to_async.') Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/app.py", line 48, in switch_schema tenant = task.get_tenant_for_schema(schema_name=schema) File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/task.py", line 43, in get_tenant_for_schema cached_value = get_tenant_model().objects.get(schema_name=schema_name) File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 431, in get num = len(clone) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. It doesn't always happen and it doesn't always throw on the same line. Does anybody know why this is happening and how to prevent it from happening? -
Failed to access formData in Django. Uploading Files With VueJS and Axios + Django
I have used code of Uploading Files With VueJS and Axios. I am using backend code Django uploaded images save into database. In after submit and before submit i am able to see images uploaded in console. But After submit i am not able to access formData into django backend. Below is snippet code Template code <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <h2>Multiple Files</h2> <hr/> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label> <span>Files</span> <input type="file" multiple name="file" @change="handleFileUploads($event)" /> <ul v-if="files.length"> <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li> </ul> </label> <div> <img v-for="image in images" :src="image" /> </div> <br /> <button @click="submitFile()">Submit</button> </form> </div> <script> new Vue({ el: '#app', data() { return { files: [], images: [], } }, computed: { filesNames() { const fn = [] for (let i = 0; i < this.files.length; ++i) { fn.push(this.files.item(i).name) console.log('fn'); console.log(fn); } return fn } }, methods: { handleFileUploads(event) { this.files = event.target.files; this.images = [...this.files].map(URL.createObjectURL); console.log('images'); console.log(this.images); let formData = new FormData(); for (var i = 0; i < this.files.length; i++) { let file = this.files[i]; formData.append('files[' + i + ']', file); } console.log('formData'); console.log(formData); console.log('values'); console.log(formData.values()); for (var value of formData.values()) { console.log('value'); console.log(value); } }, submitFile() { … -
How to set user access restrictions in Django
first question. Is there a way to set access rights for a function without giving a conditional expression in django template? Currently, the code below is the code I wrote. If user click the "Click" text, a modal window is created depending on the condition, and if the condition is not met, a message window indicating that you do not have access rights is displayed. However, I think it is unnecessary to enter these conditions every time. {% if request.user.first_name in class.teacher|split:"/" %} <div data-toggle="modal" data-target="#relation_{{ class.id }}" class-id="{{ class.id }}">Click</div> {% else %} <a onclick="alert('You do not have access rights..');" class="col-form-label col-10 show-whitespace" style="cursor:pointer">Click</a> {% endif %} Second question. This example is similar. Through the conditional expression in the template, if the job of the current login account is 'principal', the Principal button is displayed. If it is not the principal job, the Principal button is not displayed on the screen. However, even if it is not a principal, user can connect by entering the '/class/principal/list' url directly. Is there a workaround? {% if job_title == 'principal' %} <a class="btn nav-link nav-link-button" href="/class/principal/list"> <span>principal</span> </a> {% else %} <a class="btn nav-link disabled nav-link-button" href="/class/principal/list"> <span>principal</span> </a> {% endif %} -
how to upload multiple files and use charfields at the same time in django rest framework?
Im pretty new in this field, so I will try to explain this the best way I can. Im trying to upload two different optional files (this means that it is not required to upload them) and also have two optional CharFields as inputs in the same API method. I can better explain this by showing what my views.py, my serializers.py is like and how I would like to be able to enter it in postman. With this, I can upload a file, but after this I have a traceback return None as HttpResponse, because the code cannot continue. views.py class FileUploadView(APIView): parser_classes = (FileUploadParser,) @swagger_auto_schema(request_body=FileSerializer, responses={ HTTP_200_OK: PostSuccessResponseSerializer, HTTP_400_BAD_REQUEST: PostErrorResponseSerializer } ) def post(self, request): # Upload two different OPTIONAL files file_1 = request.data.get('file', None) file_2 = request.data.get('file_2', None) # CharField optional inputs user_input = request.data.get('user_input') or '' foo_char = request.data.get('model_filename') or '' # Do something with the files ... # do something with the CharFields inputs ... return Response(f'Success!', status=HTTP_200_OK) serializer.py class FileSerializer(serializers.Serializer): file = serializers.FileField(allow_empty_file=False, use_url=False) user_input = serializers.CharField() foo_char = serializers.CharField() Postman -
Capital gains calculatation
Does any one knows older version of "capital-gains" python library. This support python3.9+ version. Or any other python library that i can use for capital gains calculation. Can anyone help me? -
How to properly manage categories in django admin?
I have register my models in admin.py as admin.site.register(Food_Gallery) admin.site.register(Gym) admin.site.register(Gym_Gallery) admin.site.register(Gym_Pricing_Plans) admin.site.register(Gym_Programs) admin.site.register(Trainer) admin.site.register(Farm) admin.site.register(Farm_Gallery) admin.site.register(Farm_Products) This shows all the models in a single page in django admin I want to categorize these models into certain categories and display their respective models.How to manage this? Certain examples as Food Gym Farm -
Why is `csrf_exempt` not needed when using django-rest-framework?
When I make a POST request with Postman, I receive an error Forbidden (CSRF cookie not set.) class BooksView(View): def post(self, request): If I use csrf_exempt the error does not occur from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='dispatch') class BooksView(View): def post(self, request): However, this error does not occur at all when I use django-rest-framework from rest_framework.views import APIView # /books class BooksView(APIView): def post(self, request): What is django-rest-framework and the APIView class doing in relation to csrf? -
How to restrict viewing properly in django rest framework
I have a page in my application where the in the HTML, I have the following codes: {% if job.owner == user.username or user.username == 'admin' %} So this means that the logged in user can view job that he/she created in the application and the admin user can view all the created jobs as admin is the master user. I am trying to apply the same logic in django rest framework but it is not working. Now is just filtering owner=request.user. This works for only user can view their own created job, but it also affected the admin. Admin now cant view all the jobs due to the filtering. How do I solve this? Here is my code: @api_view(['GET']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def jobs(request): job = Job.objects.filter(owner = request.user) jobserializer = JobViewSeralizers(job, many = True) return Response(jobserializer.data) -
how to print list in Django template
I received a List in this format from PostgreSQL. [(11, 'www.xyz.com', '03216784000', 'THis is admin side vendor', ['2020,2002'], ['Plugs,genrator'], 'zeshan@gmail.com,zeshan@hotmail.com', ['Corolla,toyota'])] Using this very simple query vendor_record = StaffUser.objects.get(user_id=id) I try to print or show a list special ['Corolla,Toyota] using split but could not remove the comma. I don't know how to print the whole list special ['Corolla,Toyota] type of data. anyone, please help. I am new to Django and could not find accurate results. -
Django custom save mixin
I've created a custom save function which has some specific logic depending on whether a Django model field has changed or not. Basically, I initialize and store the fields I'm interested in as part of the models init method, and then check whether those fields have changed as part of the models save function. All works well. But I'd like to create this as a mixin. I'm not sure how to best pass the initialized parameters within the mixin. Any advice? This works fine: class Model(models.Model): field = models.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__field_stored = self.field def save(self, *args, **kwargs): if self.field != self.__field_stored: # do something super().save(*args, **kwargs) But as a mixin? The below doesn't seem to work, raising an attribute error: class Model(SaveMixin, models.Model): field = models.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__field_stored = self.field def save(self, *args, **kwargs): super().save(*args, **kwargs) class SaveMixin(models.Model): field: str __field_stored: str class Meta: abstract = True def save(self, *args, **kwargs): if self.field != self.__field_stored: # do something super().save(*args, **kwargs) -
add jump to page function for server-side pagination in Django
I have a Django project, using server-side pagination for some table. The use want me to add a jump to function to go directly to the page he select, no matter it's a drop down or an input box. Browse_and_adopt.html: <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} &emsp;<a href="?page=1">&laquo; First Page</a> &emsp;<a href="?page={{ page_obj.previous_page_number }}">Previous Page</a> {% endif %} <span class="current"> &emsp;Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} &emsp;<a href="?page={{ page_obj.next_page_number }}">Next Page</a> &emsp;<a href="?page={{ page_obj.paginator.num_pages }}">Last Page&raquo;</a> {% endif %} </span> </div> view.py: @csrf_exempt def search_book(request): global Title_list_cache if request.method == 'POST': print(request.POST) search_keyword = request.POST.get('search_keyword', '') print(search_keyword) Title_list = Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print"), title__icontains=search_keyword).select_related('publisher').order_by('title') | Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print"), author__icontains=search_keyword).select_related('publisher').order_by('title') | Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print"), vbid__icontains=search_keyword).select_related('publisher').order_by('title') | Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print")).select_related('publisher').filter(publisher_id__name=search_keyword).order_by('title')| Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print"), description__icontains=search_keyword).select_related('publisher').order_by('title') Title_list_cache = Title_list else: Title_list = Title_list_cache page = request.GET.get('page', 1) paginator = Paginator(Title_list, 10) try: Titles = paginator.page(page) except PageNotAnInteger: Titles = paginator.page(1) except EmptyPage: Titles = paginator.page(paginator.num_pages) query_results_2 = Semester.objects.all() page_obj = paginator.get_page(page) query_results_code = CourseInfo.objects.none() if request.user.is_authenticated: username = request.user.username user_id = User.objects.get(username=username).id #user_id = 1 #test discipline_queryset = Discipline.objects.filter(hop1_id=user_id) | Discipline.objects.filter(hop2_id=user_id) | Discipline.objects.filter(executive_id=user_id) | Discipline.objects.filter(executive2_id=user_id) | Discipline.objects.filter(executive3_id=user_id) print(discipline_queryset) for discipline in discipline_queryset: id = Discipline.objects.only('id').get(name=discipline).id query_results_code … -
is it possible to attach a string variable in return redirect() in django
I have a situation here where I am creating a record from a view def index(request): if request.method == "POST": order_number = request.POST.get('order_number') post_code = request.POST.get('post_code') print(order_number) print(post_code) if order_number and post_code: n = page1.objects.create(orderNumber=order_number, postCode=post_code) n.save() id = n.id return redirect("page1:waiting") return render(request,"page1/index.html") And upon creating the record I am redirecting the user to another page with id. 127.0.0.1/page1/waiting/fb65-io98-..... from django.urls import path from . import views app_name = 'page1' urlpatterns = [ path('', views.index, name="amounts"), path('waiting/<str:pk>', views.waitReply, name="waiting"), ] View for Second URL def waitReply(request,pk): get_amount = page1.objects.get(id=pk) context = {'get_amount':get_amount} return render(request, "page1/payment-confirm.html", context) But the problem is how do I attach/generate/get the id in index view and send it for the waitReply view I can get the latest ID through n.id Kindly help. -
Restrict selections in a dropdown choice field based on usertype
I have usertype a and usertype b in my project how do i restrict the selections in dropdown based on user type in django the user type a has take and acknowledge as option whereas the user type b has option in drop down as create and finish models.py class Model(models.Model): title = models.CharField(max_length=200) info = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) CHOICES = ( ('Create','Create'), ('Taken','Taken'), ('acknowledged','acknowledged'), ('Finished','Finished') ) status = models.CharField('Status',choices=CHOICES) -
How to use Django test self.client.get to get user detail with url like this /user/<int:user_id>?
I want to create a test to check if getting user detail run correctly if I go to this url /user/int:user_id. My code is like this: def test_get_user_detail(self): self.client.login(username='tes', password='pandora_key') User_ID = 13 self.db_login = create_user(User_ID) db_login_count = DB_Login.objects.all().count() self.assertEqual(db_login_count, 1) self.assertNotEqual(db_login_count, 0) db_login_user = DB_Login.objects.filter(User_ID=User_ID).first() self.assertEqual(db_login_user.User_ID, User_ID) response = self.client.get('/user/<int:user_id>/', args=[User_ID]) self.assertEqual(response.status_code, 200) I've check that creating the user with that specific ID work correctly, but when getting that user from the URL the response always get code 404 not found. Anyone knows how to fix this? -
Custom authentication method in Django Rest Framework return None and not user
i've been trying to implement a custom authentication method in DRF but the overwrited method of authentication doesn't return User, it's return None. Here the code. First the configuration in my settings.py file. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'passewok.authentication.CustomAuthentication', ], } Now my CustomAuthentication class from rest_framework import authentication from apps.passmanager.models import User class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): password = request.META.get('HTTP_X') username = request.META.get('HTTP_Y') private_key = request.META.get('HTTP_Z') if not password or not username or not private_key: return None master_key=self.get_master_key() print(master_key,password,master_key==private_key) if master_key!=private_key: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') print(user.password) return (user,None) And then the view where i implement or use my custom auth @api_view(["POST"]) def login_manager(request): try: result = authenticate(request) print(result)#Here prints None in anyway if result: user=result login(request=request,user=user) return Response( { "Usuario": UserSerializer(user).data, "token": AuthToken.objects.create(user)[1], }, status=HTTP_200_OK ) else: return Response({"Error": "Failed"}, status=HTTP_401_UNAUTHORIZED) except: return Response({"Error": "Failed"}, status=HTTP_401_UNAUTHORIZED)