我正在尝试通过电子邮件使用django rest_auth登录:
serializers.py:
from rest_framework import serializers
from users.models import User
from rest_auth.serializers import LoginSerializer
class CustomLoginSerializer(LoginSerializer):
username = None
email = serializers.EmailField(required = True)
password1 = serializers.CharField(write_only = True)
class Meta:
model = User
fields = ('email','password')
导入了loginview:
from rest_auth.views import LoginView
class CustomLoginView(LoginView):
queryset = User.objects.all()
用户模型:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError('user must have email address')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
email=email,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_joined=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
user=self._create_user(email, password, True, True, **extra_fields)
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length = 100, unique = True)
First_Name = models.CharField(max_length = 100, null = True, blank = True)
Last_Name = models.CharField(max_length = 100, null = True, blank = True)
is_staff = models.BooleanField(default = False)
is_superuser = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
last_login = models.DateTimeField(null = True, blank = True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = "email"
EMAIL_FIELD = "email"
REQUIRED_FIELD = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
settings.py:
REST_AUTH_SERIALIZERS = {
'LOGIN_SERIALIZER': 'api.serializers.CustomLoginSerializer'
}
我已经用电子邮件创建了自定义用户模式,因此错误显示用户名有效,但是我该如何从登录名中删除。当我运行localhost:8000 / rest-auth / login时,我正在获取电子邮件和密码视图,但登录后显示如下:
Field name `username` is not valid for model `User`
答案 0 :(得分:0)
如果您不想将用户名添加到序列化程序中,只需删除username = None