1

I am learning Django. Particularly I am reading about forms and I cannot understand how do they work. Lets look at example code:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

why create class with unbounded members? there is no self statement.

I looked on Django source code itself:

class Form(BaseForm):
"A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one
# to define a form using declarative syntax.
# BaseForm itself has no way of designating self.fields.
__metaclass__ = DeclarativeFieldsMetaclass

Could you explain what is the role of __metaclass__ ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ashim
  • 24,380
  • 29
  • 72
  • 96

1 Answers1

0

The form fields are descriptors, which are simply a class written to a specific protocol. The metaclass is the type of the class (since classes themselves, being objects, are instantiated from something).

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358