Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modelserializer related to users model
i have a model serializer which will create a post, and this post should be related to the user posting it, why this dont work ? class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('title', 'image') def create(self, validated_data): request = self.context.get('request', None) if request: user = request.user userobj=User.objects.get(username=user) post = Posts.objects.create(user=userobj, **validated_data) post.save() return user error message : AttributeError: 'User' object has no attribute 'title' -
Decoding (and equating) special characters with the Django REST framework SearchFilter?
I have implemented a Django Rest Framework SearchFilter in my backend, which for the most part works correctly. This is the code structure in views.py: class JobsViewSet(viewsets.ModelViewSet): queryset = Jobs.objects.all() serializer_class = JobSerializer filter_backends = [filters.SearchFilter] search_fields = ['^name', '^job_type'] The only remaining problem is that when sending get requests with a special character, for example the Swedish letter å, Django doesn't recognize that å is the same letter as Å only in lower case (as it does with for example a and A). In the GET calls from the front end, å gets converted to %C3%A5 for lowercase and %C3%85 for uppercase. This results in the search box not finding the jobs beginning with the letters åäö if the job title begins in uppercase (as in Återvinning). Does anyone know of a solution that makes the filter understand and equate uppercase and lowercase letters of special characters? Something along the lines of UTF-8 decoding? I have looked for answers both in the REST framework documentation and here on Stack Overflow, without any luck. New to Stack Overflow btw, I hope I'm doing the formatting correctly! -
not able to POST required data in django templates
I want to POST a form from my html to views.py in django, but I am not able do it. This is my html. This form should post the url of the downloaded image to the views.py function. {% for x in photo %} <a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a> <form action="/image_info/" method="POST" id='dform'> {% csrf_token %} <input name='d_button' type="hidden" value="{{x.image.url}}"> </form> {% endfor %} This is my javascript function to submit form whenever the get link is pressed <script type="text/javascript"> function myfunc() { document.getElementById("dform").submit(); console.log('hello'); } </script> this is my views.py. This should take the image url from the form and display it in the new page. def show_image(): image_url = request.POST.get('d_button', None) return render(request, 'show_image.html', {'image': image_url) but my problem is that the form is not returning the url of the image that is clicked instead it is returning the url of first link. for example link1 link2 link3 link4 if I click on link3, it is downloading the image in link3 but POSTING the url of link1 This is a bit tricky to explain but this is the best I can. Thanks in adavnce. -
Django ORM taking long time to load
fund_df = pd.DataFrame(list(FundRolling.objects.filter(code__exact=str(code), rolling=rolling, start_date__gte=start_date, end_date__lte=end_date).values())) I have the above line of code in my views.py file. FundRolling is a model created in Django from MYSQL database. This model is having nearly 1 crore entries. This line is taking 20 seconds for execution. But I want it to reduce to milliseconds. What should I do? Thanks in advance. -
Django model field with a regex validator not working
The below model has a regex validator, however, when creating new objects (with standard model instantiation and model.objects.create() ), there is no error message given when creating an object that violates the validator. It allows the object to be saved. Below is the code for the model: class Area(models.Model): area = models.CharField(max_length=6, validators=[RegexValidator( regex='^[A-Z]{1,2}[0-9][A-Z0-9]?$', message='Area is not in correct format', code='invalid_area' )]) Any advise would be much appreciated. -
django-background-tasks not working with django-hosts
django-background-tasks package does not work when django-hosts package is configured. My background task function looks something like this: @staticmethod @background(queue="text") def sendMessage(phone_number, message): I am running this function on a specific queue. Also background task command is running too. python3 manage.py process_tasks --queue text My hosts configuration works properly. But not background tasks. When I remove hosts configuration background task function executes. -
data not pre populating in form when updating model data in DJANGO
I'm not sure what is going wrong but the data from the user is not pre populating into the form, even after following the django documentation, I'm only getting a empty form , in the url I have the correct id for the item , I have text and 2 'filefields' that i need to request into the update form and want the user to be able to update one or more of the fields , appreciate the help ? here are my views and updateform html views @login_required def music_upload(request, slug): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): song = form.save(commit=False) song.artist = request.user song.track = request.FILES['track'] file_type = song.track.url.split('.')[-1] file_type = file_type.lower() if file_type not in MUSIC_FILE_TYPES: messages.error(request, f'ERROR - Track needs to be in MP3 format, Please try again!') return render(request, 'feed/music_upload.html', {'form':form}) else: song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile', slug=slug) else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) @login_required def edit_song(request, pk): artist = request.user.profile.user_id track = Music.objects.get(pk=pk).artist if request.method == 'POST': m_form = MusicUpdateForm(request.POST, request.FILES, instance=track) if m_form.is_valid(): m_form.save() messages.info(request, f'Your track has been updated!') return redirect('edit_track') else: m_form = MusicUpdateForm(instance=track) context ={ 'm_form': m_form, 'track': track, 'artist': artist, } return render(request, … -
Django many to many field, but display just the highest value
I want to know how I can display the highest ranking from the model education in the staff. The user would be able to select all of their educations, but for me it's irrelevant to know if the the user selected "high school" when he/she also has a master's degree. class Staff(models.Model): education = models.ManyToManyField('Education', verbose_name = 'Education') class Education(models.Model): name = models.CharField(max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name I gave every type of education a ranking. So in the Admin, the only thing I want returned would be the highest eduacation by a member of the staff - how do I write this function? class StaffAdmin(admin.ModelAdmin): list_display = ('rank') -
Error [{'error': 'NotRegistered'}] while using FCMNotification in python
I am getting the below error while running the snippet , even I tried uninstalling the app and login again, but no luck (using django REST as backend) Error msg {'multicast_ids': [5963190568359198474], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} code def send_notification_multiple_devices(device_ids=None, data=None): push_service = FCMNotification(api_key=FIRE_BASE_KEY) result = [] for id in device_ids: try: resp = push_service.notify_single_device( registration_id=id, message_title=data["title"], message_body=data["desc"], data_message=data, extra_notification_kwargs=extra_notification_kwargs, content_available=True, ) result.append(resp) except: pass return result -
AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
i'm trying to test admin and getting AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) even i check the solution over here but i already did the same and getting same error. My model file, admin file, and Testing file are below. admin.py from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) tests/test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_user( email = 'admin@admin.com', password = 'admin' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email = 'test@londondevapp.com', password = 'Test@123', name = 'Test 1' ) def test_user_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) -
Not able to get image from django rest framework url
I've setup my django rest framework server in which I want to upload some news alongside their images. Actually I'm able to upload news and images because I retrieve them on my server filesystem, but when I request for a list of news I get an image url which, when pasted in my browser, shows me "The requested resource was not found on this server". Following is reported some code. models.py class News(models.Model): author = models.CharField(max_length=50) title = models.CharField(max_length=150) content = models.CharField(max_length=10000) image = models.ImageField(upload_to='news', blank=True, null=True) created = models.DateField(auto_now_add=True) def __str__(self): return "{}".format(self.title) serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py class GetNews(generics.ListAPIView): queryset = News.objects.all() serializer_class = NewsSerializer def post(self, request): author = request.data['author'] title = request.data['title'] content = request.data['content'] try: image = request.data['image'] except KeyError: raise ParseError('Request has no resource file attached') news = News.objects.create(image=image, author=author, title=title, content=content) return Response("News successfully uploaded.", status=status.HTTP_200_OK) def delete(self, request): token = request.META.get('HTTP_AUTHORIZATION') if not check_token(token): return JsonResponse({'message': 'Unauthorized!'}, status=status.HTTP_401_UNAUTHORIZED) news = News.objects.get(id=request.data['id']) news.delete() return JsonResponse({'message': 'News was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ ... path('news', views.GetNews.as_view()) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Bootstrap will not let me center this container
I have been trying to center this div container after my navbar so that there is an equal space on both sides of the page. But, it is not working for some reason. Can you guys help please? The post_job.html is the issue. The portion where i display the text is being rendered on the left side with a bit of text going down Here is my code snippet: post_job.html {% load static %} {% include 'recruiter_navigation.html' %} {% block content %} <div class="row"> <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12 hidden-xs hidden-sm full_width"> <h2 style="color: darkblue;" class="text-center">Post an Internship</h2> </div> </div> {% endblock content %} recruiter_navigation.html <div class="container"> {% block content %} {% endblock content %} </div> -
Django Queryset on JSONField with nested data, whereby a dictionary key has a hyphen in the key name
I have a jsonfield called "data" that contains the following for one row, and I'm experimenting with querysets: { "id": "5cfbffb4-c03a-4905-aa3c-8ecd878f56d7", "owner": "string", "name": "some string", "short-name": "some string", "description": "some description", "sub-identifier": [{ "sub_id": "d2610379-abcc-4201-ad89-5f3ad3a4b1c2", "sub_name": "Test Dummy1", "sub-short-name": "some further name", "sub_description": "some description" }, { "sub_id": "7461b531-a181-483d-a554-ab8761c1d672", "sub_name": "Test Dummy2", "sub-short-name": "some further name", "sub_description": "some description" }] } So I can create a new query set queryset = TestModel.objects.filter(data__name='some string') this returns my queryset result correctly. However, I've noticed that if the dictionary key has a hyphen in it then it gives me an error. The following returns a syntax error: queryset = TestModel.objects.filter(data__sub-identifier__sub_id__0='d2610379-abcc-4201-ad89-5f3ad3a4b1c2') SyntaxError: expression cannot contain assignment, perhaps you meant "=="? Is there a way to tell Django to accept key names that may have a hyphen in? Or do I have to ensure that in my json data that all keys use underscores instead? Also, can I loop through each element in the list within sub-identifier to test the sub_id for a number I'm looking for. Naturally, I can do this as above using the 0, but hope there is a way to just loop through each element in the list of dictionaries … -
Is it possible to get extra value in a models.Model using django?
I would like to include some methode in the Model and was looking to get the "Supplier_Id" from an other table. class Thematic(models.Model): name = models.CharField(max_length=100, blank=True, null=True) ref = models.CharField(max_length=10, blank=True, null=True) def get_nber_of_questions(self): # count all questions in a thematic return Question.objects.filter(thema_id=self).count() def get_nber_of_answers_by_thematics(self): ### Extra value (**supplier_id**) I would like to get from the Model bellow ### return AuditSupplier.objects.filter(thematic_id=self, **supplier_id=18**).count() def __str__(self): return self.name class AuditSupplier(models.Model): supplier = models.ForeignKey(OrgaProfile, related_name='audit_supplier',on_delete=models.CASCADE) thematic = models.ForeignKey(Thematic, related_name='audit_thematic', on_delete=models.CASCADE) answer = models.IntegerField(choices=CHOICES, null=True, default=2) def __str__(self): return '{}'.format(self.supplier) Is it possible or Do I have to manage it in the view ? -
Django Channels: Web socket connection is failing in production
Locally its working fine. But when i deploy the same application in production. Its raising WebSocket connection to 'wss://example.com/ws/chat/room/list/' failed: (anonymous) @ (index):678 I checked the line 678 and code is below var ws_protocol = window.location.protocol == "https:" ? "wss:" : "ws:"; var url = ws_protocol+'//' + window.location.host +'/ws/chat/room/' +window.location.href.split("/")[4].replace("chat_","")+ '/'; var user = "User " + window.location.href.split("/")[4]$("#user").text(user) var chatSocketMsg = new WebSocket(url); Error @ line number 678 I'm suspecting the problem in deployment is Secure websocket connection. anyhow i fixed it using window.location.protocol == "https:" ? "wss:" : "ws:"; So, what else could be the problem? -
Newbie needs help understanding Docker Postgres django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
I am a newbie trying to follow this tutorial. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#postgres I succeeded in building the docker containers but got this error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres". My question is why has authentication failed when the python and postgres containers env shows the correct user and password? And how can I solve the problem? I also tried poking around to find pg_hba.conf (because previous answers suggested editing it) but /etc/postgresql does not seem to exist for me. This is from my python container. # python Python 3.8.2 (default, Apr 23 2020, 14:32:57) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.get("SQL_ENGINE") 'django.db.backends.postgresql' >>> os.environ.get("SQL_DATABASE") 'postgres' >>> os.environ.get("SQL_USER") 'postgres' >>> os.environ.get("SQL_PASSWORD") 'password123' >>> os.environ.get("SQL_HOST") 'db' >>> os.environ.get("SQL_PORT") '5432' This is from my postgres container. / # env HOSTNAME=6715b7624eba SHLVL=1 HOME=/root PG_VERSION=13.2 TERM=xterm POSTGRES_PASSWORD=password123 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin POSTGRES_USER=postgres LANG=en_US.utf8 PG_MAJOR=13 PG_SHA256=5fd7fcd08db86f5b2aed28fcfaf9ae0aca8e9428561ac547764c2a2b0f41adfc PWD=/ POSTGRES_DB=postgres PGDATA=/var/lib/postgresql/data / # ls bin lib root tmp dev media run usr docker-entrypoint-initdb.d mnt sbin var etc opt srv home proc sys / # cd etc /etc # ls alpine-release fstab hosts issue modules-load.d opt periodic resolv.conf shadow- sysctl.d apk group init.d logrotate.d motd os-release profile securetty shells terminfo conf.d … -
Salut j'aimerais savoir comment utiliser ImageField() pour enregistrer une image dans ma base de données. J'utilise Django 3 et python 3
picture = models.ImageField('') -
How did the [login.html] get the [school_name]
C:\Django-School-Management-System\templates\registration\login.html How did school_name get the value?? There no where to import the config. Config is here -
Unable to login via Facebook in live server using django alluth package
I tried to use django allauth package in my production server directly because in my localhost it says its not a secure connection everytime. But in my production server it gives the error saying Social Network Login Failure I have posted the code and screenshots below: My settings: 'allauth', 'allauth.account', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount', ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =10 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQURIED=True #ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 115 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED SOCIALACCOUNT_STORE_TOKENS=True LOGIN_REDIRECT_URL = '/' ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', # 'first_name', # 'last_name', # 'verified', # 'locale', # 'timezone', # 'link', # 'gender', # 'updated_time', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.12', }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } My urls: path('accounts/',include('allauth.urls')), -
Django Search Functionality gives error Related Field got invalid lookup: icontains
I am getting a strange error in my search functionality: def search(request): query=request.GET['query'] messages = {} if len(query)>78: allPosts=Post.objects.none() else: allPostsTitle= Post.objects.filter(title__icontains=query) allPostsAuthor= Post.objects.filter(author__icontains=query) allPostsContent =Post.objects.filter(content__icontains=query) allPosts= allPostsTitle.union(allPostsContent, allPostsAuthor) if allPosts.count()==0: messages.warning(request, "No search results found. Please refine your query.") params={'allPosts': allPosts, 'query': query} return render(request, 'blog/search.html', params) Where is the problem? -
{user: ["This field is required."]} doesn't even work when hardcoded (DRF)
I've read through lots of similar topics but can't solve my current issue. I am trying to allow a user to update a list name, which is then POSTed via AJAX to a DRF API. However, I keep getting this error returned: {user: ["This field is required."]} I've tried many different things to overcome this including hardcoding a user in but it still doesn't work. Here is my view: class UpdateUserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def update(self, instance, validated_data): serializer_class = UserListSerializer if self.request.method == "POST": list_id = request.data.get('id') user = self.request.user.id list_name = request.data.get('list_name') data = {'user': user, 'list_name': list_name} serializer = serializer_class(data=data, partial=True) if serializer.is_valid(): serializer.save() return Response({'status' : 'ok'}, status=200) else: return Response({'error' : serializer.errors}, status=400) Here is the relevant serializer: class UserListSerializer(serializers.ModelSerializer): #this is what we worked on on October 1 class Meta: model = UserList fields = ['id', 'user', 'list_name'] Here is the model: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name -
docker-compose: can't access Django container from within Nuxt container
Both my backend (localhost:8000) and frontend (locahost:5000) containers spin up and are accessible through the browser, but I can't access the backend container from the frontend container. From within frontend: /usr/src/nuxt-app # curl http://localhost:8000 -v * Trying 127.0.0.1:8000... * TCP_NODELAY set * connect to 127.0.0.1 port 8000 failed: Connection refused * Trying ::1:8000... * TCP_NODELAY set * Immediate connect fail for ::1: Address not available * Trying ::1:8000... * TCP_NODELAY set * Immediate connect fail for ::1: Address not available * Failed to connect to localhost port 8000: Connection refused * Closing connection 0 curl: (7) Failed to connect to localhost port 8000: Connection refused My nuxt app (frontend) is using axios to call http://localhost:8000/preview/api/qc/. When the frontend starts up, I can see axios catching errorError: connect ECONNREFUSED 127.0.0.1:8000. In the console it says [HMR] connected though. If I make a change to index.vue, the frontend reloads and then in the console it displays: access to XMLHttpRequest at 'http://localhost:8000/preview/api/qc/' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. VM11:1 GET http://localhost:8000/preview/api/qc/ net::ERR_FAILED I have already setup django-cors-headers (included it in INSTALLED_APPS, and set ALLOWED_HOSTS = ['*'] and CORS_ALLOW_ALL_ORIGINS … -
Test SameSite and Secure cookies in Django Test client response
I have a Django 3.1.7 API. Until now I was adding SameSite and Secure cookies in the responses through a custom middleware before Django 3.1, depending on the user agent, with automated tests. Now that Django 3.1 can add those cookie keys itself, I removed the custom middleware and still want to test the presence of SameSite and Secure cookies in the responses. So I added the following constants in settings.py, as Django doc says: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' But when I look at the content of the responses in my tests, I don't get any SameSite neither Secure cookie keys anymore. I printed the content of the cookies, and it's not there. Why? Here are my tests: agent_string = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2227.0 Safari/537.36" from django.test import Client test_client = Client() res = test_client.get("/", HTTP_USER_AGENT=agent_string) print(res.cookies.items()) I also tried with the DRF test client just in case, with same result: agent_string = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2227.0 Safari/537.36" from rest_framework.test import APIClient test_client = APIClient() res = test_client.get("/", HTTP_USER_AGENT=agent_string) print(res.cookies.items()) -
how to iterate over a html tag in jinja templat {django}
I want to iterate over an input tag value! like if the user gives input 6 then 6 input fields will be created! if he gives 10 then 10 input fields should be created! <input type="text" name="sub_count" > {% for x in sub_count %} { <input type="text"> } {% endfor %} What's wrong with it! help -
django.db.utils.DatabaseError: ORA-00933: SQL command not properly ended
I am trying to connect the remote oracle database. I have installed clients and added the path to LD_LIBRARY_PATH. The query and parameters generated are as follows. The query runs in psql, dbeaver. It only fails when running Django. SELECT "AUTHTOKEN_TOKEN"."KEY", "AUTHTOKEN_TOKEN"."USER_ID", "AUTHTOKEN_TOKEN"."CREATED", "AUTH_USER"."ID", "AUTH_USER"."PASSWORD", "AUTH_USER"."LAST_LOGIN", "AUTH_USER"."IS_SUPERUSER", "AUTH_USER"."USERNAME", "AUTH_USER"."FIRST_NAME", "AUTH_USER"."LAST_NAME", "AUTH_USER"."EMAIL", "AUTH_USER"."IS_STAFF", "AUTH_USER"."IS_ACTIVE", "AUTH_USER"."DATE_JOINED" FROM "AUTHTOKEN_TOKEN" INNER JOIN "AUTH_USER" ON ("AUTHTOKEN_TOKEN"."USER_ID" = "AUTH_USER"."ID") WHERE "AUTHTOKEN_TOKEN"."KEY" = :arg0 FETCH FIRST 21 ROWS ONLY {':arg0': <django.db.backends.oracle.base.OracleParam object at 0x10b8497d0>} and the error I am seeing is Traceback (most recent call last): File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/authentication.py", line 196, in authenticate return self.authenticate_credentials(token) File …