我知道django内置了一个User
模型,下面的代码可以正常工作,并且可以将用户正确地保存到数据库中,我只是不明白为什么为什么:< / p>
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserCreationForm
def index(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponse('Saved')
else:
form = UserCreationForm()
return render(request, 'core/index.html', {'form':form})
第form = UserCreationForm(request.POST)
行在说什么? (request.POST)
是提交表单的内容吗? user = form.save()
如何将用户保存到数据库?我以为django必须将该变量命名为user
才能将其识别为User
对象,但事实并非如此,因为我将语句更改为test = form.save()
并且仍然将User
保存到我的数据库中。
答案 0 :(得分:0)
这是Django文档:
[docs]class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
您可以看到“保存”方法,它使用带有super的用户模型。结果UserCreationForm使用用户模型,可以保存在用户数据库中
答案 1 :(得分:0)
我这是您应该阅读UserCreationForm代码以使您脑海中清楚的事情。