覆盖Django管理网站中“自定义"字段的默认显示 [英] Override default display of Custom field in Django admin site

查看:42
本文介绍了覆盖Django管理网站中“自定义"字段的默认显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义字段,定义如下:

I have a custom field which is defined as below:

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

def __init__(self, *args, **kwargs):
    self.token = kwargs.pop('token', ';')
    super(SeparatedValuesField, self).__init__(*args, **kwargs)

def to_python(self, value):
    if not value:
        return
    if isinstance(value, list):
        return value
    return value.split(self.token)

def get_db_prep_value(self, value, *args, **kwargs):
    if not value:
        return
    assert (isinstance(value, list) or isinstance(value, tuple))
    return self.token.join([unicode(s) for s in value])

def value_to_string(self, obj):
    value = self._get_val_from_obj(obj)
    print (value)
    return self.get_db_prep_value(value)

它允许我提交一个字符串列表,然后将其合并为一个长字符串以保存到数据库.

It allows me to submit a list of string, then concat it into a long string to save to database.

问题是当我使用模型的默认管理站点来更改现有对象时,未调用 value_to_string 方法.因此,如果我的数据库中有 some_str ,它将显示为 [u'some_str] (我相信这是list的默认字符串化行为).并且当我将其保存到db时,该值从字面上更改为 ['usome_str] .当我再次加载它时,它将是 [u'[u'some_str]] ,依此类推.

The problem is when I use the default admin site of the model to change an existing object, the value_to_string method is not called. So if I have in my db some_str, it will be displayed as [u'some_str] (which I believe is the default stringify behaviour of list). And when I save it to db, the value changed to ['usome_str] literally. And when I load it again, it would be [u'[u'some_str]], so on and so on.

我正在寻找一种方法来更改使用该自定义字段的字段的管理员形式的显示,因此我可以使其显示为 some_str 而不是 ['usome_str]

I am looking for a way to change the display in the admin form of the field which use that custom field, so I can make it displays as some_str instead of ['usome_str]

P/s:我正在使用Django 1.6.

P/s: I'm using django 1.6.

谢谢

推荐答案

没关系,我在这里找到了答案:

Never mind, I have found the answer here:

https://stackoverflow.com/a/11942954/3870344

基本上,我们需要创建自定义表单,然后在表单中通过调用以下代码覆盖显示值: self.initial ['some_field'] = some_encoding_method(self.instance.some_field)

Basically, we need to create the custom form, and in the form override the display value by calling: self.initial['some_field'] = some_encoding_method(self.instance.some_field)

干杯!

这篇关于覆盖Django管理网站中“自定义"字段的默认显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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