gpt4 book ai didi

python - Django 表单在创建用户时不保存密码

转载 作者:行者123 更新时间:2023-12-02 06:59:28 25 4
gpt4 key购买 nike

我为我的 django 应用程序制作了一个自定义表单,允许用户自行注册该网站。

这是我的 django 应用程序的表单:

class TeacherRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
school = forms.CharField(required = True)
subject = forms.CharField(required = True)
head_of_subject = forms.BooleanField(required = False)
identification_code = forms.CharField(required = True)

def __init__(self, *args, **kwargs):
super(TeacherRegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].help_text = ''
self.fields['password2'].help_text = ''


class Meta:
model = User

fields = (
'username',
'first_name',
'last_name',
'email',
'school',
'identification_code',
'subject',
'head_of_subject',
'password1',
'password2'
)

def save(self, request):
form = TeacherRegistrationForm(request.POST)
user = User.objects.create(first_name=self.cleaned_data['first_name'],
last_name=self.cleaned_data['last_name'],
email=self.cleaned_data['email'],
username=self.cleaned_data['username'],
password=self.cleaned_data['password1']
)

teacher_profile = TeacherProfile.objects.create(user=user,
school=self.cleaned_data['school'],
subject=self.cleaned_data['subject'],
head_of_subject=self.cleaned_data['head_of_subject'],
)


return user, teacher_profile

这是 View 的相关部分:

if request.method == 'POST':

form = TeacherRegistrationForm(request.POST)

entered_school_name = form['school'].value()
entered_school_id = form['identification_code'].value()

actual_school_id = SchoolProfile.objects.get(school_name__exact = entered_school_name).identification_code

if form.is_valid()and (entered_school_id == actual_school_id):

user, teacher_profile = form.save(request)

return render(request, 'accounts/home.html')
else:
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)

当我按提交时,将创建用户,但没有为用户设置密码

最佳答案

不需要触及属于 User 的任何字段,事实上您不应该这样做,而应该让 UserCreationForm 处理它,因为其中对密码有一些特殊处理。

在表单类保存方法中这样做:

def save(self):
user = super(TeacherRegistrationForm, self).save()
teacher_profile = TeacherProfile(
user=user,
school=self.cleaned_data['school'],
subject=self.cleaned_data['subject'],
head_of_subject=self.cleaned_data['head_of_subject']
)
teacher_profile.save()
return user, teacher_profile

这将产生 TeacherRegistrationForm,它是 UserCreationForm 的子类,而 UserCreationForm 又是 ModelForm 的子类。它将执行 ModelForm 应该执行的操作,即在您创建时将其自身保存到数据库(用户表)中。调用它的保存方法。这一切都为你完成了。然后,您只需处理添加到其他模型表单中的额外字段。

请注意,我使用了模型 save() 方法,而不是使用 create(),在本例中它完成了相同的事情..但您可以稍后修改表单代码允许同一表单编辑现有模型而不仅仅是创建新模型。如果您也希望我对此进行解释,请告诉我。

关于python - Django 表单在创建用户时不保存密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44527549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com