#django 在 admin 中使用什么方法来表示模型字段

发布于 2024-09-15 03:08:50 字数 302 浏览 4 评论 0原文

我正在尝试使用自定义 unicode 方法对 CharField 进行子类化。基本上,我希望能够对默认模型字段返回的值调用我的自定义加密方法。我尝试了以下操作,但管理员似乎正在以其他方式获取值。在我看来,这将是实现这一点的最Pythonic的方式,但也许我错了。

def PasswordCharField(models.CharField):  
    def __unicode__(self):  
        return crypt(super(PasswordCharField,self).__unicode__())

I am trying to subclass CharField with a custom unicode method. Basically, I want to be able to call my custom crypto method on the value that is returned by the default model field. I tried the following, but it seems that admin is getting the values some other way. It seems to me that this would be the most pythonic way to implement this, but perhaps I'm wrong.

def PasswordCharField(models.CharField):  
    def __unicode__(self):  
        return crypt(super(PasswordCharField,self).__unicode__())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你的占有欲 2024-09-22 03:08:50

我仍然不太确定为什么你要尝试加密输出上的字段 - 这看起来不太安全,通常的方法(由 Django 自己的密码字段采用)是对输入上的数据进行哈希处理并存储该哈希版本在数据库上。

但是,如果您想走这条路,仍然没有理由在自定义字段子类上使用 __unicode__ 。文档中没有任何内容暗示 Django 的任何部分(无论是管理员还是其他任何部分)都使用它来获取字段的值。事实上,管理员使用与其他字段完全相同的方法来获取字段的值。

自定义字段子类在文档中有完整描述,链接从内容页面。如果没有真正理解你想要做什么,很难说,但可能是 to_python 方法就是您所需要的。请记住,这会影响 Django 中所有使用的字段值。

I'm still not really sure why you're trying to encrypt a field on output - that doesn't seem very secure, the usual approach (taken by Django's own password fields) is to hash the data on entry and store that hashed version on the database.

However, if you want to go down this route, there's still no reason to use __unicode__ on a custom field subclass. There's nothing in the documentation that implies that this is what any part of Django - whether the admin or anything else - uses to get the value of a field. In fact, the admin uses exactly the same method to get the value of a field as anything else.

Custom field subclasses are fully described in the documentation, linked from the contents page. Without really understanding what you're trying to do it's hard to tell, but it could be that the to_python method is what you need. Bear in mind though that this will affect the value of the field for all uses in Django.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文