我有这个视图存储2个表单的数据。我的第二张表格的数据很好。但对于主用户表单,我只想存储用户名,密码并确认密码。创建用户时,由于某种原因,密码会存储在电子邮件字段中。
class UserForm(forms.ModelForm):
password = forms.CharField(label='Password', max_length=32, required=True, widget=forms.PasswordInput)
confirm_password = forms.CharField(label='Confirm', max_length=32, required=True, widget=forms.PasswordInput, help_text="Passwords must match!")
def clean(self):
cleaned_data = super(UserForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError(
"password and confirm_password does not match"
)
class Meta:
model = User
fields = ('username', 'password')
exclude = ('email',)
def student_register(request, user):
data = dict()
if request.method == 'POST':
form1 = UserForm(request.POST)
form2 = StudentForm(request.POST, request.FILES)
if form1.is_valid() and form2.is_valid():
cd1 = form1.cleaned_data
user.username = cd1["username"]
user.password = cd1["password"]
user.confirm_password = cd1["confirm_password"]
new_user = User.objects.create_user(user.username, password, confirm_password)
new_user.save()
cd2 = form2.cleaned_data
name = cd2['name']
surname = cd2['surname']
email = cd2['email']
phone = cd2['phone']
student_id = cd2['student_ID']
photo = cd2['photo']
Student.objects.create(user=new_user, name=name, surname=surname, email=email, phone=phone,
student_ID=student_id, photo=photo)
return redirect('index')
else:
form1 = UserForm()
form2 = StudentForm()
data['form1'] = form1
data['form2'] = form2
return render(request, "student_signup_form.html", data)
答案 0 :(得分:2)
create_user
方法的第二个参数是email
。更改代码,以便将password
作为关键字参数传递。你不需要confirm_password
就行了。
new_user = User.objects.create_user(user.username, password=password)
答案 1 :(得分:0)
摘自UserManager
的来源:
// The visible signatures of the function
// The first one takes keyof T and infers return type based on it
function getKey<T extends object, U extends keyof T> (obj: T, key: U) : T[U]
// The second one takes string and will return any
function getKey<T extends object> (obj: T, key: string) : any
// The implementation signature allows indexing, this will not be public.
function getKey(obj: { [index: string]: any }, key: string) {
if (key in obj) {
return obj[key] // Can now index T
}
}
let r = getKey({ type: "test"}, "type"); // r is infered to `test`
let r2 = getKey({ type: "test"}, "notAProp"); // r is infered to any
请注意如何使用class UserManager(BaseUserManager):
# ....
def create_user(self, username, email=None, password=None, **extra_fields):
# ....
作为第二个参数调用User.objects.create_user(...)
。从该方法的签名中可以看出,password
作为password
传递。根本不应该传递email
:
confirm_password