zjm1126
zjm1126

Reputation: 66647

django error in my code ,what does i do

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

Upvotes: 0

Views: 193

Answers (1)

ozan
ozan

Reputation: 9321

The django forms module uses a metaclass to facilitate declarative syntax for form fields. As a consequence, you should consider remember_me to be a field of your form instance, not a class attribute. So accessing the field as so makes sense:

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

or, similarly, the value:

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

Obviously, django.forms is doing a bit of work behind the scenes to make this happen. If you want to understand how, check out the relevant code. If you just want to make your forms work, try to follow the usage outlined in the docs.

Upvotes: 1

Related Questions