Search code examples
djangorestdjango-rest-frameworkbasic-authenticationdjango-authentication

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!


Solution

  • 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.