fla*_*ino 3 django django-models django-forms django-views
我已经通过覆盖这样的save()函数成功地散列了我的自定义用户模型的密码:
def save(self, commit = True):
user = super(RegisterForm, self).save(commit = False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Run Code Online (Sandbox Code Playgroud)
但我已将此覆盖置于我的注册表单定义中,我突然想到我也可以在用户模型定义中或在我的register()视图中执行此操作。
是否有“正确”的地方可以覆盖这些功能,例如clean()或save()?有什么实际区别吗?
ps:我对使用 Django 的默认密码更改和注册视图或表单不感兴趣。
在挖掘源代码后,我发现 ModelForm 的save()方法正在调用 Model 的(模型实例)save()方法。在这里检查。
现在很明显,第一个 ModelFormsave()被调用,并且在其中(取决于提交值)模型save()被调用。
另外值得注意的是,在代码中:
def save(self, commit = True):
user = super(RegisterForm, self).save(commit = False)
user.set_password(self.cleaned_data["password1"])
#When you're hashing and setting the password to the user variable,
#this user variable is a Model Object but is not saved in the database yet.
if commit:
user.save()
#Now in the above line you're ultimately calling the save method of Model instance.
return user
Run Code Online (Sandbox Code Playgroud)
所以问题归结于你。
您想在 Django 模型的抽象层(通过覆盖 Model 实例的 save 方法)中再上一步吗?
你真的有必要这样做吗?
抽象是 OOPS 的组成部分之一。因此,除非出现实际需要您超越抽象层的需求,否则为什么要这样做?显然,密码可以在 ModelForm 的save()方法中散列。
此外,如果您在抽象层上层,如果将来发生意外行为怎么办?
在我看来,为什么不把它留在 ModelForm 中呢?当我们开始使用 django 时,我们从抽象的最高层开始(我们只是调用方法,通常不知道我们正在继承的类中发生了什么;这就是 oops 的用途),并且只有在特定需要时才开始出现。
希望这能以某种方式指导您。谢谢。
| 归档时间: |
|
| 查看次数: |
3823 次 |
| 最近记录: |