[英]how to login a Custom User Model in django rest API framework
I defined a Custom User Model in models.py whose name is Student. 我在models.py中定义了一个自定义用户模型,其名称为Student。 This model inherits Django User.
该模型继承了Django用户。 I can sign up student correctly, but when I want to login , I get error.
我可以正确注册学生,但是当我要登录时,出现错误。
I want to login with identity no and student no which exists in database when a student signs up. 我想用学生身份注册时数据库中存在的编号no和学生编号登录。
models.py:
class CustomUser(AbstractUser):
USER_TYPE_CHOICES = ((1, 'student'),
(2, 'professor'),)
username = models.CharField(max_length=50, unique=True)
user_type=models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,
null=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=100)
identity_no = models.PositiveIntegerField(default=0)
email = models.EmailField(max_length=300)
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
entry_year = models.PositiveIntegerField()
student_no = models.PositiveIntegerField()
serilizers.py:
class CustomUserForLogin(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = (
'identity_no',
)
class StudentLoginView(serializers.ModelSerializer):
user = CustomUserForLogin()
class Meta:
model = Student
fields = [
"user",
"student_no", ]
def validate(self, data): # validated_data
identity_no = data.get('identity_no')
print("identity_no", identity_no)
student_no = data.get("student_no")
print("student_no", student_no)
# to search username or email is a user Model
user = Student.objects.filter(
Q(identity_no=identity_no) |
Q(student_no=student_no)
).distinct()
print("user", user)
if user.exists() and user.count() == 1:
user_obj = user.first()
else:
raise ValidationError("This username or student_no is not existed")
if user_obj:
if not user_obj.check_password(student_no): # Return a boolean of whether the raw_password was correct.
raise ValidationError("Incorrect Credential please try again")
return user_obj
views.py:
views.py:
class StudentloginView(APIView):
permission_classes = [AllowAny]
serializer_class = StudentLoginView
def post(self, request, *args, **kwargs):
data = request.data
serializer = StudentLoginView(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
FieldError at /system/student-login/ / system / student-login /中的FieldError
Cannot resolve keyword 'identity_no' into field. 无法将关键字“ identity_no”解析为字段。 Choices are: courserelationstudent, entry_year, id, student_no, user, user_id
选项包括:courserelationstudent,entry_year,id,student_no,user,user_id
Request Method: POST Request URL: http://127.0.0.1:8000/system/student-login/ Django Version: 1.11.17 Exception Type: FieldError Exception Value: 请求方法:POST请求URL: http : //127.0.0.1 :8000/system/student-login/ Django版本:1.11.17异常类型:FieldError异常值:
Cannot resolve keyword 'identity_no' into field. 无法将关键字“ identity_no”解析为字段。 Choices are: courserelationstudent, entry_year, id, student_no, user, user_id
选项包括:courserelationstudent,entry_year,id,student_no,user,user_id
Exception Location: C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\django\\db\\models\\sql\\query.py in names_to_path, line 1352 Python Executable: C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\python.exe Python Version: 3.7.3 Python Path: 例外位置:names_to_path中的C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ lib \\ site-packages \\ django \\ db \\ models \\ sql \\ query.py,第1352行Python可执行文件:C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ python.exe Python版本:3.7.3 Python路径:
['C:\\Users\\LELA\\Desktop\\APINewSystem', 'C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\LELA\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages'] ['C:\\ Users \\ LELA \\ Desktop \\ APINewSystem','C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ python37.zip','C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ DLLs','C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ lib','C:\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37','C :\\ Users \\ LELA \\ AppData \\ Local \\ Programs \\ Python \\ Python37 \\ lib \\ site-packages']
Server time: Sat, 6 Jul 2019 05:37:50 +0000 服务器时间:2019年7月6日,星期六05:37:50 +0000
Look closer at the student filtering: 仔细查看学生过滤条件:
user = Student.objects.filter(
Q(identity_no=identity_no) |
Q(student_no=student_no)
).distinct()
And then at your models: 然后在您的模型上:
class CustomUser(AbstractUser):
...
identity_no = ...
class Student(models.Model):
...
user = ...
student_no = ...
The fields identity_no
and student_no
are in two separate models - User
and Student
. 字段
identity_no
和student_no
在两个单独的模型中: User
和Student
。 Thus in your students filtering you should perform filtration on the related user model: 因此,在学生过滤中,您应该对相关的用户模型执行过滤:
user = Student.objects.filter(
Q(user__identity_no=identity_no) | # <<<
Q(student_no=student_no)
).distinct()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.