简体   繁体   English

如何在Django Rest API框架中登录自定义用户模型

[英]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_nostudent_no在两个单独的模型中: UserStudent 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.

相关问题 django-rest-framework 自定义用户模型登录失败 - django-rest-framework custom user model login failed Django rest 框架不验证自定义用户模型 - Django rest framework not authenticating custom user model 自动将用户令牌分配给自定义配置文件模型 django rest 框架 - Automatically assigning User token to custom profile model django rest framework Django REST Framework,保存到自定义用户模型的其他字段 - Django REST Framework, save to extra field on custom user model 当我有自定义身份验证模型时,如何登录到 Django Rest 可浏览 API? - How do I login to the Django Rest browsable API when I have a custom auth model? 如何与Django用户模型建立一对一关系的自定义模型的Rest Api - How to build Rest Api for custom model with one to one relationship with django user model 如何在 django-rest-framework-simple-jwt 中使用自定义模型用户 - how to use custom model user in django-rest-framework-simple-jwt 如何在 Django Rest Framework 中为用户登录创建 Json Web 令牌? - How to create Json Web Token to User login in Django Rest Framework? Django REST Framework / Django-额外的用户模型 - Django REST Framework/Django - extra user model 如何使用Django Rest Framework创建登录API? - How do I create a login API using Django Rest Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM