简体   繁体   English

如何使用 django rest 框架为不同的用户类型创建自定义用户模型

[英]How can I create custom user model for different user types using django rest framework

I am new to django rest framework and I want to create different types of users "I think it should be 4", (students, teachers, staff and admin) And I want the staff user to register the teacher and student users.我是 django rest 框架的新手,我想创建不同类型的用户“我认为应该是 4”,(学生、教师、员工和管理员)并且我希望员工用户注册教师和学生用户。 I want to use custom user model and use email to register and login, can it be done, please help, I have been looking for days for anything that can help me to understand how to do it我想使用自定义用户模型并使用电子邮件进行注册和登录,可以做到吗,请帮忙,我一直在寻找任何可以帮助我了解如何操作的东西

You can use AbstractUser , This is pretty straighforward since the class django.contrib.auth.models.AbstractUser provides the full implementation of the default User as an abstract model.您可以使用 AbstractUser ,这非常简单,因为类 django.contrib.auth.models.AbstractUser 提供了默认 User 作为抽象模型的完整实现。

**
    from django.db import models
    from django.contrib.auth.models import AbstractUser
    USER_TYPE_CHOICES = (
     ('student', 'student'),
     ('teacher', 'teacher'),
     ('staff', 'staff'),
     ('admin', 'admin'),
                        )
    class User(AbstractUser):
       user_type = models.CharField(max_length=40,choices=USER_TYPE_CHOICES)
**

After that you have to update our settings.py defining the AUTH_USER_MODEL property.之后,您必须更新定义 AUTH_USER_MODEL 属性的 settings.py。

 AUTH_USER_MODEL = 'Your app name.User'

You can email as username in your serializers.py:您可以在 serializers.py 中以用户名发送电子邮件:

class RegisterSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)

    class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'password','password1',  'user_type',)

    def validate(self, attr):
       validate_password(attr['password'])
       return attr

    def create(self, validated_data):
          user = User.objects.create(
                username=validated_data['email'],
                user_type=validated_data['user_type'],
                email=validated_data['email'],
                first_name=validated_data['first_name'],
                last_name=validated_data['last_name'],

                )
        user.set_password(validated_data['password'])
        user.save()



       return user

Now ,you can use this serializer in your views.py and create user with different user types现在,您可以在 views.py 中使用此序列化程序并创建具有不同用户类型的用户

Best regards,此致,

yes it can be definitely done please checkout this!是的,它绝对可以完成,请检查这个! https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#extending-user https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#extending-user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM