在django管理员的模型字段中修改动态verbose_name [英] Modify on-the-fly verbose_name in a model field on django admin

查看:1509
本文介绍了在django管理员的模型字段中修改动态verbose_name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个示例模型使用管理员

 类作者(models.Model):
name = models.CharField(_('Text in here'),max_length = 100)

with verbose_name set as ugettext_lazy'文本在这里',但有时,根据site_id我想提出一个不同的详细名称,所以我修改了 init 这样的方式



$ _ code def __init __(self,* args,** kwargs):
super(Author,self).__ init __(* args,** kwargs)
#这里的一些逻辑
self._meta.get_field('name')。verbose_name = _('Other text')

它的作品,显示其他文字,而不是在这里的文本...除了第一次使用作者/添加视图。



¿这是正确的方法吗? ¿我如何解决第一次问题?



提前感谢

解决方案

不要修改模型的元素。在模型定义中有各种类型的元类,它们会破坏你所发现的东西。



相反,定义一个自定义表单,并在 __ init __ 方法。


I have this sample model working with the admin

class Author(models.Model):
    name = models.CharField(_('Text in here'), max_length=100)

with verbose_name set as ugettext_lazy 'Text in here', but sometimes, depending on the site_id i want to present a diferent verbose name, so I modified the init in this way

def __init__(self, *args, **kwargs):
    super(Author, self).__init__(*args, **kwargs)
    #some logic in here
    self._meta.get_field('name').verbose_name = _('Other text')

It works, displaying the 'Other text' instead the 'Text in here'... except for the very first time the author/add view is used.

¿Is it the right way to do it? ¿How can i fix the first time problem?

Thanks in advance

解决方案

Don't modify elements of the model. There's all sorts of metaclass stuff going on in model definitions that will break things, as you have discovered.

Instead, define a custom form and change the field label in the __init__ method there.

这篇关于在django管理员的模型字段中修改动态verbose_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆