我正在用Django进行身份验证,添加USERNAME_FIELD
更改模型,并创建视图进行登录,但仍然无法进行。我使用的电子邮件地址为username
Django==2.2.8
django-cors-headers==3.2.0
django-filter==2.2.0
djangorestframework==3.10.3
我的代码:
用户模型:
class User(AbstractBaseUser,
UGCModel):
class Meta:
app_label = 'user'
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=254, unique=True)
username = models.CharField(max_length=150, unique=True)
email_verified = models.BooleanField(default=False)
genre = models.CharField(max_length=1, choices=GENRES, blank=True)
date_of_birth = models.DateField(blank=False, null=True)
cep = models.CharField(validators=[v.validate_cep], max_length=100)
USERNAME_FIELD = 'username'
def __str__(self):
return '(User)%s' % self.email
我的观点:
def post(self, request, format=None):
errors = None
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
errors = serializer.errors
else:
username = request.data['username']
password = request.data['password']
user = authenticate(self, username=username, password=password)
if user:
pass
else:
errors = 'check username or password'
if not errors:
login(request, user)
user.relationships.flush_cache()
data = {'detail': 'authenticated',
'super' : user.super_user,
'key': Token.objects.get(user=user).key}
return Response(data, status=status.HTTP_200_OK)
detail = {'detail': errors}
return Response(detail, status=status.HTTP_400_BAD_REQUEST)
我将其添加到设置中:
AUTH_USER_MODEL = "user.User"
用户创建成功:
uid: "_e8f35f44afa8"
username: "vini@gmail.com"
password: "123123"
first_name: "vini"
cep: "05407-002"
last_name: "morais"
email: "vini@gmail.com"
date_of_birth: null
但是身份验证总是失败。
vini@gmail.com 123123
check username or password
Bad Request: /login
WARNING:django.request:Bad Request: /login
[20/Dec/2019 23:51:03] "POST /login HTTP/1.1" 400 39
身份验证将发送到authenticate(self, username=username, password=password)
,但是它不起作用。我忘记了要设置的东西吗?