Ticket #122: model_api.diff

File model_api.diff, 38.6 KB (added by mmarshall, 12 years ago)

Implements the new model api. Breaks compatibility with old models.

  • django/models/core.py

     
    11from django.core import meta, validators
    22
    33class Site(meta.Model):
    4     db_table = 'sites'
    5     fields = (
    6         meta.CharField('domain', 'domain name', maxlength=100),
    7         meta.CharField('name', 'display name', maxlength=50),
    8     )
    9     ordering = ('domain',)
     4    domain = meta.CharField('domain name', maxlength=100)
     5    name = meta.CharField('display name', maxlength=50)
    106
     7    class Meta:
     8        db_table = 'sites'
     9        ordering = ('domain',)
     10
    1111    def __repr__(self):
    1212        return self.domain
    1313
     
    1717        return get_object(pk=SITE_ID)
    1818
    1919class Package(meta.Model):
    20     db_table = 'packages'
    21     fields = (
    22         meta.CharField('label', 'label', maxlength=20, primary_key=True),
    23         meta.CharField('name', 'name', maxlength=30, unique=True),
    24     )
    25     ordering = ('name',)
     20    label = meta.CharField(maxlength=20, primary_key=True)
     21    name = meta.CharField(maxlength=30, unique=True)
    2622
     23    class Meta:
     24        db_table = 'packages'
     25        ordering = ('name',)
     26
    2727    def __repr__(self):
    2828        return self.name
    2929
    3030class ContentType(meta.Model):
    31     db_table = 'content_types'
    32     fields = (
    33         meta.CharField('name', 'name', maxlength=100),
    34         meta.ForeignKey(Package, name='package'),
    35         meta.CharField('python_module_name', 'Python module name', maxlength=50),
    36     )
    37     ordering = ('package', 'name')
    38     unique_together = (('package', 'python_module_name'),)
     31    name = meta.CharField(maxlength=100)
     32    meta.ForeignKey(Package, name='package')
     33    python_module_name = meta.CharField('Python module name', maxlength=50)
    3934
     35    class Meta:
     36        db_table = 'content_types'
     37        ordering = ('package', 'name')
     38        unique_together = (('package', 'python_module_name'),)
     39
    4040    def __repr__(self):
    4141        return "%s | %s" % (self.package, self.name)
    4242
     
    5454        return self.get_model_module().get_object(**kwargs)
    5555
    5656class Redirect(meta.Model):
    57     db_table = 'redirects'
    58     fields = (
    59         meta.ForeignKey(Site, radio_admin=meta.VERTICAL),
    60         meta.CharField('old_path', 'redirect from', maxlength=200, db_index=True,
    61             help_text="This should be an absolute path, excluding the domain name. Example: '/events/search/'."),
    62         meta.CharField('new_path', 'redirect to', maxlength=200, blank=True,
    63             help_text="This can be either an absolute path (as above) or a full URL starting with 'http://'."),
    64     )
    65     unique_together=(('site_id', 'old_path'),)
    66     ordering = ('old_path',)
    67     admin = meta.Admin(
    68         list_display = ('__repr__',),
    69         list_filter = ('site_id',),
    70         search_fields = ('old_path', 'new_path'),
    71     )
     57    meta.ForeignKey(Site, radio_admin=meta.VERTICAL)
     58    old_path = meta.CharField('redirect from', maxlength=200, db_index=True,
     59            help_text="This should be an absolute path, excluding the domain name. Example: '/events/search/'.")
     60    new_path = meta.CharField('redirect to', maxlength=200, blank=True,
     61            help_text="This can be either an absolute path (as above) or a full URL starting with 'http://'.")
    7262
     63    class Meta:
     64        db_table = 'redirects'
     65        unique_together=(('site_id', 'old_path'),)
     66        ordering = ('old_path',)
     67        admin = meta.Admin(
     68            list_display = ('__repr__',),
     69            list_filter = ('site_id',),
     70            search_fields = ('old_path', 'new_path'),
     71        )
     72
    7373    def __repr__(self):
    7474        return "%s ---> %s" % (self.old_path, self.new_path)
    7575
    7676class FlatFile(meta.Model):
    77     db_table = 'flatfiles'
    78     fields = (
    79         meta.CharField('url', 'URL', maxlength=100, validator_list=[validators.isAlphaNumericURL],
    80             help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes."),
    81         meta.CharField('title', 'title', maxlength=200),
    82         meta.TextField('content', 'content', help_text="Full HTML is allowed."),
    83         meta.BooleanField('enable_comments', 'enable comments'),
    84         meta.CharField('template_name', 'template name', maxlength=70, blank=True,
    85             help_text="Example: 'flatfiles/contact_page'. If this isn't provided, the system will use 'flatfiles/default'."),
    86         meta.BooleanField('registration_required', 'registration required',
    87             help_text="If this is checked, only logged-in users will be able to view the page."),
    88         meta.ManyToManyField(Site),
    89     )
    90     ordering = ('url',)
    91     admin = meta.Admin(
    92         fields = (
    93             (None, {'fields': ('url', 'title', 'content', 'sites')}),
    94             ('Advanced options', {'classes': 'collapse', 'fields': ('enable_comments', 'registration_required', 'template_name')}),
    95         ),
    96         list_filter = ('sites',),
    97         search_fields = ('url', 'title'),
    98     )
     77    url = meta.CharField('URL', maxlength=100, validator_list=[validators.isAlphaNumericURL],
     78            help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes.")
     79    title = meta.CharField(maxlength=200)
     80    content = meta.TextField(help_text="Full HTML is allowed.")
     81    enable_comments = meta.BooleanField()
     82    template_name = meta.CharField(maxlength=70, blank=True,
     83            help_text="Example: 'flatfiles/contact_page'. If this isn't provided, the system will use 'flatfiles/default'.")
     84    registration_required = meta.BooleanField(help_text="If this is checked, only logged-in users will be able to view the page.")
     85    meta.ManyToManyField(Site)
    9986
     87    class Meta:
     88        db_table = 'flatfiles'
     89        ordering = ('url',)
     90        admin = meta.Admin(
     91            fields = (
     92                (None, {'fields': ('url', 'title', 'content', 'sites')}),
     93                ('Advanced options', {'classes': 'collapse', 'fields': ('enable_comments', 'registration_required', 'template_name')}),
     94            ),
     95            list_filter = ('sites',),
     96            search_fields = ('url', 'title'),
     97        )
     98
    10099    def __repr__(self):
    101100        return "%s -- %s" % (self.url, self.title)
    102101
  • django/models/auth.py

     
    22from django.models import core
    33
    44class Permission(meta.Model):
    5     fields = (
    6         meta.CharField('name', 'name', maxlength=50),
    7         meta.ForeignKey(core.Package, name='package'),
    8         meta.CharField('codename', 'code name', maxlength=100),
    9     )
    10     unique_together = (('package', 'codename'),)
    11     ordering = ('package', 'codename')
     5    name = meta.CharField(maxlength=50)
     6    meta.ForeignKey(core.Package, name='package')
     7    codename = meta.CharField('code name', maxlength=100)
    128
     9    class Meta:
     10        unique_together = (('package', 'codename'),)
     11        ordering = ('package', 'codename')
     12
    1313    def __repr__(self):
    1414        return "%s | %s" % (self.package, self.name)
    1515
    1616class Group(meta.Model):
    17     fields = (
    18         meta.CharField('name', 'name', maxlength=80, unique=True),
    19         meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL),
    20     )
    21     ordering = ('name',)
    22     admin = meta.Admin(
    23         search_fields = ('name',),
    24     )
     17    name = meta.CharField(maxlength=80, unique=True)
     18    meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL)
    2519
     20    class Meta:
     21        ordering = ('name',)
     22        admin = meta.Admin(
     23            search_fields = ('name',),
     24        )
     25
    2626    def __repr__(self):
    2727        return self.name
    2828
    2929class User(meta.Model):
    30     fields = (
    31         meta.CharField('username', 'username', maxlength=30, unique=True,
    32             validator_list=[validators.isAlphaNumeric]),
    33         meta.CharField('first_name', 'first name', maxlength=30, blank=True),
    34         meta.CharField('last_name', 'last name', maxlength=30, blank=True),
    35         meta.EmailField('email', 'e-mail address', blank=True),
    36         meta.CharField('password_md5', 'password', maxlength=32, help_text="Use an MD5 hash -- not the raw password."),
    37         meta.BooleanField('is_staff', 'staff status',
    38             help_text="Designates whether the user can log into this admin site."),
    39         meta.BooleanField('is_active', 'active', default=True),
    40         meta.BooleanField('is_superuser', 'superuser status'),
    41         meta.DateTimeField('last_login', 'last login', default=meta.LazyDate()),
    42         meta.DateTimeField('date_joined', 'date joined', default=meta.LazyDate()),
    43         meta.ManyToManyField(Group, blank=True,
    44             help_text="In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."),
    45         meta.ManyToManyField(Permission, name='user_permissions', blank=True, filter_interface=meta.HORIZONTAL),
    46     )
    47     ordering = ('username',)
    48     exceptions = ('SiteProfileNotAvailable',)
    49     admin = meta.Admin(
    50         fields = (
    51             (None, {'fields': ('username', 'password_md5')}),
    52             ('Personal info', {'fields': ('first_name', 'last_name', 'email')}),
    53             ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
    54             ('Important dates', {'fields': ('last_login', 'date_joined')}),
    55             ('Groups', {'fields': ('groups',)}),
    56         ),
    57         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
    58         list_filter = ('is_staff', 'is_superuser'),
    59         search_fields = ('username', 'first_name', 'last_name', 'email'),
    60     )
     30    username = meta.CharField(maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric])
     31    first_name = meta.CharField(maxlength=30, blank=True)
     32    last_name = meta.CharField(maxlength=30, blank=True)
     33    email = meta.EmailField('e-mail address', blank=True)
     34    password_md5 = meta.CharField('password', maxlength=32, help_text="Use an MD5 hash -- not the raw password.")
     35    is_staff = meta.BooleanField('staff status', help_text="Designates whether the user can log into this admin site.")
     36    is_active = meta.BooleanField('active', default=True)
     37    is_superuser = meta.BooleanField('superuser status')
     38    last_login = meta.DateTimeField(default=meta.LazyDate())
     39    date_joined = meta.DateTimeField(default=meta.LazyDate())
     40    meta.ManyToManyField(Group, blank=True,
     41            help_text="In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")
     42    meta.ManyToManyField(Permission, name='user_permissions', blank=True, filter_interface=meta.HORIZONTAL)
    6143
     44    class Meta:
     45        ordering = ('username',)
     46        exceptions = ('SiteProfileNotAvailable',)
     47        admin = meta.Admin(
     48            fields = (
     49                (None, {'fields': ('username', 'password_md5')}),
     50                ('Personal info', {'fields': ('first_name', 'last_name', 'email')}),
     51                ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
     52                ('Important dates', {'fields': ('last_login', 'date_joined')}),
     53                ('Groups', {'fields': ('groups',)}),
     54            ),
     55            list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
     56            list_filter = ('is_staff', 'is_superuser'),
     57            search_fields = ('username', 'first_name', 'last_name', 'email'),
     58        )
     59
    6260    def __repr__(self):
    6361        return self.username
    6462
     
    173171        return ''.join([choice(allowed_chars) for i in range(length)])
    174172
    175173class Session(meta.Model):
    176     fields = (
    177         meta.ForeignKey(User),
    178         meta.CharField('session_md5', 'session MD5 hash', maxlength=32),
    179         meta.DateTimeField('start_time', 'start time', auto_now=True),
    180     )
    181     module_constants = {
    182         'TEST_COOKIE_NAME': 'testcookie',
    183         'TEST_COOKIE_VALUE': 'worked',
    184     }
     174    meta.ForeignKey(User)
     175    session_md5 = meta.CharField('session MD5 hash', maxlength=32)
     176    start_time = meta.DateTimeField(auto_now=True)
    185177
     178    class Meta:
     179        module_constants = {
     180            'TEST_COOKIE_NAME': 'testcookie',
     181            'TEST_COOKIE_VALUE': 'worked',
     182        }
     183
    186184    def __repr__(self):
    187185        return "session started at %s" % self.start_time
    188186
     
    231229        response.set_cookie(key, value, domain=cookie_domain)
    232230
    233231class Message(meta.Model):
    234     fields = (
    235         meta.AutoField('id', 'ID', primary_key=True),
    236         meta.ForeignKey(User),
    237         meta.TextField('message', 'message'),
    238     )
     232    id = meta.AutoField('ID', primary_key=True)
     233    meta.ForeignKey(User)
     234    message = meta.TextField()
    239235
    240236    def __repr__(self):
    241237        return self.message
    242238
    243239class LogEntry(meta.Model):
    244     module_name = 'log'
    245     verbose_name_plural = 'log entries'
    246     db_table = 'auth_admin_log'
    247     fields = (
    248         meta.DateTimeField('action_time', 'action time', auto_now=True),
    249         meta.ForeignKey(User),
    250         meta.ForeignKey(core.ContentType, name='content_type_id', rel_name='content_type', blank=True, null=True),
    251         meta.IntegerField('object_id', 'object ID', blank=True, null=True),
    252         meta.CharField('object_repr', 'object representation', maxlength=200),
    253         meta.PositiveSmallIntegerField('action_flag', 'action flag'),
    254         meta.TextField('change_message', 'change message', blank=True),
    255     )
    256     ordering = ('-action_time',)
    257     module_constants = {
    258         'ADDITION': 1,
    259         'CHANGE': 2,
    260         'DELETION': 3,
    261     }
     240    action_time = meta.DateTimeField(auto_now=True)
     241    meta.ForeignKey(User)
     242    meta.ForeignKey(core.ContentType, name='content_type_id', rel_name='content_type', blank=True, null=True)
     243    object_id = meta.IntegerField('object ID', blank=True, null=True)
     244    object_repr = meta.CharField('object representation', maxlength=200)
     245    action_flag = meta.PositiveSmallIntegerField()
     246    change_message = meta.TextField(blank=True)
    262247
     248    class Meta:
     249        module_name = 'log'
     250        verbose_name_plural = 'log entries'
     251        db_table = 'auth_admin_log'
     252        ordering = ('-action_time',)
     253        module_constants = {
     254            'ADDITION': 1,
     255            'CHANGE': 2,
     256            'DELETION': 3,
     257        }
     258
    263259    def __repr__(self):
    264260        return str(self.action_time)
    265261
  • django/core/meta/__init__.py

     
    55from django.core.meta.fields import *
    66from django.utils.functional import curry
    77from django.utils.text import capfirst
    8 import copy, datetime, os, re, sys, types
     8import copy, datetime, os, re, sys, types, inspect
    99
    1010# Admin stages.
    1111ADD, CHANGE, BOTH = 1, 2, 3
     
    196196        for f in self.fields:
    197197            if f.primary_key:
    198198                self.pk = f
    199                 break
     199
    200200        # If a primary_key field hasn't been specified, add an
    201201        # auto-incrementing primary-key ID field automatically.
    202202        if self.pk is None:
    203             self.fields.insert(0, AutoField('id', 'ID', primary_key=True))
     203            self.fields.insert(0, AutoField(name='id', verbose_name='ID', primary_key=True))
    204204            self.pk = self.fields[0]
    205205
    206206    def __repr__(self):
     
    372372        if not bases:
    373373            return type.__new__(cls, name, bases, attrs)
    374374
     375        # Use the attributes from the imbedded class 'Meta', if it exists.
     376        if attrs.has_key('Meta'):
     377            meta_attrs = attrs['Meta'].__dict__
     378            del attrs['Meta']
     379        else:
     380            meta_attrs = {}
     381
     382        # In order to make sure that we only add fields that were created inside of this
     383        # class, we identify our model with a tuple containing the filename, and the class name.
     384        model_ident = inspect.stack()[1][1], name
     385
     386        # Gather all of the attributes that are instances of Field.  Apply the attribute name as needed.
     387        fields = []
     388        for obj_name, obj in attrs.items():
     389            if isinstance(obj, Field):
     390                if isinstance(obj,(ForeignKey, ManyToManyField, OneToOneField)):
     391                    obj.rel.name = obj_name
     392                else:
     393                    obj.set_name(obj_name)
     394                fields.append(obj)
     395                del Field.instance_bank[model_ident][id(obj)]
     396                del attrs[obj_name]
     397
     398        # Gather the fields that were not assigned to an attribute. 
     399        for obj_id, obj in Field.instance_bank[model_ident].items():
     400            fields.append(obj)
     401            del Field.instance_bank[model_ident][obj_id]
     402
     403        # Sort the fields in the order that they were created.
     404        fields.sort(lambda x,y: x.creation_counter - y.creation_counter)
     405
    375406        # If this model is a subclass of another Model, create an Options
    376407        # object by first copying the base class's _meta and then updating it
    377408        # with the overrides from this class.
    378409        replaces_module = None
    379410        if bases[0] != Model:
    380             if not attrs.has_key('fields'):
    381                 attrs['fields'] = list(bases[0]._meta._orig_init_args['fields'][:])
    382             if attrs.has_key('ignore_fields'):
    383                 ignore_fields = attrs.pop('ignore_fields')
     411            # Inherent fields from the parent.  In order to allow for overrides, we must make
     412            # sure that we don't duplicate a name.
     413            field_names = [f.name for f in fields]
     414            for f in bases[0]._meta._orig_init_args['fields']:
     415                if not f.name in field_names:
     416                    fields.append(f)
     417            if meta_attrs.has_key('ignore_fields'):
     418                ignore_fields = meta_attrs.pop('ignore_fields')
    384419                new_fields = []
    385                 for i, f in enumerate(attrs['fields']):
     420                for f in fields:
    386421                    if f.name not in ignore_fields:
    387422                        new_fields.append(f)
    388                 attrs['fields'] = new_fields
    389             if attrs.has_key('add_fields'):
    390                 attrs['fields'].extend(attrs.pop('add_fields'))
    391             if attrs.has_key('replaces_module'):
     423                fields = new_fields
     424            if meta_attrs.has_key('replaces_module'):
    392425                # Set the replaces_module variable for now. We can't actually
    393426                # do anything with it yet, because the module hasn't yet been
    394427                # created.
    395                 replaces_module = attrs.pop('replaces_module').split('.')
     428                replaces_module = meta_attrs.pop('replaces_module').split('.')
    396429            # Pass any Options overrides to the base's Options instance, and
    397             # simultaneously remove them from attrs. When this is done, attrs
     430            # simultaneously remove them from meta_attrs. When this is done, meta_attrs
    398431            # will be a dictionary of custom methods, plus __module__.
    399             meta_overrides = {}
    400             for k, v in attrs.items():
    401                 if not callable(v) and k != '__module__':
    402                     meta_overrides[k] = attrs.pop(k)
     432            meta_overrides = {'fields':fields}
     433            for k, v in meta_attrs.items():
     434                if k != '__module__':
     435                    meta_overrides[k] = meta_attrs.pop(k)
    403436            opts = bases[0]._meta.copy(**meta_overrides)
    404437            opts.object_name = name
    405438            del meta_overrides
     
    408441                # If the module_name wasn't given, use the class name
    409442                # in lowercase, plus a trailing "s" -- a poor-man's
    410443                # pluralization.
    411                 module_name = attrs.pop('module_name', name.lower() + 's'),
     444                module_name = meta_attrs.pop('module_name', name.lower() + 's'),
    412445                # If the verbose_name wasn't given, use the class name,
    413446                # converted from InitialCaps to "lowercase with spaces".
    414                 verbose_name = attrs.pop('verbose_name',
     447                verbose_name = meta_attrs.pop('verbose_name',
    415448                    re.sub('([A-Z])', ' \\1', name).lower().strip()),
    416                 verbose_name_plural = attrs.pop('verbose_name_plural', ''),
    417                 db_table = attrs.pop('db_table', ''),
    418                 fields = attrs.pop('fields'),
    419                 ordering = attrs.pop('ordering', None),
    420                 unique_together = attrs.pop('unique_together', None),
    421                 admin = attrs.pop('admin', None),
    422                 has_related_links = attrs.pop('has_related_links', False),
    423                 where_constraints = attrs.pop('where_constraints', None),
     449                verbose_name_plural = meta_attrs.pop('verbose_name_plural', ''),
     450                db_table = meta_attrs.pop('db_table', ''),
     451                fields = fields,
     452                ordering = meta_attrs.pop('ordering', None),
     453                unique_together = meta_attrs.pop('unique_together', None),
     454                admin = meta_attrs.pop('admin', None),
     455                has_related_links = meta_attrs.pop('has_related_links', False),
     456                where_constraints = meta_attrs.pop('where_constraints', None),
    424457                object_name = name,
    425                 app_label = attrs.pop('app_label', None),
    426                 exceptions = attrs.pop('exceptions', None),
    427                 permissions = attrs.pop('permissions', None),
    428                 get_latest_by = attrs.pop('get_latest_by', None),
    429                 order_with_respect_to = attrs.pop('order_with_respect_to', None),
    430                 module_constants = attrs.pop('module_constants', None),
     458                app_label = meta_attrs.pop('app_label', None),
     459                exceptions = meta_attrs.pop('exceptions', None),
     460                permissions = meta_attrs.pop('permissions', None),
     461                get_latest_by = meta_attrs.pop('get_latest_by', None),
     462                order_with_respect_to = meta_attrs.pop('order_with_respect_to', None),
     463                module_constants = meta_attrs.pop('module_constants', None),
    431464            )
    432465
    433466        # Dynamically create the module that will contain this class and its
     
    450483        for k, v in attrs.items():
    451484            if k in ('__module__', '__init__', '_overrides', '__doc__'):
    452485                continue # Skip the important stuff.
     486            # Make sure that this is a function, and give a helpful error otherwise.
     487            if not callable(v):
     488                raise ValueError("All attributes of a Model must be either a Field instance or a function.  %s is a %s." % (k, type(v)))
    453489            # Give the function a function attribute "custom" to designate that
    454490            # it's a custom function/method.
    455491            v.custom = True
  • django/core/meta/fields.py

     
    33from django.core.exceptions import ObjectDoesNotExist
    44from django.utils.functional import curry
    55from django.utils.text import capfirst
    6 import datetime, os
     6import datetime, os, inspect
    77
    88# Random entropy string used by "default" param.
    99NOT_PROVIDED = 'oijpwojefiojpanv'
     
    4646
    4747class Field(object):
    4848
     49    # Stores field instances.
     50    instance_bank = {}
     51
     52    # Will be increased each time a Field object is instanced.  Used to
     53    # retain the order of fields.
     54    creation_counter = 0
     55
    4956    # Designates whether empty strings fundamentally are allowed at the
    5057    # database level.
    5158    empty_strings_allowed = True
    5259
    53     def __init__(self, name, verbose_name=None, primary_key=False,
     60    def __init__(self, verbose_name=None, name=None, primary_key=False,
    5461        maxlength=None, unique=False, blank=False, null=False, db_index=None,
    5562        core=False, rel=None, default=NOT_PROVIDED, editable=True,
    5663        prepopulate_from=None, unique_for_date=None, unique_for_month=None,
    5764        unique_for_year=None, validator_list=None, choices=None, radio_admin=None,
    5865        help_text=''):
    5966        self.name = name
    60         self.verbose_name = verbose_name or name.replace('_', ' ')
     67        self.verbose_name = verbose_name or name and name.replace('_', ' ')
    6168        self.primary_key = primary_key
    6269        self.maxlength, self.unique = maxlength, unique
    6370        self.blank, self.null = blank, null
     
    8289        else:
    8390            self.db_index = db_index
    8491
     92        # Save the field instance, so that it can be retrieved later (in case it wasn't assigned to anything.)
     93        # We will identify the class by a tuple containing the filename it was defined in, and it's own name.
     94        # This is to make sure that a model only gets fields that were created inside of it's class.
     95        stack = inspect.stack()
     96        try:
     97            # Walk up the stack until we find a name other than '__init__'.
     98            while stack[0][3] == "__init__":
     99                stack.pop(0)
     100            model_ident = stack[0][1],stack[0][3]
     101        finally:
     102            del stack
     103        if not Field.instance_bank.has_key(model_ident):
     104            Field.instance_bank[model_ident] = {}
     105        Field.instance_bank[model_ident][id(self)] = self
     106
     107        # Increase the creation counter, and save our local copy.
     108        self.creation_counter = Field.creation_counter
     109        Field.creation_counter += 1
     110
     111    def set_name(self, name):
     112        """
     113        Sets the name, as well as the verbose_name if it is None.  (Should be called when the
     114        name is not availible at creation time.)
     115        """
     116        self.name = name
     117        self.verbose_name = self.verbose_name or self.name.replace('_',' ')
     118
    85119    def pre_save(self, obj, value, add):
    86120        """
    87121        Hook for altering the object obj based on the value of this field and
     
    267301
    268302class DateField(Field):
    269303    empty_strings_allowed = False
    270     def __init__(self, name, verbose_name=None, auto_now=False, auto_now_add=False, **kwargs):
     304    def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
    271305        self.auto_now, self.auto_now_add = auto_now, auto_now_add
    272306        if auto_now or auto_now_add:
    273307            kwargs['editable'] = False
    274         Field.__init__(self, name, verbose_name, **kwargs)
     308        Field.__init__(self, verbose_name, name, **kwargs)
    275309
    276310    def get_db_prep_lookup(self, lookup_type, value):
    277311        if lookup_type == 'range':
     
    323357        return [formfields.EmailField]
    324358
    325359class FileField(Field):
    326     def __init__(self, name, verbose_name=None, upload_to='', **kwargs):
     360    def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs):
    327361        self.upload_to = upload_to
    328         Field.__init__(self, name, verbose_name, **kwargs)
     362        Field.__init__(self, verbose_name, name, **kwargs)
    329363
    330364    def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):
    331365        field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel)
     
    388422
    389423class FloatField(Field):
    390424    empty_strings_allowed = False
    391     def __init__(self, name, verbose_name=None, max_digits=None, decimal_places=None, **kwargs):
     425    def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs):
    392426        self.max_digits, self.decimal_places = max_digits, decimal_places
    393         Field.__init__(self, name, verbose_name, **kwargs)
     427        Field.__init__(self, verbose_name, name, **kwargs)
    394428
    395429    def get_manipulator_field_objs(self):
    396430        return [curry(formfields.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
    397431
    398432class ImageField(FileField):
    399     def __init__(self, name, verbose_name=None, width_field=None, height_field=None, **kwargs):
     433    def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
    400434        self.width_field, self.height_field = width_field, height_field
    401         FileField.__init__(self, name, verbose_name, **kwargs)
     435        FileField.__init__(self, verbose_name, name, **kwargs)
    402436
    403437    def get_manipulator_field_objs(self):
    404438        return [formfields.ImageUploadField, formfields.HiddenField]
     
    470504
    471505class TimeField(Field):
    472506    empty_strings_allowed = False
    473     def __init__(self, name, verbose_name=None, auto_now=False, auto_now_add=False, **kwargs):
     507    def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
    474508        self.auto_now, self.auto_now_add  = auto_now, auto_now_add
    475509        if auto_now or auto_now_add:
    476510            kwargs['editable'] = False
    477         Field.__init__(self, name, verbose_name, **kwargs)
     511        Field.__init__(self, verbose_name, name, **kwargs)
    478512
    479513    def get_db_prep_lookup(self, lookup_type, value):
    480514        if lookup_type == 'range':
     
    497531        return [formfields.TimeField]
    498532
    499533class URLField(Field):
    500     def __init__(self, name, verbose_name=None, verify_exists=True, **kwargs):
     534    def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
    501535        if verify_exists:
    502536            kwargs.setdefault('validator_list', []).append(validators.isExistingURL)
    503         Field.__init__(self, name, verbose_name, **kwargs)
     537        Field.__init__(self, verbose_name, name, **kwargs)
    504538
    505539    def get_manipulator_field_objs(self):
    506540        return [formfields.URLField]
     
    510544        return [formfields.USStateField]
    511545
    512546class XMLField(Field):
    513     def __init__(self, name, verbose_name=None, schema_path=None, **kwargs):
     547    def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs):
    514548        self.schema_path = schema_path
    515         Field.__init__(self, name, verbose_name, **kwargs)
     549        Field.__init__(self, verbose_name, name, **kwargs)
    516550
    517551    def get_manipulator_field_objs(self):
    518552        return [curry(formfields.XMLLargeTextField, schema_path=self.schema_path)]
  • tests/testapp/models/repr.py

     
    1111from django.core import meta
    1212
    1313class Article(meta.Model):
    14     fields = (
    15         meta.CharField('headline', maxlength=100),
    16         meta.DateTimeField('pub_date'),
    17     )
     14    headline = meta.CharField(maxlength=100)
     15    pub_date = meta.DateTimeField()
    1816
    1917    def __repr__(self):
    2018        return self.headline
  • tests/testapp/models/ordering.py

     
    1616from django.core import meta
    1717
    1818class Article(meta.Model):
    19     fields = (
    20         meta.CharField('headline', maxlength=100),
    21         meta.DateTimeField('pub_date'),
    22     )
    23     ordering = ('-pub_date', 'headline')
     19    headline = meta.CharField(maxlength=100)
     20    pub_date = meta.DateTimeField()
    2421
     22    class Meta:
     23        ordering = ('-pub_date', 'headline')
     24
    2525    def __repr__(self):
    2626        return self.headline
    2727
  • tests/testapp/models/lookup.py

     
    77from django.core import meta
    88
    99class Article(meta.Model):
    10     fields = (
    11         meta.CharField('headline', maxlength=100),
    12         meta.DateTimeField('pub_date'),
    13     )
    14     ordering = ('-pub_date', 'headline')
     10    headline = meta.CharField(maxlength=100)
     11    pub_date = meta.DateTimeField()
    1512
     13    class Meta:
     14        ordering = ('-pub_date', 'headline')
     15
    1616    def __repr__(self):
    1717        return self.headline
    1818
  • tests/testapp/models/many_to_many.py

     
    1010from django.core import meta
    1111
    1212class Publication(meta.Model):
    13     fields = (
    14         meta.CharField('title', maxlength=30),
    15     )
     13    title = meta.CharField(maxlength=30)
    1614
    1715    def __repr__(self):
    1816        return self.title
    1917
    2018class Article(meta.Model):
    21     fields = (
    22         meta.CharField('headline', maxlength=100),
    23         meta.ManyToManyField(Publication),
    24     )
     19    headline = meta.CharField(maxlength=100)
     20    meta.ManyToManyField(Publication)
    2521
    2622    def __repr__(self):
    2723        return self.headline
  • tests/testapp/models/get_latest.py

     
    1111from django.core import meta
    1212
    1313class Article(meta.Model):
    14     fields = (
    15         meta.CharField('headline', maxlength=100),
    16         meta.DateTimeField('pub_date'),
    17     )
    18     get_latest_by = 'pub_date'
     14    headline = meta.CharField(maxlength=100)
     15    pub_date = meta.DateTimeField()
    1916
     17    class Meta:
     18        get_latest_by = 'pub_date'
     19
    2020    def __repr__(self):
    2121        return self.headline
    2222
  • tests/testapp/models/custom_methods.py

     
    2323from django.core import meta
    2424
    2525class Article(meta.Model):
    26     fields = (
    27         meta.CharField('headline', maxlength=100),
    28         meta.DateField('pub_date'),
    29     )
     26    headline = meta.CharField(maxlength=100)
     27    pub_date = meta.DateField()
    3028
    3129    def __repr__(self):
    3230        return self.headline
  • tests/testapp/models/basic.py

     
    77from django.core import meta
    88
    99class Article(meta.Model):
    10     fields = (
    11         meta.CharField('headline', maxlength=100, default='Default headline'),
    12         meta.DateTimeField('pub_date'),
    13     )
     10    headline = meta.CharField(maxlength=100, default='Default headline')
     11    pub_date = meta.DateTimeField()
    1412
     13
    1514API_TESTS = """
    1615# No articles are in the system yet.
    1716>>> articles.get_list()
  • tests/testapp/models/m2o_recursive.py

     
    1515from django.core import meta
    1616
    1717class Category(meta.Model):
    18     module_name = 'categories'
    19     fields = (
    20         meta.CharField('name', maxlength=20),
    21         meta.ForeignKey('self', null=True,
    22             rel_name='parent', related_name='child'),
    23     )
     18    name = meta.CharField(maxlength=20)
     19    parent = meta.ForeignKey('self', null=True, related_name='child')
     20   
     21    class Meta:
     22       module_name = 'categories'
    2423
    2524    def __repr__(self):
    2625        return self.name
  • tests/testapp/models/one_to_one.py

     
    99from django.core import meta
    1010
    1111class Place(meta.Model):
    12     fields = (
    13         meta.CharField('name', maxlength=50),
    14         meta.CharField('address', maxlength=80),
    15     )
     12    name = meta.CharField(maxlength=50)
     13    address = meta.CharField(maxlength=80)
    1614
    1715    def __repr__(self):
    1816        return "%s the place" % self.name
    1917
    2018class Restaurant(meta.Model):
    21     fields = (
    22         meta.OneToOneField(Place),
    23         meta.BooleanField('serves_hot_dogs'),
    24         meta.BooleanField('serves_pizza'),
    25     )
     19    meta.OneToOneField(Place)
     20    serves_hot_dogs = meta.BooleanField()
     21    serves_pizza = meta.BooleanField()
    2622
    2723    def __repr__(self):
    2824        return "%s the restaurant" % self.get_place().name
  • tests/testapp/models/m2o_recursive2.py

     
    1414from django.core import meta
    1515
    1616class Person(meta.Model):
    17     fields = (
    18         meta.CharField('full_name', maxlength=20),
    19         meta.ForeignKey('self', null=True, rel_name='mother',
    20             related_name='mothers_child'),
    21         meta.ForeignKey('self', null=True, rel_name='father',
    22             related_name='fathers_child'),
    23     )
     17    full_name = meta.CharField(maxlength=20)
     18    mother = meta.ForeignKey('self', null=True, related_name='mothers_child')
     19    father = meta.ForeignKey('self', null=True, related_name='fathers_child')
    2420
    2521    def __repr__(self):
    2622        return self.full_name
  • tests/testapp/models/many_to_one.py

     
    77from django.core import meta
    88
    99class Reporter(meta.Model):
    10     fields = (
    11         meta.CharField('first_name', maxlength=30),
    12         meta.CharField('last_name', maxlength=30),
    13     )
     10    first_name = meta.CharField(maxlength=30)
     11    last_name = meta.CharField(maxlength=30)
    1412
    1513    def __repr__(self):
    1614        return "%s %s" % (self.first_name, self.last_name)
    1715
    1816class Article(meta.Model):
    19     fields = (
    20         meta.CharField('headline', maxlength=100),
    21         meta.DateField('pub_date'),
    22         meta.ForeignKey(Reporter),
    23     )
     17    headline = meta.CharField(maxlength=100)
     18    pub_date = meta.DateField()
     19    meta.ForeignKey(Reporter)
    2420
    2521    def __repr__(self):
    2622        return self.headline
  • tests/testapp/models/m2m_intermediary.py

     
    1313from django.core import meta
    1414
    1515class Reporter(meta.Model):
    16     fields = (
    17         meta.CharField('first_name', maxlength=30),
    18         meta.CharField('last_name', maxlength=30),
    19     )
     16    first_name = meta.CharField(maxlength=30)
     17    last_name = meta.CharField(maxlength=30)
    2018
    2119    def __repr__(self):
    2220        return "%s %s" % (self.first_name, self.last_name)
    2321
    2422class Article(meta.Model):
    25     fields = (
    26         meta.CharField('headline', maxlength=100),
    27         meta.DateField('pub_date'),
    28     )
     23    headline = meta.CharField(maxlength=100)
     24    pub_date = meta.DateField()
    2925
    3026    def __repr__(self):
    3127        return self.headline
    3228
    3329class Writer(meta.Model):
    34     fields = (
    35         meta.ForeignKey(Reporter),
    36         meta.ForeignKey(Article),
    37         meta.CharField('position', maxlength=100),
    38     )
     30    meta.ForeignKey(Reporter)
     31    meta.ForeignKey(Article)
     32    position = meta.CharField(maxlength=100)
    3933
    4034    def __repr__(self):
    4135        return '%r (%s)' % (self.get_reporter(), self.position)
Back to Top