Search code examples
pythondjango-rest-frameworkdjango-rest-auth

how to remove username field from login page in django userchangeform


there are three fields in login page(username,email,password) but i want only two fields(email,password). how to remove username field from login page. thanks in advance

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    name = models.CharField(max_length=255)

    def __str__(self):
    return self.email

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('username','email')

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields

serializer.py

from rest_framework import serializers
from . import models

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CustomUser
        fields = ('email', 'username', )

Solution

  • Remove field username from login endpoint

    You can remove the field username by overriding the LoginSerializer like this:

    from rest_auth.serializers import LoginSerializer as RestAuthLoginSerializer
    
    
    class LoginSerializer(RestAuthLoginSerializer):
        username = None
    

    And then adding following in your settings.py:

    REST_AUTH_SERIALIZERS = {'LOGIN_SERIALIZER': 'path.to.your.LoginSerializer'}
    
    ACCOUNT_AUTHENTICATION_METHOD = 'email'
    
    ACCOUNT_EMAIL_REQUIRED = True
    

    Add an endpoint to change email and password

    It turned out that this actually was not the question of the OP but I leave it here for completeness.

    You can add an endpoint to change the users settings like this:

    from rest_framework import serializers, generics
    from . import models
    
    
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.CustomUser
            fields = ('email', 'password')
    
    
    class UserChangeView(generics.UpdateAPIView):
        queryset = models.CustomUser.objects.all()
        serializer_class = UserSerializer
    

    By the way, you don't need the forms for your API.