Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
custom search filter in django modelviewset not showing anything
I'm trying to do a searchfilter on modelviewset and I think the way to do this is to create a custom search filter. Not sure whats missing but its not working. Its not returning anything. This is what I have so far: my custom search filter on another file: class CustomSearchFilter(SearchFilter): def get_search_fields(self, view, request): if request.query_params.get('courseCode'): return ['courseCode'] return super(CustomSearchFilter, self).get_search_fields(view, request) my model view set: class CourseViewSet(viewsets.ModelViewSet): authentication_class = (TokenAuthentication, ) permissions_class = (IsAuthenticated, ) def list(self, request): if self.request.user.is_professor: user = self.request.user paginator = LargeResultsSetPagination() search = CustomSearchFilter() course = Course.objects.filter(course_professor=user) prof = User.objects.filter(is_professor=True) result_page = paginator.paginate_queryset(course, request) paginator_count = paginator.get_paginated_response(course) course_serializer = CourseSerializer(result_page, many=True) prof_serializer = UserSerializer(prof, many=True) search_queryset = search.get_search_fields(course,request) search_ser = CourseSerializer(search_queryset, many=True) response = {'message': 'Sucess!', 'prof': prof_serializer.data, 'course': course_serializer.data, 'page': paginator_count.data, 'search': search_ser.data } return Response(response, status=status.HTTP_200_OK) -
upload image from angular 7 to Django
my UI is angular 7 and backend Django. i wanna upload my image in FileField at django backend: this is my api code: class UploadImage(APIView): parser_classes = (FileUploadParser,) renderer_classes = [JPEGRenderer] def put(self, request, filename, format=None): try: _u = request.user users = UserProfiles.objects.filter(user=_u) for g in users: g.picture = request.data['file'] g.save() return response.Response({'status': 0, 'msg': 'upload successfully!'}, status=HTTP_200_OK) except Exception as e: print(e) return response.Response({}, status=HTTP_400_BAD_REQUEST) and this is my JPEGRenderer : from rest_framework.renderers import BaseRenderer class JPEGRenderer(BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data when i sent my image to backend i take 406 acceptable http error my request: Request URL:api/user/upload_img/IMG_20181207_160953.jpg Request method:PUT Remote address:127.0.0.1:8000 Status code: 406 Version:HTTP/1.1 Referrer Policy:no-referrer-when-downgrade request headers: Host: localhost:8000 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: application/json Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://localhost:4200/ Authorization: Bearer eyJ0eXAiOiJFp Content-type: image/jpeg enctype: multipart/form-data Content-Length: 255159 Origin: http://localhost:4200 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache and my image is in request payload -
I am not able to reset password
TimeoutError at /passwordreset/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:8000/passwordreset/ Django Version: 3.0.2 Exception Type: TimeoutError Exception Value: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Exception Location: C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\socket.py in create_connection, line 796 Python Executable: C:\Users\saikr\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['C:\New_Django\Realtime', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] Server time: Thu, 13 Feb 2020 07:29:38 +0000 -
How to throw back serializer.errors in Django?
How do I throw the serializer.errors if I have a wrong input in some field? Do I have to code some "logic", or I just have to "write" some configurations. #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): ... def update(self, instance, validated_data): ... #views.py class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer def partial_update(self, request, pk=None): ... def get_queryset(self): ... For example I want to POST: { "name": "Banana", "amount": "ABCD", "description": "" } Instead of getting an error in the server: ValueError: invalid literal for int() with base 10: 'ABCD' I want a response like this: {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]} -
Django server and prestodb connection and data pagination
I have a simple infrastructure that is using django server for APIs and PrestoDb as query engine. Everything is working fine for me but I have few limitations depending on prestodb: Prestodb doesn't support pagination, How can I manage huge amount of data? loading it into memory is costly. I am opening and closing connection to presto again and again for each query, What is the best way to use only one or two connections only and use them all over the application? What is the proper way to show errors to users instead of raw presto exceptions? What kind of caching mechanism should be used for common data? I am using celery for background jobs, is there any other for running background jobs that are not load on python server? What are best practices for django? Any helpful link? -
Using with and if simultaneous in django template
my view : I have used templated_context_processor for my convinience def list_subtest(request): return {'subtest':Subtest.objects.all(),'test':Test.objects.all()} my models :Here I have test and subtest models. For example Blood falls in test category and hemoglobin falls in subtest category class Test(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subtest(models.Model): name = models.CharField(max_length=100) test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True) unit = models.CharField(max_length=10) reference_value = models.IntegerField() selected = models.BooleanField(default=False) def __str__(self): return self.name my template : I want to show the test and the subtest that falls under the same test . <ul class="nav-list"> <li> <a href="#">Test</a> <form class="hero-menu"> {% for test in test %} <div class="category-block"> <ul class="dropdown-list"> <li> <a href="#"><h4 data-modal-target="menu-test-popup"> {{test.name|title}} </h4></a> </li> {% for subtest in subtest %} {% with subtest.test as name %} {% if name %} <li> <div class="checkbox-group"> <input type="checkbox" id="aUniqueName" name= value="example"/> <label for="aUniqueName"> {{subtest.name}} </label> </div> </li> {% endif %} {% endwith %} {% endfor %} -
django project how to integrate with tcp/udp request
i want to collect and store data from one tracking device, That device using TCP UDP protocol, I don't know how to integrate my project with tracking device, am using Django frame work, any one know the solution please let me know. -
Disqus Commenting - show latest 10 comment first
how to load latest 10 comment first in disqus? i have already read this docs https://django-disqus.readthedocs.io/en/latest/templatetags.html , but i didn't got any helpful. any help, would be appreciated. thanks! -
Django tutorial part 5. Indexview testing doesn't get message "No polls are available."
I tried to run the testing on django tutorial part 5. But I couldn't pass. The test class is like below class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exists, an appropriate message is displayed """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_future_question(self): """ Questions with a pub_date in the future aren't displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_past_question(self): """ Questions with pub_date in the past are displayed on the index page """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions are displayed """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) Errors occured in functions test_future_question and test_future_question_and_past_question. I able passed the test when I commented out the statements 'self.assertContains(response, "No polls are available.")' It seems like I need … -
Djnago manage.py makemigrations killed always
(venv) /project/Backend$ python manage.py makemigrations Killed (venv) /project/Backend$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... -
How access all information provided by DEBUG=TRUE on production server without accessing it to users
I have a project which is in development stage. Now I am building authorization app where I want to put logic 1 - user registered on site after registration he by default isn't verified. 2 - backend send email verified letter to user provided email while registering. 3 - letter contain link with domain.uid. 4 - user clicking on link in letter which will redirect him and if all above steps is good his account verified. All above logic I have created but faced with problem link which send to user's email domain.uid contain domain which in development server equal == localhost because of it while I am debugging it click on link it's give me 404 error. I decided that my problem can be solved by providing really registered domain. I bought domain linked it to my hosting and deployed my project with gunicorn, nginx on production server. Now I am faced with another I read that DEBUG=TRUE on production server can be cached with Google and provide vulnerabilities . And now my question how I can access DEBUG=TRUE information from my production server with closing this information to users??? Or I should doing by another way?? Please guide … -
Django multivalue for a field
I want to have a table schema as below. table 1: User userid, tech, other here tech is a foreign key to Tech table object Table 2: Tech techid, techanme, scenes Here, I want multiple values to be assigned to the scenes. How can I do this using django models. (Please see I used manytomanyfields, but there I could not get back the scenes for the techname as required) -
how do i generate custom 404/500 error page in django app on entring or requesting a wrong url which is not exist in the project
i have tried the code bellow to generate custom error/404/500 page but its not working at all, actually i want to raise this error when user tries to enter wrong url,then a custom error page with 404/500 would be displayed to the user. views.py from django.shortcuts import render from django.shortcuts import render from django.conf import settings def error_404(request,exception): context = {} context = {"project name":settings.PROJECT_NAME} return render(request,'error_404.html',context) def error_500(request): context = {} context = {"project name":settings.PROJECT_NAME} return render(request,'error_500.html',context) app urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path from django.conf.urls import handler404, handler500, include from .import views import testapp from testapp import views as common_views urlpatterns = [ path('error_404',views.error_404,'error_404'), path('error_500',views.error_500,'error_500'), ] project/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import handler404, handler500, include from testapp import urls import testapp from testapp import views as common_views urlpatterns = [ path('admin/', admin.site.urls), path('', include(testapp.urls)), ] handler404 = common_views.error_404 handler500 = common_views.error_500 -
Ordering by geospatial data and moving up specific records based on a field - ElasticSearch DSL DRF
The situation I'm currently trying to solve is a case where GeoSpatialOrderingFilterBackend is used from ElasticSearch DSL - DRF, which orders the documents based on a location (lat, long), this in return gives out a elasticsearch_dsl.search.Search queryset - ordered as it should; although I have a case where some are featured and therefore would like to move them to the top of the queryset. Scenario (as is): Record 1, Location X, Featured False Record 3 Location Y, Featured False Record 2, Location Z, Featured True Expected: Record 1, Location Z, Featured True Record 2, Location X, Featured False Record 3, Location Y, Featured False Sorting afterwards (as shown below) on the queryset puts the featured up at the top; although scrambles the whole geospatial/location ordering. result = super().filter_queryset(request, queryset, view).sort('-featured') I'm looking for a way to put the featured records up at the top; but maintain the order of the records. -
During AJAX call of POST method converted to GET method when using with Django i18n pattern
I have used Django i18n pattern in my project to convert my website text between english and german. I have handled all post methods with common code written in webbase.js file. After implementation of Django i18n code in my project, my website started to behave strangely and converted my all POST mehtod with GET. I have already tried with solutions explained online like below. sol-1 : Append slash after url. sol-2 : AJAX call I have tried with both type: "POST" ad method: "POST". But even after updating code as per solution, still I am not able to solve my issue. My code is as below. webbase.js app.post = function(url, postData, hasMsg, callback, dataType, msgId, processData, contentType) { try { msgId = msgId || "appMsg" var ajaxParam = { dataType: dataType || "json", type: "POST", headers: { "X-CSRFToken": app.getStorage("csrftoken") }, url:url, data: postData, beforeSend: function() { ajaxCalls++; $('#loading-image').show(); }, complete: function() { ajaxCalls--; if(ajaxCalls == 0) { $('#loading-image').hide(); } }, success: function(data) { if (hasMsg) { if (data.code == 0) { app.showMessage(msgId, app.MsgType.Error, data.msg, 10); return; } app.showMessage(msgId, app.MsgType.Success, data.msg, 10); } if(callback) { callback(data); } }, error: function(data) { app.showMessage(msgId, app.MsgType.Error, "Error occurred", 10); console.log(data); } } if(typeof processData … -
How to redirect to the same page after successful POST request?
Here I have a newsletter form inside every pages so I placed it inside base.html and I wrote views like this. What I want is if the user process the request from home page it should redirect to the homepage and if the user send request from services page it should redirect to the services page and so on. With request.path_info this is returning to the /newsletter/ path but I don't want that.I want to redirect to that template from where the request has been sent. base.html <form action="{% url 'newsletter' %}" method="POST" class="form-inline"> {% csrf_token %} <input type="text" placeholder="Email Address" name="email" class="form-control"> <button class="btn btn-primary btn--subcribe" type="submit">Subcribe</button> {% if form.email.errors %}<b class="text text-danger"> </form> I tried with request.path_info like this def newsletter(request): form = NewsletterForm() if request.method == "POST": form = NewsletterForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank you for your subscription.') return redirect(request.path_info) return render(request, 'base.html', {'form': form}) -
get data from form.cleaned_data in a dictionary
I have a django form which sends data as: {'transaction_date': datetime.date(2020, 2, 13), 'dispatch_date': datetime.date(2020, 2, 13), 'send_from_warehouse': <Warehouse: test_warehouse>, 'sales_order': <MaterialRequest: 6>, 'parent_company': <Client: client>, 'product1': '132', 'product1_quantity': 273, 'product2': '231', 'product2_quantity': 273, 'product3': '213', 'product3_quantity': 325, 'product4': '216', 'product4_quantity': 325, 'product5': '564', 'product5_quantity': 260, 'product6': None, 'product6_quantity': None, 'product7': None, 'product7_quantity': None, 'product8': None, 'product8_quantity': None, 'model': 'Sell', 'driver_name': '0', 'dri ver_number': '0', 'lr_number': 0, 'vehicle_number': '0', 'freight_charges': 0, 'vehicle_type': 'Part Load', 'transport_by': <Vendor: BlaBla>, 'expected_delivery': datetime.date(2020, 2, 13), 'remarks': None} How can I get the dictionary of product with their quantity ? Expected output is: {'132': 273, '231': 273, '213': 325, '216': 325, '564': 260} What I am doing right now is this: products = [] quantity = [] products.append(form.cleaned_data["product1"]) products.append(form.cleaned_data["product2"]) products.append(form.cleaned_data["product3"]) products.append(form.cleaned_data["product4"]) products.append(form.cleaned_data["product5"]) products.append(form.cleaned_data["product6"]) products.append(form.cleaned_data["product7"]) products.append(form.cleaned_data["product8"]) for i in products: if i == None: products.remove(i) quantity.append(form.cleaned_data["product1_quantity"]) quantity.append(form.cleaned_data["product2_quantity"]) quantity.append(form.cleaned_data["product3_quantity"]) quantity.append(form.cleaned_data["product4_quantity"]) quantity.append(form.cleaned_data["product5_quantity"]) quantity.append(form.cleaned_data["product6_quantity"]) quantity.append(form.cleaned_data["product7_quantity"]) quantity.append(form.cleaned_data["product8_quantity"]) for i in quantity: if i == None: quantity.remove(i) prod_quant = dict(zip(products,quantity)) print("prod_quant is ", prod_quant) which outputs as: prod_quant is {'132': 273, '231': 273, '213': 325, '216': 325, '564': 260, None: None} Also why is "None" not removed from both the lists? -
How to throw ValidationError in Django, ModelViewSet
Hi I am trying to implement a ValidationError in my application but I could not get an example. I want to throw in some json error like if there is some issue with the input on a POST/Update method. Where is also appropriate to put it -- on serializer or in views? Thanks! {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]} #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): ... def update(self, instance, validated_data): ... #views.py class ProductsViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer def partial_update(self, request, pk=None): ... def get_queryset(self): ... -
Reverse for 'ads' not found. 'ads' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I would like to invoke another Html in the Index file that contains the contents of a model The index actually works properly and is called from the post model correctly but not from the ads model. Can anybody see what I'm missing? URLS.py from django.urls import path, re_path from .views import * app_name = 'post' urlpatterns = [ path('', index_view, name="index"), path('create/', create_view, name="create"), path('ads/', ads_view, name="ads"), re_path(r'^(?P<id>\d+)/$', detail_view, name="detail"), #re_path(r'^(?P<id>\d+)/ads/$', ads_view, name="ads"), re_path(r'^(?P<id>\d+)/update/$', update_view, name="update"), re_path(r'^(?P<id>\d+)/delete/$', delete_view, name="delete"), re_path(r'^(?P<id>\d+)/search/$', delete_view, name="search"), ] views.py def ads_view(request,id): ads = get_object_or_404(Ads,id=2) return render(request, "post/ads.html", {"ads":ads}) base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PhoneBook</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static '/css/bootstrap.css' %}"> </head> <body> <div class="container"> {% block header %} {% include 'header.html' %} {% url 'ads' %} {% endblock %} {% include 'message.html' %} {% block body%} {% endblock %} </div> <script src="{% static '/js/jquery.min.js' %}"></script> <script src="{% static '/js/bootstrap.js' %}"></script> </body> </html> ads.html <div class="row"> <div class="card col-md-8 offset-md-2"> <div class="card-body"> <p>{{ ads.ads_text }} </p> </div> </div> </div> NoReverseMatch at … -
Select from ENUM in Django
The below is my model, class Employee(models.Model): name = models.CharField(max_length=100) sex = models.PositiveIntegerField(choices=choices(Type)) Enum class is class Type(Enum): Male = 0 Female = 1 Now coming to our main model class Tournament(models.Model): player_name = models.ForeignKey(Employee) My admin is @admin.register(Tournament, site=admin.site) class TournamentAdmin(admin.ModelAdmin): list_display = ('player_name') The requirement is I only want to get Male players in My admin page in the field player_name. How to filter from ENUM class to get only male players name. -
How to solve Devtools failed to parse sourcemap
How to solve the problem of dev tools failed to parse? Although it is running in chrome but not in firefox properly. DevTools failed to parse SourceMap: http://127.0.0.1:8000/static/home/js/bootstrap.min.js.map bootstrap.min.js.map //# sourceMappingURL=bootstrap.min.js.map Althogh this containing a lot of other code which is out of limit. -
How can I set the time zone in Django as per the end user's time zone?
How can I set the time stamps in Django on the basis of the end users' time zone? Currently the settings file cobtains these details related to the time zone TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True -
Error connecting the redis, in app server, with django
I am trying to connect the redis ,in app server,with django. While checking the api in postman I am getting an error saying the output variable is referenced before assignment. But the api works good for the redis that I have downloaded in my local and I am getting the output as expected. I think I have went wrong while giving the credentials in the settings.py file. I would like someone to help me to put out this error. I have attached the redis cache credentials below, CACHES = { "default" : { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:// 3.233.27.21:6379/1", "TIMEOUT": 86400 , "OPTION": { "PASSWORD": "XXXXXXX", "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "XXXXXX" } } Thank you in advance. -
Run container images on Kubernetes - CrashLoopBackOff
I don't have much experience with kubernetes, but what I am essentially trying to do is run container images (django app) + (postgresql) on kubernetes cluster. I am constantly running into CrashLoopBackOff. Any help would be really appreciated. kubectl logs project-app-7ccf657d8c-ktfn7 -p (returns nothing) kubectl get pods project-app-5d954f9685-hjwvp 0/1 CrashLoopBackOff 16 59m project-database-574978c8c6-skwgk 1/1 Running 0 3h59m kubectl describe pod project-app-5d954f9685-hjwvp Name: project-app-5d954f9685-hjwvp Namespace: default Priority: 0 Node: aks-nodepool1-32957652-vmss000000/10.240.0.4 Start Time: Wed, 12 Feb 2020 20:19:41 -0800 Labels: app=project-app pod-template-hash=5d954f9685 Annotations: <none> Status: Running IP: 10.244.0.11 IPs: <none> Controlled By: ReplicaSet/project-app-5d954f9685 Containers: project-app: Container ID: docker://2ba6151dea44a42d417d43a7ea8ae90d8a5baa9e11042d0255c54981e4b7d673 Image: mentalhealth.azurecr.io/project-app4:v1 Image ID: docker-pullable://mentalhealth.azurecr.io/project-app4@sha256:c2b74c304c08f4c55891fd439364f711743273b6f166b88f9a7b21d332f69752 Port: 8000/TCP Host Port: 0/TCP State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Wed, 12 Feb 2020 21:11:32 -0800 Finished: Wed, 12 Feb 2020 21:11:32 -0800 Ready: False Restart Count: 15 Limits: cpu: 500m Requests: cpu: 250m Environment: postgres: project-database Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-ztqqh (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: default-token-ztqqh: Type: Secret (a volume populated by a Secret) SecretName: default-token-ztqqh Optional: false QoS Class: Burstable Node-Selectors: beta.kubernetes.io/os=linux Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s node.kubernetes.io/unreachable:NoExecute for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal … -
NotImplementedError: `create()` must be implemented in serializer.Serializer inheritance
I am getting error in creating auth token using serializer, I am Django beginner research lot and trying various ways to solve but it not solve, please anyone can help me in this. File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 169, in create raise NotImplementedError('create() must be implemented.') NotImplementedError: create() must be implemented. class CreateAuthTokenSerializer(serializers.Serializer): """Authentication serializer""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: msg = _('unable to authenticate with username and password') raise serializers.ValidationError(msg, code='authentication') attrs['user'] = user return attrs Thanks in advance