我正在Django(4.0+)项目上工作,在那里我使用默认的User
模型进行登录,并为signup
定制表单,并且我有一个布尔字段:blogger
在注册表单中,如果用户检查此,我必须设置is_staff
为真,否则它将作为正常用户。
我有:
Registration Form:
class UserRegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=101)
last_name = forms.CharField(max_length=101)
email = forms.EmailField()
blogger = forms.BooleanField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'blogger', 'is_staff']
views.py:
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
print(form['blogger'])
if form['blogger']:
form['is_staff'] = True
form.save()
messages.success(request, f'Your account has been created. You can log in now!')
return redirect('login')
else:
print(form.errors)
else:
form = UserRegistrationForm()
context = {'form': form}
return render(request, 'users/signup.html', context)
给出如下错误:
TypeError: 'UserRegistrationForm' object does not support item assignment
我怎么才能做到呢?
您需要首先保存user对象,而不是将其提交到数据库。
最好使用form.cleaned_data
来检查提交的数据
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
if form.cleaned_data['blogger']:
user.is_staff = True
user.save()
您可以在.save(…)
中处理这个问题method[Django-doc],如果将blogger
设置为True
,则可以先将is_staff
的清理数据设置为True
:
class UserRegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=101)
last_name = forms.CharField(max_length=101)
email = forms.EmailField()
blogger = forms.BooleanField()
def save(self, *args, **kwargs):
self.cleaned_data['is_staff'] |= self.cleaned_data['blogger']
return super().save(*args, **kwargs)
class Meta:
model = User
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'blogger',
'is_staff',
]
然后我们可以像使用其他形式一样使用这个形式:
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(
request, f'Your account has been created. You can log in now!'
)
return redirect('login')
else:
form = UserRegistrationForm()
context = {'form': form}
return render(request, 'users/signup.html', context)
由于您的视图遵循样板格式,因此使用基于类的视图可能更容易:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView
class RegisterView(SuccessMessageMixin, CreateView):
form_class = UserRegistrationForm
success_url = reverse_lazy('login')
template_name = 'users/signup.html'
success_message = 'Your account has been created. You can log in now!'