我有一个有2个用户级别的应用;超级用户和员工。超级用户将登录此应用程序并创建新用户并为用户分配超级用户或员工权限,但他们没有通过默认的Django管理员登录,他们将登录到自定义管理员。如何在表单中显示权限复选框,如何为正在创建的新用户保存它们?它只是一个普通的复选框,还是我需要覆盖才能完成这个?
这是我现在的CreateUserForm。
class CreateUserForm(forms.Form):
username = forms.EmailField(max_length=50)
email = forms.EmailField()
first_name = forms.CharField(max_length=150)
last_name = forms.CharField(max_length=150)
password1 = forms.CharField(max_length=30, widget=forms.PasswordInput(render_value=False), label='Password')
password2 = forms.CharField(max_length=30, widget=forms.PasswordInput(render_value=False), label='Password Confirmation')
address_1 = forms.CharField(max_length=50)
address_2 = forms.CharField(max_length=50)
city = forms.CharField(max_length=50)
province = forms.CharField(max_length=2)
country = forms.CharField(max_length=50)
postal_code = forms.CharField(max_length=10)
work_phone = forms.CharField(max_length=20)
mobile_phone = forms.CharField(max_length=20)
fax = forms.CharField(max_length=20)
url = forms.CharField()
comments = forms.CharField(widget=forms.Textarea)
def clean_username(self):
try:
User.objects.get(username=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError("Sorry, this username has already been taken. Please choose another.")
def clean_email(self):
try:
User.objects.get(email=self.cleaned_data['email'])
except User.DoesNotExist:
return self.cleaned_data['email']
raise forms.ValidationError("Sorry, this email has already been taken. Please choose another.")
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time.")
if ' ' in self.cleaned_data['username']:
raise forms.ValidationError("username must not contain spaces")
return self.cleaned_data
def save(self):
new_user = User.objects.create_user(
username = self.cleaned_data['username'],
email = self.cleaned_data['email']
)
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.set_password(self.cleaned_data['password'])
new_user.is_active = True
new_user.save()
new_profile = UserProfile(
# TODO:
)
由于
答案 0 :(得分:2)
如果您指的是is_staff和is_superuser的权限复选框,那么您可能最好使用具有User模型的ModelForm。这将自动为您处理一切。
class UserForm(forms.ModelForm):
class Meta:
model = User
exclude = ('last_login', 'date_joined')
每个OP更新的编辑:您可以在表单中为is_superadmin和is_staff添加2个forms.BooleanField()
字段(或者以不同的方式命名),就像您已经在保存方法,你可以做new_user.is_staff = self.cleaned_data['is_staff']
。您可以考虑使用选择字段,使用带有3个条目的下拉列表,“普通用户”,“员工用户”,“管理员用户”,然后根据用户的选择设置is_staff和is_superadmin。
还可以在User模型上使用ModelForm,并添加必要的额外字段。它取决于您的习惯,可能也可能不值得。
关于您的表单的另一个注意事项 - 当涉及到编辑现有用户时,这将无法用于使用用户名/电子邮件上的当前清理方法。但是,如果您调整那些以从查找中排除当前实例(如果设置),您将能够使用此表单来编辑现有用户(尽管它不是模型表单,您需要手动填充初始数据)。