我正在尝试为公司,管理员和员工构建一个自定义注册表单。当我创建超级用户时,我的“帐户类型”是“管理员”,但当我尝试注册为公司时,我的“帐户类型”为空。
我可以在我的模型类中设置默认值,但我希望将来添加更多不同类型的“帐户类型”。
我也不想让字段下拉
models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager,
AbstractBaseUser
)
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, account_type=None, password=None):
if not email:
raise ValueError('Email address is required')
user = self.model(
email = self.normalize_email(email),
first_name = first_name,
last_name = last_name,
account_type = account_type
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, first_name, last_name, password):
user = self.create_user(
email,
first_name = first_name,
last_name = last_name,
account_type = 'staff',
password = password
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password):
user = self.create_user(
email,
first_name = first_name,
last_name = last_name,
account_type = 'admin',
password = password
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.CharField(max_length=255, unique=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
account_type = models.CharField(max_length=32)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return self.email
def get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_admin(self):
return self.admin
@property
def is_staff(self):
return self.staff
@property
def is_active(self):
return self.active
views.py
from django.shortcuts import render
from accounts.forms import RegisterForm
# Create your views here.
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data.get('password')
user = form.save(commit=False)
user.account_type = 'company'
user.set_password(password)
user.save()
return HttpResponse('account created')
else:
form = RegisterForm();
context = {
'form' : form
}
return render(request, 'accounts/form.html', context)