django model无法解析关键字' username'进入田野

时间:2015-01-21 21:28:51

标签: python django django-models python-3.4

我正在将我的一个Django项目从1.2升级到1.6.6。我尝试调用模型成员时遇到Cannot resolve keyword 'username' into field错误。似乎所有字段都包含了" wrap_model"不被承认。以下是wrap_model()

的代码
def wrap_model(o):
    from django.conf import settings
    FIELD_LABELS=getattr(settings,'MODEL_FIELDS',{})
    object_name=o._meta.object_name
    if FIELD_LABELS:
        for f in o._meta.local_fields:
            fl=None
            full_field_name='%s__%s' % (object_name,f.name)  
            if full_field_name in FIELD_LABELS:
                fl=FIELD_LABELS[full_field_name]
            elif f.name in FIELD_LABELS:
                fl=FIELD_LABELS[f.name]
            if fl:
                if isinstance(fl,dict):
                    for k,v in list(fl.items()):
                        setattr(f,k,v)
            else:
                f.verbose_name=fl
    return o

这是我的模型的代码

@wrap_model
class Member(models.Model):
    username = wrap(
        models.EmailField(
            _('Email:'), unique=True), size='50'
    )
    password = PasswordField(
        _('Password:'),
        max_length=50,
        help_text='(type and retype password to change)'
    )
    title = wrap(
        models.CharField(
            _('Title'),
            max_length=50,
            null=True,
            default='',
            blank=True
        ),
        size='50'
    )
    fname = wrap(
        models.CharField(
            _('First Name:'),
            max_length=50,
            null=False,
            default=''
        ),
        size='25',
        grp=1
    )
    lname = wrap(
        models.CharField(
            _('Last Name:'),
            max_length=50,
            null=False,
            default=''
        ),
        size='25',
        grp=2
    )    
    created = models.DateTimeField(
        auto_now_add=True
    )
    modified = models.DateTimeField(
        editable=False,
        blank=True,
        null=True,
        auto_now=True
    )
    accessed = models.DateTimeField(blank=True, null=True)

显然,没有包装器(例如创建,修改,访问)的字段是正常的,无法识别包含wrap_model()函数的字段。 非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

wrap()函数中有一个缩进错误。正确缩进的代码应该是这样的

def wrap(obj, widget=None, clean=None, format=None, grp=3, header='',**attrs):
    def formfield(**kwargs):
        "This makes sure the right properties get sent to form generator"
        form_class=obj.__class__.formfield(obj, **kwargs)
        if widget:
            defaults=dict(attrs=attrs)
        if obj.choices: defaults.update(choices=obj.choices)
        if format: defaults.update(format=format)
        form_class.widget=widget(**defaults)
        if hasattr(widget,'clean'):
            form_class.clean=widget.clean
        else:
            form_class.widget.attrs.update(**attrs)
        if clean:   form_class.clean=clean
        form_class.grp=grp
        form_class.header=header
        return form_class
    if widget or clean or attrs:
        obj.formfield=formfield
    return obj