Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute '_meta' django login setup without password
I am trying to authenticate user with the system username but I am getting below error: AttributeError at / 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.15 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' if getpass.getuser() != None: login(request, getpass.getuser()) if user.user_type == "1": print("Admin") return HttpResponseRedirect(request, '/admin_home') elif user.user_type == "2": print("staff") return HttpResponseRedirect(request, reverse("staff_home")) else: return HttpResponseRedirect(request, reverse("student_home")) else: # messages.error(request,"Invalid Login Details") messages.error( request, "You Do No Have Access To This Application") return HttpResponseRedirect("/") -
How to solve FileNotFoundError: [Errno 2] while deploying in heroku?
While deploying in heroku, I face this problem. If I run py manage.py collectstatic --noinput I'm seeing 0 static files copied to 'D:\Coding\horek\uddokta\mysite\staticfiles, 132 unmodified, 300 post-processed. If I run heroku config:set DISABLE_COLLECTSTATIC=1 and deployed to heroku then I see Bad request(400). Should I copy {% load static %} in every html file? My settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ ........ 'libooki', MIDDLEWARE = [ .......................................... 'whitenoise.middleware.WhiteNoiseMiddleware', STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Traceback when pushing in heroku remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 109, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line … -
What are the downsides of using filesystem for storing uploaded files in django?
I know about s3 storage but I am trying to see if things can work out by only using filesystem -
create django user who can not login
I want to create a user whom I'm using as a ForeignKey and i don't want those users can login to system. I have no idea how to go on. (about setting set_unusable_password() or None, and how to perform it): my accounts.py file is as class User(AbstractBaseUser): GENDER = (("MALE", "Male"), ("FEMALE", "Female")) user_type = models.CharField(max_length=50, choices=Types.choices, default=Types.PATIENT) full_name = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, blank=True, null=True, unique=True) active = models.BooleanField(default=False) gender = models.CharField(max_length=15, choices=GENDER) admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "phone" # username REQUIRED_FIELDS = [] objects = UserManager() thanks in advance guys. <3 -
How to add more than one cast for a movie model in Django?
I'm making a movie app in Django. I have a model named Movie with its usual properties. I want to create another model named Cast where I'll create different actors. For a given movie, I want to be able to link different actors and also the actors shouldn't be removed when a movie is deleted. I tried using ForeignKey for the Cast at the actors field in Movie model. Thus it looked like this: class MovieCast(models.Model): """ Model for the actors in a movie """ actor_name = models.CharField(max_length=100) class Movie(models.Model): """ Base class for the properties our movie will have """ **other items** cast = models.ForeignKey(MovieCast, on_delete=models.PROTECT) What the problem is that the models do show up in admin site and I am able to add an actor to the MovieCast model, but in the cast field of the Movie model, I can't add more than one actors. -
How to design Invite model with additional data if user does not exist in Django
I am unsure about the correct implementation for the following problem, while designing an e-signing service: There is a Contract entity There is a ContractRecipientEvent entity, which is created using through m2m table. Here is code for those models: class Contract(AbstractModelBase): owner = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name="contracts") contract_signing_date = models.ForeignKey(ContractSigningDate, on_delete=models.CASCADE) title = models.CharField(max_length=32) contract_signing_type = models.CharField( max_length=64, choices=ContractSigningType.choices, default=ContractSigningType.SIMPLE ) recipients = models.ManyToManyField(User, through="ContractRecipientEvent", related_name="contracts_from_events") Then there is ContractRecipientEvent: class ContractRecipientEvent(AbstractModelBase): contract = models.ForeignKey(Contract, on_delete=models.CASCADE, related_name='contract_to_person') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person_to_contract') role = models.CharField( max_length=64, choices=ContractRecipientAction.choices, default=ContractRecipientAction.SIGN ) message = models.TextField(max_length=1000, null=True, blank=True) recipient_signing_status = models.CharField( max_length=64, choices=ContractRecipientSigningStatus.choices, default=ContractRecipientSigningStatus.NOT_SIGNED, blank=True, ) As you can see ContractRecipientEvent has references to both Contract and User. It works well if the User is already created. The problem is that I need the following behavior: The Contract Serializer should only accept recipients' emails. Those emails will most likely be of the new users, who are not registered in the system so that they don't have a User entity. I think that I need to create a separate Invite model, which would have an email field. Then I could check after user registration for which contract he was invited to, delete the Invite record, and … -
Django, runserver issues (windows)
I've been looking for the solution everywhere. I tries to execute "python manage.py runserver" command, but all I recieves is an error. enter image description here I have a virtualenv activated, which is also visible at the screen. Also i did the "path" thing. (enter image description here) I have lost so many time for this. What else can i do? I must note, that i am quite new in this world. Barely did my first "hello world" recently. -
convert a datetime string into datetime object python
I have a form with two fields and one field gets the selected date and the other gets a selected time ,this is my form : <input id="datepicker" class="form-control shadow-sm datepicker" name="date" type="text" {%if meeting.pk%} value="" data-value="{{meeting.date_time.date|date:'Y-m-d'}}"{%else%} value="" data-value="2021-02-14"{%endif%} required> <div style="color: red;" class="invalid-feedback"></div> </div> <div class="col-6 pr-0"> <input id="input_from" class="form-control shadow-sm timepicker" type="time" {%if meeting.pk%} data-value="{{meeting.date_time.time}}" {%else%} data-value="Date" {%endif%} name="time" required> <div style="color: red;" class="invalid-feedback"></div> </div> i need to take these two fileds in the init function of the form and convert them into one datetime object and save it in model, this is init function : class CreatMeetingForm(forms.ModelForm): date = forms.DateField(required=True) time = forms.TimeField(required=True, widget=forms.TimeInput(format='%H:%M')) class Meta: model = Meeting fields = ['time_zone','title','members_email','date','time','description','lat','lng','meeting_photo','yelp_business_id','is_virtual','meeting_url','location_name','location_address'] def __init__ (self,data=None,*args , **kwargs): if data is not None : data = data.copy() date_field =data.get('date') time_field = data.get('time') date_time_filed = date_field+" "+time_field date_time = datetime.strptime(date_time_filed,'%Y/%m/%d %H:%M:') data['date_time'] = date_time super().__init__(data,*args,**kwargs) but i get this error : ValueError at /meeting/create-meeting/ time data '2021-02-2112:30' does not match format '%Y/%m/%d %H:%M:' Traceback Switch to copy-and-paste view /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/contrib/auth/decorators.py, line 21, in _wrapped_view … -
Saving an integer value obtained by JS/ jQuery into Django models
I have made this crude type of quiz application, and it still needs refining, but as the title states, I want to save the marks obtained by the participant into the database, but I'm not sure how to write its code. If you look at the jquery code I've written var points = []; $("#q1b,#q2d,#q3a,#q4c,#q5b,#q6a,#q7c").click(function result() { if($(this).hasClass("toggled")){ points.push(1); console.log(points); } else { points.pop(); console.log(points); } var score = points.length; document.getElementById('score').innerHTML = `${score} / 7`; }); and as for my models.py file from django.db import models from django.conf import settings # Create your models here. class score(models.Model): marks = models.IntegerField() participant = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.participant}:{self:marks}' My app does have a user registration/login system (I made another app for it, for practicing). the participant can only take the quiz after registering. So that if the user logs in again, he may be able to see his results, rather than taking the quiz again. This is all I have in my views.py from django.shortcuts import render # Create your views here. def welcome_view(request): return render(request, 'quizapp/welcome.html') def quiz_view(request): return render(request, 'quizapp/quiz.html') def result_view(request): return render(request, 'quizapp/results.html') yup, that's it...bcuz basically, it's based on more javascript stuff. I didn't hardcode … -
Link static/css file with Django template
I am pretty new with Django and I am trying to link css file with my html document and I have tried using all possible ways posted on stackoverflow and I am unable to locate what is the issue in here. Here is the directory and file structure: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) index.html {% load static %} <link rel="stylesheet" type="css/text" href="{% static 'css/style.css' % }"> Thanks in advance. -
how do I handle matching query does not exist when try catch doesnt work?
I want to skip adding subtechnique if the parent technique is not on the database to avoid matching query does not exist. , but however if I use .first or .exists it doesnt work even with if not ... or try catch blocks keeps the same error where come from Dmeo.objects.get_or_create( how can I fix this issue? trace back analizer | apps.api.models.DoesNotExist: Dmeo matching query does not exist. analizer | The above exception was the direct cause of the following exception: analizer | analizer | Traceback (most recent call last): analizer | File "updater.py", line 38, in <module> analizer | subtechnique, created = Dmeo.objects.get_or_create( falling code for subtechnique in src_subtechniques: for data_subtechniques in subtechnique: technique = Technique.objects.filter(technique_id=data_subtechniques['technique_id'].partition('.')[0]).exists() subtechnique, created = Dmeo.objects.get_or_create( subtechnique_id=data_subtechniques['technique_id'], technique_name=data_subtechniques['technique'], url=data_subtechniques['url'], ) -
TruncMinute Celery TaskResult
I am trying to display statistics about the "django-celery-results" I need a list to use for chartjs. last_records = TaskResult.objects.filter(task_name='scraper.tasks.send_game', date_created__day=20).order_by("-date_created")[:100] queryset = last_records.annotate(date=TruncMinute('date_created')).values("date_created").annotate(created_count=Count('id')) I made this query however its not returning the correct response. There are many records so thats why I limit it to last 100 records. In order to use chartjs correctly, I need a list of the date with the hour and how many records there are of it. I need something like this: [{'date_created': '2021-02-20 10:49'), 'count': 2}, ...] -
Unable to make migrations in django
I have a model class in which I have 4 fileds when I am trying to make migrations its saying: No changes detected Below is my model file: models.py from django.db import models # Create your models here. class CarDetail(models.Model): modelname = models.CharField(max_length=20) modelimg = models.ImageField(upload_to = 'allcars/') modelcolor = models.CharField(max_length=11) modelage = models.IntegerField() Someone please let me know how can I migrate fields to database any help would be appreciated. THANKS -
How can I allow for returns in Django form inputs?
I have a form that accepts texts and can save it but when I put in "Hello World" it gets saved and comes out as "Hello World" without the return. How can I allow for the return to be saved? -
AttributeError 'tuple' object has no attribute 'encode' during all auth login with facebook
I am trying to integrate the social login into my project. during login Facebook, gives the error 'tuple' object has no attribute 'encode'.I have used django-allauth django-allauth and I used the Heroku go deploy projects. to see the error click. Inside the database data, entry from Facebook is happening. to see facebook entry any suggestions to rid of this problem. Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'encode' -
Images can't display with django when storing in s3 aws
I'm storing images in media with s3 aws. I've added Media_root to urlpatterns but they are still missing in my homepages. The pictures are visible in my s3 aws bucket. Any suggestion for this ? Many Thanks -
django allauth - get() returned more than one User -- it returned 2! in production
I'm trying to add google auth service to my site, it is working correctly in localhost, but in the server, I've got an error when a new user tries to sign up although the old users can connect their account to google account without any problems get() returned more than one User -- it returned 2! there is no duplicated either in the user model or social account model. before I added social auth users could only log in or sign in with their email addresses, so now my AUTHENTICATION_BACKENDS is like that: AUTHENTICATION_BACKENDS = ( 'user_profile.backends.EmailBackend', 'allauth.account.auth_backends.AuthenticationBackend',) and my EmailBackend file in like this: class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username.lower()) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user if user.id: return try: customer = User.objects.get(email=user.email) # if user exists, connect the account to the existing account and login sociallogin.state['process'] = 'connect' perform_login(request, customer, 'none') except User.DoesNotExist: pass and in my settings.py: SOCIALACCOUNT_ADAPTER = 'user_profile.backends.MySocialAccountAdapter' thanks a lot, it has been a disaster -
add to cart function not working in django rest framework using functional view
I tried to create an add-to-cart api using (non api-server-side) code into Django rest framework. But when I call api in postman it shows 403 forbidden. I haven't use any serializer in this view. Also, I tried using APIView and serializers, it doesnt work as well. I am new to django rest framework. I need help writing this. My models: class OrderItem(models.Model) : user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.name}" class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) items = models.ManyToManyField(OrderItem,blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.email My views: @login_required def add_to_cart(self, pk): item = get_object_or_404(Product, pk=pk) order_item, created = OrderItem.objects.get_or_create( item=item, user=self.request.user, ordered=False ) order_qs = Order.objects.filter(user=self.request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__pk=item.pk).exists(): order_item.quantity += 1 order_item.save() return Response({"message": "Added quantity Item", }, status=status.HTTP_200_OK ) else: order.items.add(order_item) return Response({"message": " Item added to your cart", }, status=status.HTTP_200_OK, ) else: ordered_date = datetime.timezone.now() order = Order.objects.create(user=self.request.user, ordered_date=ordered_date) order.items.add(order_item) return Response({"message": "Item added to your cart", }, status=status.HTTP_200_OK, ) My url: path('api/addorderitem/int:pk', views.add_to_cart, name='api-addorder'), The following code is using APIView: class AddtoOrderItemView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = OrderItem.objects.all() … -
Excuse meท What happened with the command ( python manage.py shell)
When i run python manage.py shell on other PC. It shows this :enter image description here. But when i run python manage.py shell on my PC. It always shows this message : enter image description here so i don't want to run IPython.I just want to run python shell. I don't know why it is like this.Can you tell me how to solve this problem. -
partially initialized module 'rest_framework.views' has no attribute 'APIView' (most likely due to a circular import)
I have two file : first is the my main module's file(django-rest-framework-simplejwt/rest_framework_simplejwt/views.py / ) and other is my project file(authenticate.py).But when I inherit post method from TokenRefreshView.At that time this error occured: from rest_framework_simplejwt.views import TokenRefreshView File"C:\Users....\lib\site-packages\rest_framework_simplejwt\views.py", line 1, in from rest_framework import generics, status File "C:\Users....\lib\site-packages\rest_framework\generics.py", line 24, in class GenericAPIView(views.APIView): AttributeError: partially initialized module 'rest_framework.views' has no attribute 'APIView' (most likely due to a circular import) For more clarity see this: See this file authenticate.py: from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.exceptions import InvalidToken,TokenError from rest_framework_simplejwt.views import TokenRefreshView from django.conf import settings import requests import json from .utility import set_browser_cookie from rest_framework.response import Response class CustomTokenRefreshView(TokenRefreshView): """ Takes a refresh type JSON web token and returns an access type JSON web token if the refresh token is valid. """ def post(self, request, *args, **kwargs): response = Response() serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) print("token = ",serializer.validated_data) print("token = ",serializer.validated_data["access"]) set_browser_cookie(response,settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS'],serializer.validated_data) response.data = serializer.validated_data return response For more clarity see this: See this file django-rest-framework-simplejwt/rest_framework_simplejwt/views.py/ from rest_framework import generics, status from rest_framework.response import Response from . import serializers from .authentication import AUTH_HEADER_TYPES from .exceptions import InvalidToken, TokenError class TokenViewBase(generics.GenericAPIView): permission_classes = () authentication_classes = () … -
"su postgres" not a recognized command
In the book "Django 3 by Example" on page 108/569 I'm trying to set up full text search for my blog. Now I want to connect Django to a PostgreSQL database instead of SQLite. After installing PostgreSQL for Windows, it resides on C:\ProgramData\Microsoft\Windows\Start Menu\Programs\PostgreSQL 13 In my Command Prompt I used C:\Users\DELL\my_env>Scripts\activate to get into my virtual environment. Then with >pip install psycopg2-binary I successfully installed psycopg2-binary-2.8.6 However, the book now asks me to enter su postgres. When I enter (my_env) C:\Users\DELL\my_env>su postgres it returns "'su' is not recognized as an internal or external command, operable program or batch file." What am I missing? -
Duplicate message are send in websocket
In my application, I only called socket.onmessage() one time, but it receives the duplicate message. For example, I have browser 1 and browser 2 with two different user id, but instead of receiving one message for each browser, browser 1 didn't receive anything, but the browser 2 received twice. This is how I send the data in the consumer.py await self.channel_layer.group_send( self.project_page, { "type": "discussion_message", "text": json.dumps(data) } ) This is actually working in localhost, but when I deploy it in the heroku, this situation happens. We used 2 dynos for it (not sure if this could be the reason), but could anyone help me to solve this issue? Thanks! -
DRF Serializer for Writable Nested JSON
Firstly, I would like to mention that I've already seen many SO posts about this issue, but still couldn't figure out the problem occurring here. I would like to POST a JSON object to my Django application, which looks like this: { "id": "1363362773409783808", "text": "@MsLaydeeLala Damn haha. Reminds me of my dog. If someone comes into my room while I\u2019m sleeping he gets up and growls at them if he doesn\u2019t recognize them right away.", "created_at": "2021-02-21T05:39:49.000Z", "author": { "id": "112233445566778899", "username": "Elrafa559", "name": "EL RAFA" }, "keywords": [ { "name": "dog" } ] } and save it to my database, where my models are: class Keyword(models.Model): """ Represents keywords which we are looking for, must be unique, 20 chars max. """ name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class TwitterAccount(models.Model): id = models.CharField(max_length=20, primary_key=True) username = models.CharField(max_length=80) name = models.CharField(max_length=80) class Tweet(models.Model): id = models.CharField(max_length=20, primary_key=True) text = models.CharField(max_length=380) # 280 for tweet, 100 for links created_at = models.DateTimeField() author = models.ForeignKey(TwitterAccount, on_delete=models.CASCADE) keywords = models.ManyToManyField(Keyword) def __str__(self): return str(self.author.username) + "/" + str(self.id) class TweetKeyword(models.Model): # TODO is CASCADE the right choice? tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE) for that, I've written this serializer: … -
in django why doesn't my database table get all the info that i entered into the form?
in Django why doesn't my database table get all the info that i entered into the form? i only get the name and the age when i retrieve the table and the rest not showing? there is no indentation error i use pycharm i need to know why when i look at the table phpmyadmin i only see result for the full_name and the age is there anyway to help is there any kind of certain type of database utf8 or anything else thanks for help and if you dont get me well please contact me on facebook https://www.facebook.com/7assan3aly/ view.py from django.shortcuts import render from django.http import HttpResponse from .models import Contact from django.contrib import messages def contact(request): if request.method=='POST': if request.POST.get('full_name') \ and request.POST.get('email') \ and request.POST.get('mobile_number') \ and request.POST.get('whatsapp') \ and request.POST.get('xray_image') \ and request.POST.get('message'): savored = Contact() savored.full_name = request.POST.get('full_name') savored.age = request.POST.get('age') savored.email = request.POST.get('email') savored.mobile_number = request.POST.get('mobile_number') savored.whatsapp = request.POST.get('whatsapp') savored.xray_image = request.POST.get('xray_image') savored.message = request.POST.get('message') savored.save() messages.success(request, 'Done') return render(request, 'contact.html') else: return render(request, 'contact.html') ===========model.py============= from django.db import models class Contact(models.Model): full_name = models.CharField(max_length=30) age = models.IntegerField() # age = models.CharField(max_length=31) email = models.CharField(max_length=32) mobile_number = models.CharField(max_length=33) whatsapp = models.CharField(max_length=34) xray_image = models.CharField(max_length=301) … -
Token Authrorization Django {"detail":"Authentication credentials were not provided."}
I am trying to implement Token based Authorization at my server APIs. But, when i fire a query then it returns {"detail":"Authentication credentials were not provided."} I have done almost all the settings recommended at various posts and also at Django documentation. In my settings.py INSTALLED_APPS = [ 'rest_framework.authtoken', ] And also, REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } In my views file: from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] And in my Apache Config file at WSGI WSGIPassAuthorization On RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP-AUTHORIZATION:%1] I don't know if i am missing anything other than this.The token is pre-generated at super user level using command line.