ngx311
ngx311

Reputation: 507

Django REST Framework Token Registration

I'm trying to create a user registration with Django-Rest-Framework. But when I go to my url I get this message:

{ "detail": "Authentication credentials were not provided." }

Here's a screen capture.

Is it asking for a token? I'm trying to register the user so it shouldn't have/need one at this point right?

Mind you, I'm just using my browser and just going to

127.0.0.1:8000/register

I'm not playing around with angular and requesting api's, I just went to /register in my browser to see what I would get. I was expecting to see a form or something. Is it working properly and I just accessed it the wrong way?

Here's my models.py

@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 CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField('email address', unique=True, db_index=True)
    password1 = models.CharField(max_length=50)
    username = models.CharField('username', max_length=50, unique=True, db_index=True)
    image = models.FileField(upload_to='photos', null=True, blank=True)
    joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    friends = []

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __unicode__(self):
    return self.username

    class Meta:
        unique_together = (('username', 'password1'),)

my views.py

@api_view(['POST'])
def create_auth(request):
    serialized = CustomUserSerializer(data=request.DATA)
    if serialized.is_valid():
        CustomUser.objects.create_user(
            serialized.init_data['email'],
            serialized.init_data['username'],
            serialized.init_data['password1']
        )
        return Response(serialized.data, status=HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=HTTP_400_BAD_REQUEST)

urls.py

router = DefaultRouter()
router.register(r'friends', FriendViewSet)
router.register(r'posts', PostViewSet, 'Post')

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(router.urls)),
    url(r'^users/$', UserView.as_view()),
    url(r'^add_friend/$', add_friend),
    url(r'^register', create_auth), # This is the url I'm trying to access.
    url(r'^api-token-auth/$', ObtainAuthToken.as_view()),
    url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^logout/$', Logout.as_view()),

]

EDIT 1 settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
       'rest_framework.authentication.SessionAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
   ),
}

Upvotes: 0

Views: 1797

Answers (1)

levi
levi

Reputation: 22697

Try to adding permission_classes decorator along IsNotAuthenticated to your view

from authentication.permissions import IsNotAuthenticated


@api_view(['POST'])
@permission_classes((IsNotAuthenticated,))
def create_auth(request):
    serialized = CustomUserSerializer(data=request.DATA)
    if serialized.is_valid():
        CustomUser.objects.create_user(
            serialized.init_data['email'],
            serialized.init_data['username'],
            serialized.init_data['password1']
        )
        return Response(serialized.data, status=HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=HTTP_400_BAD_REQUEST)

My recomendation: Work with Based-Class Views

Upvotes: 1

Related Questions