Search code examples
djangodjango-rest-frameworkdjango-rest-auth

Email field required django.contrib.auth


I want to register a user in django-rest-auth, if all username, password and email fields are provided. (I want to implement token authentication too to obtain a JSON response from the server.)

The default email field in django.contrib.auth.User is optional. But I want to set the email filed as required to register in the database so that the user gets an HTTP error response when a POST request has been made without an email.

In the project I am registering the new user through the following code.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', User.USERNAME_FIELD, "password", 'full_name',
                  'is_active', 'links', )
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        print("Validated Data",validated_data)
        if 'email' in validated_data:
            user = get_user_model().objects.create(
                username=validated_data['username']
            )
            user.set_email(validated_data['email'])
            user.set_password(validated_data['password'])
            user.save()
            email = EmailMessage('Hello', 'World',
                                 to=[validated_data['email']])
            email.send()
            user.is_active=False
            return user
        else:
            return None

However, the above gives:

create() did not return an object instance

How do I set the email field as a required field?


Solution

  • I want to register an user in django-rest-auth, if all username, password and email fields are provided.

    The correct way to require a field on a serializer in Django REST framework is to set required=True when initializing the field, or using the extra_kwargs parameter to set it on automatically generated fields.

    In default email field in django.contrib.auth.User is optional. But I want to set the email filed as required to register in the database so that the user gets HTTP error response when POST request has been made without a email.

    This means that the automatically generated field will not be required by default, but you can still override it with required=True.

    However, the above gives:

    create() did not return an object instance

    This is because you are not returning a User instance from the create method, just like it says on the tin. Specifically, you are returning None if the email field is not included. None is not a User instance, and DRF is warning you that you're doing something wrong.