如何在 Django 中创建两种类型的用户?
Posted
技术标签:
【中文标题】如何在 Django 中创建两种类型的用户?【英文标题】:How to create 2 types of users in Django? 【发布时间】:2021-12-02 12:22:34 【问题描述】:我想在我的 Django 项目中创建两种类型的用户,即客户和公司。两个用户在注册过程中具有不同的属性。 这是我的用户 odel.py 文件 -
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, is_staff=False, is_superuser=False, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', is_staff)
extra_fields.setdefault('is_superuser', is_superuser)
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
"""User model."""
username = None
last_name = None
first_name = None
name = models.CharField(max_length=100)
email = models.EmailField(_('email address'), unique=True)
contact = models.CharField(max_length=100)
USERNAME_FIELD = 'id'
REQUIRED_FIELDS = ['contact']
objects = UserManager()
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
我想为这两个用户创建不同的注册页面。我几乎到处搜索,但找不到合适的解决方案。有人可以帮忙吗?
【问题讨论】:
【参考方案1】:您必须使用用户的外键创建两个单独的模型。并制作单独的表单,添加您想要的任何额外字段。
【讨论】:
我创建了 2 个用户并使用 OneToOne 字段链接他们,但我只是在做后端工作并创建一个 API。我不想使用表格。你能告诉我如何更改views.py 文件本身吗?假设我有 2 个模型 - 客户和公司【参考方案2】:这是类似的情况:
models.py:
class User(AbstractUser):
first_name = None
last_name = None
phoneNumberRegex = RegexValidator(
regex=r'^\+?1?\d8,15$', message='Enter valid phone')
username = models.CharField(
_('phone'),
validators=[phoneNumberRegex],
max_length=16,
unique=True,
error_messages=
'unique': _('A user with that phone already exists.'),
,
help_text=_('Required. 16 characters or fewer.'),
)
full_name = models.CharField(
_('full name'),
max_length=70,
blank=True,
null=True,
error_messages=
'max_length': _('Full name max length is 70 characters.'),
)
...
class Worker(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
error_messages=
'blank': _('Worker must have a user related to!'),
'null': _('Worker must have a user related to!'),
)
is_manager = models.BooleanField(
_('manager status'),
default=False,
help_text=_(
'Designates whether the user can log into this manager site.'),
)
...
serializers.py:
from allauth.account.adapter import get_adapter
class CustomRegisterSerializer(serializers.ModelSerializer):
password1 = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'full_name', 'password1', 'password2',
'is_worker')
def get_cleaned_data(self):
return
'username': self.validated_data.get('username'),
'full_name': full_name if full_name != "" else None,
'password1': self.validated_data.get('password1'),
'is_worker': self.validated_data.get('is_worker', False),
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
for attr, value in self.cleaned_data.items():
setattr(user, attr, value)
adapter.save_user(request, user, self)
if self.cleaned_data.get(is_worker):
Worker.objects.create(user=user, is_manager=False) # for example
return user
【讨论】:
以上是关于如何在 Django 中创建两种类型的用户?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 TypeScript 中强制两种类型不兼容? [复制]
如何在 HTML 表单中创建两组单选按钮以及 A 组中的更改何时会在 B 组中更改?
如何在Django中创建从Abstract User继承的多个用户配置文件?
如何结合突变在 django-graphql-jwt 中创建或登录用户?