Asutosh Katyal
Asutosh Katyal

Reputation: 111

Django rest framework not encrypting passwords, when being logged into the database

So I am using Django's (1.7 with postgres) Rest Api (Django REST framework 3.0.2) with basic authentication to register and authenticate users for my mobile test app. The problem is that the users I create through the admin panel get their passwords encrypted, however when I create users, using the rest-framework into the same "User" (default) database, the passwords do not get encrypted. This is causing us several problems (especially to validate a user to get a token from api-token-auth). Is there something I can do? Perhaps something in the settings? (We are also running gunicorn and ngnix on our server). Thanks a lot!

Upvotes: 4

Views: 2415

Answers (2)

Eslamspot
Eslamspot

Reputation: 75

Easy way to do that

class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ['email', 'username', 'password']
    extra_kwargs = {'password': {'write_only': True}}

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

Upvotes: 1

José Padilla
José Padilla

Reputation: 216

Sounds like you're just using a ModelSerializer and a ModelViewSet. You're going to have to override your ModelSerializer's create method.

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

The ModelSerializer's doc have an example that might be useful.

Upvotes: 8

Related Questions