如何在Django Rest API框架中登录自定义用户模型 [英] how to login a Custom User Model in django rest API framework
问题描述
我在models.py中定义了一个自定义用户模型,其名称为Student。该模型继承了Django User。我可以正确注册学生,但是当我要登录时,出现错误。
我想用学生注册时在数据库中存在的标识no和学生号登录。
models.py:
类CustomUser(AbstractUser):
USER_TYPE_CHOICES =(((1,'student'),
(2,'professor'), )
用户名= models.CharField(最大长度= 50,唯一=真)
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)
类Student(models.Model):
user = models.OneToOneField(CustomUser,on_delete = models.CASCADE)
entry_year = models.PositiveIntegerField()
student_no = models.PositiveIntegerField()
serilizers.py:
类CustomUserForLogin(serializers.ModelSerializer):
类Meta:
模型= CustomUser
字段= (
'identity_no',
)
类StudentLoginView(serializers.ModelSerializer):
用户= CustomUserForLogin()
类Meta:
模型=学生
字段= [
用户,
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 )
#搜索用户名或电子邮件的用户是用户模型
user = Student.objects.filter(
Q(identity_no = identity_no)|
Q(student_no = student_no)
).distinct()
print( user,用户)
如果user.exists()和user.count()== 1 :
user_obj = user.first()
其他:
引发ValidationError(此用户名或Student_no不存在)
如果user_obj:
(如果不是user_obj)。 check_password(student_no):#返回一个布尔值,表明raw_password是否正确。
提高ValidationError(凭据不正确,请重试)
return user_obj
views.py:
class StudentloginView(APIView):
Permission_classes = [AllowAny]
serializer_class = StudentLoginView
def post(自己,请求,* args,** kwargs):
data = request.data
serializer = StudentLoginView(data = data)
如果serializer.is_valid(raise_exception = True):
new_data = serializer.data
return响应(new_data,status = HTTP_200_OK)
return响应(serializer.errors,status = HTTP_400_BAD_REQUEST)
/ system / student-login /上的FieldError p>
无法将关键字 identity_no解析为字段。选项包括:courserelationstudent,entry_year,id,student_no,user,user_id
请求方法:POST
请求URL: http://127.0.0.1:8000/system/student-login/
Django版本:1.11.17
异常类型:FieldError
异常值:
无法将关键字 identity_no解析为字段。选项包括:courserelationstudent,entry_year,id,student_no,user,user_id
例外位置:C:\Users\LELA\AppData\Local\Programs\ namesPython\Python37\lib\站点包\django\db\models\sql\query.py in names_to_path,第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\程序\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']
服务器时间:2019年7月6日,星期六05:37:50 +0000
解决方案靠近学生过滤:
user = Student.objects.filter(
Q(identity_no = identity_no)|
Q(student_no = student_no)
).distinct()
在您的模型上:
class CustomUser(AbstractUser):
...
identity_no = ...
班级Student(models.Model):
...
用户= ...
student_no = ...
字段
identity_no
和student_no
有两个单独的模型-User
和Student
。因此,在学生过滤中,您应该对相关的用户模型执行过滤:user = Student.objects.filter(
Q(user__identity_no = identity_no)|#<<
Q(student_no = student_no)
).distinct()
I defined a Custom User Model in models.py whose name is Student. This model inherits Django User. 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.
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:
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/
Cannot resolve keyword 'identity_no' into field. Choices are: 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:
Cannot resolve keyword 'identity_no' into field. Choices are: 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:
['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
解决方案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
andstudent_no
are in two separate models -User
andStudent
. 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()
这篇关于如何在Django Rest API框架中登录自定义用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!