Django save() 覆盖,最佳实践 : on model, 表单或 View ?

标签 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

但是我已经将这个覆盖放在了我的注册表单定义中,我突然想到我也可以在用户模型定义或我的 register() 中执行此操作。看法。

是否有“正确”的地方可以覆盖这些功能,例如 clean()save() ?有什么实际区别吗?

ps:我对使用 Django 的默认密码更改和注册 View 或表单不感兴趣。

最佳答案

在挖掘源代码后,我发现了 ModelForm 的 save()方法来调用模型的(模型实例)save()方法。查一下 here.

现在很明显,第一个 ModelForm 的 save()被调用并在其中(取决于提交值)模型的 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

所以问题归结于你。

您想在 Django 模型的抽象层(通过覆盖 Model 实例的 save 方法)中再上一步吗?

你真的有必要这样做吗?

抽象是 OOPS 的组成部分之一。 因此,除非出现实际需要您超越抽象层的需求,否则为什么要这样做? 显然,密码可以在 ModelForm 的 save() 中散列。方法。

此外,如果你在抽象层之上,
如果将来发生意外行为怎么办?

在我看来,为什么不把它留在 ModelForm 中呢?当我们开始使用 django 时,我们从抽象的最高层开始(我们只是调用方法,通常不知道我们继承的类中发生了什么;这就是 oops 的用途)我们只有在出现特定需求时才会超越。

希望这能以某种方式指导您。谢谢。

关于Django save() 覆盖,最佳实践 : on model, 表单或 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45851005/

相关文章:

python - 使用第二个模型的外键时未定义模型

django - 根据选定的父节点显示子节点

django - ImportError:没有名为模型的模块?

django - 检查 Django 中的请求类型

python - 什么是 Django 表单操作?

python - (Django) 将 'context' (基本信息)传递到每个页面,甚至表单?

django - 从具有多对多关系django的两个表中过滤数据

python - Django View/Template 如何知道模型的最大值

python - 在 django 模型中使用 Greatest 函数时如何获取注释中相关对象的列表

python - Django View 类: name 'self' is not defined