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
答案 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。