Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework user registration?

I am following this tutorial but facing these problems I can't fix:

  1. Upon registering user, I can not log in with that user to the api because the password is not hashed "Invalid password format or unknown hashing algorithm." in admin
  2. I cannot post to 'api/accounts' or see the form in the browseable api when I am not logged in to the api

My code:

from django.contrib.auth.models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('password', 'first_name', 'last_name', 'email')
        write_only_fields = ('password',)

    def restore_object(self, attrs, instance=None):
        # call set_password on user object. Without this
        # the password will be stored in plain text.
        user = super(UserSerializer, self).restore_object(attrs, instance)
        user.set_password(attrs['password'])  #somehow not hashing
        return user
like image 651
user3149525 Avatar asked Apr 12 '14 18:04

user3149525


People also ask

What is permission in Django REST framework?

Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.


2 Answers

I tried the accepted answer in DRF 3.0.2 and it didn't work. The password was not being hashed.

Instead, override the create method in your model serializer

    def create(self, validated_data):
        user = User(email=validated_data['email'], username=validated_data['username'])
        user.set_password(validated_data['password'])
        user.save()
        return user

This hashes the password when you create a user using the rest framework, not post_save

like image 83
wsgeorge Avatar answered Sep 29 '22 12:09

wsgeorge


Another approach for DRF 3.X:

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password

    def create(self, validated_data):    
        if validated_data.get('password'):
            validated_data['password'] = make_password(
                validated_data['password']
            )

        user = get_user_model().objects.create(**validated_data)

        return user
like image 36
psychok7 Avatar answered Sep 29 '22 11:09

psychok7