[英]How to save custom added field in an extended user creation form in django
I am pretty new to Django and i made a custom signup form by extending the UserCreationForms in Django. 我对Django很陌生,我通过扩展Django中的UserCreationForms制作了自定义注册表单。
class SignUpForm(UserCreationForm): #This class will be used in views of account to make sigupform
user_type = forms.CharField(required=True,widget=forms.Select(choices=usertypes))
email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput())
class Meta:
model = User
fields = ['username', 'user_type','email','password1','password2']
def save(self,commit=True):
user = super(SignUpForm, self).save(commit=False)
user.user_type = self.cleaned_data['user_type']
print('Flag3')
if commit:
user.save()
return user
It is working fine with the view : 与视图工作正常:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
print('Flag0')
if form.is_valid():
user = form.save()
if user.user_type == 'Seller' or user.user_type=='seller':
print('Flag1')
auth_login(request, user)
print('Flag2')
print(user.user_type)
group = Group.objects.get(name='Seller')
print(group.name)
print('Flag3')
user.groups.add(group)
return redirect('get_seller')
if user.user_type == 'Customer' or user.user_type=='customer':
print('Flag1')
auth_login(request, user)
print('Flag2')
print(user.user_type)
group = Group.objects.get(name='Customer')
print(group.name)
print('Flag3')
user.groups.add(group)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
I added flags because is was checking the progress of the form. 我添加了标志,因为正在检查表单的进度。
The problem that i am facing is that i want to save the custom field that made user_type
. 我面临的问题是我想保存使
user_type
成为自定义字段 。
I don't know how to save the custom field or if it is being saved how to get the value. 我不知道如何保存自定义字段,或者是否正在保存自定义字段,如何获取值。
Update:I printed the user.user_type
. 更新:我打印了
user.user_type
。 By :
def save(self,commit=True): user = super(SignUpForm, self).save(commit=False) user.user_type = self.cleaned_data['user_type'] print(user.user_type)
通过:
def save(self,commit=True): user = super(SignUpForm, self).save(commit=False) user.user_type = self.cleaned_data['user_type'] print(user.user_type)
Django's User Model does not have user_type
field. Django的用户模型没有
user_type
字段。 If you want user_type
field to be part of Django's User Model. 如果您希望
user_type
字段成为Django用户模型的一部分。 Then use AbstractUser
model and create a custom user model. 然后使用
AbstractUser
模型并创建一个自定义用户模型。
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
user_type = models.CharField(max_lenght=20, choices=usertypes)
Now use this custom model, while create a your form. 现在,在创建表单时使用此自定义模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.