Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I login to the Django Rest browsable API when I have a custom auth model?

I have a custom user model as follows in account/models.py

from django.contrib.auth.modles import AbstractUser
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from django.db import models
from django.dispatch import receiver
from django.conf import settings

@receiver(post_save, sender=settings.AUTH_USER_MODEL)                                
def create_auth_token(sender, instance=None, created=False, **kwargs):               
    if created:                                                                      
        Token.objects.create(user=instance)                                          

class UserProfile(AbstractUser):                                                     
    gender = models.CharField(max_length=1,default='') 

and in settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

...

AUTH_USER_MODEL = "account.UserProfile"

However, whenever I try to log into the browsable API, it asks me to use a correct username and password, and I am using credentials of users who are both marked as superusers and staff.

The manage.py runserver console shows this status message:

[27/Jul/2016 20:41:39] "POST /api-auth/login/ HTTP/1.1" 200 2897
like image 390
Max Candocia Avatar asked Jul 27 '16 20:07

Max Candocia


People also ask

How do I add login to the browsable API provided by DRF?

Adding login to the Browsable API We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file. And, at the end of the file, add a pattern to include the login and logout views for the browsable API.


1 Answers

I've ran into this before too and from what I remember it's because the built-in DRF auth form is not using TokenAuthentication, but rather SessionAuthentication. Try adding rest_framework.authentication.SessionAuthentication to your DEFAULT_AUTHENTICATION_CLASSES tuple

like image 65
awwester Avatar answered Oct 01 '22 16:10

awwester