我的代码中的django错误,我该怎么做

时间:2010-01-25 03:09:17

标签: python django

from django.core.management import setup_environ
from register2 import settings
setup_environ(settings)


from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _


class AuthenticationRememberMeForm ( AuthenticationForm ):

            """
            Subclass of Django ``AuthenticationForm`` which adds a remember me checkbox.

            """

            remember_me = forms.BooleanField (
                label = _( 'Remember Me' ),
                initial = False,
                required = False,
                )

print AuthenticationRememberMeForm.remember_me


Traceback (most recent call last):
  File "D:\zjm_code\register2\b.py", line 26, in <module>
    print AuthenticationRememberMeForm['remember_me']
TypeError: 'DeclarativeFieldsMetaclass' object is unsubscriptable

1 个答案:

答案 0 :(得分:1)

django forms模块使用元类来促进表单字段的声明性语法。因此,您应该将remember_me视为表单实例字段,而不是类属性。因此,访问该领域是有道理的:

form = AuthenticationRememberMeForm()
field_obj = form.fields['remember_me']

或类似地,值:

form = AuthenticationRememberMeForm(data)
if form.is_valid():
    remember_me_value = form.cleaned_data['remember_me']

显然,django.forms正在幕后做一些工作来实现这一目标。如果您想了解具体方法,请查看relevant code。如果您只想让表单工作,请尝试关注usage outlined in the docs