Django

Code

Changeset 6417

Show
Ignore:
Timestamp:
09/24/07 19:08:38 (1 year ago)
Author:
jkocherhans
Message:

newforms-admin: Merged to [6416]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/newforms-admin

    • Property svnmerge-integrated changed from /django/trunk:1-4345,4350-4357,4359-4365,4371-4372,4374-4377,4380-4386,4388,4390-4391,4400-4402,4404-4408,4410,4412-4419,4426-4427,4430-4432,4434,4441,4443-4444,4446-4447,4450,4452-4453,4455-4458,4476,4503,4546,4564-4569,4580-4586,4617,4630,4641-6370 to /django/trunk:1-4345,4350-4357,4359-4365,4371-4372,4374-4377,4380-4386,4388,4390-4391,4400-4402,4404-4408,4410,4412-4419,4426-4427,4430-4432,4434,4441,4443-4444,4446-4447,4450,4452-4453,4455-4458,4476,4503,4546,4564-4569,4580-4586,4617,4630,4641-6390,6392-6416
  • django/branches/newforms-admin/AUTHORS

    r6372 r6417  
    5050    Fabrice Aneche <akh@nobugware.com> 
    5151    ant9000@netwise.it 
     52    Florian Apolloner  
    5253    David Ascher <http://ascher.ca/> 
    5354    david@kazserve.org 
     
    245246    phil.h.smith@gmail.com 
    246247    Gustavo Picon 
    247     pigletto 
    248248    Luke Plant <http://lukeplant.me.uk/> 
    249249    plisk 
     
    282282    Leo Soto <leo.soto@gmail.com> 
    283283    Wiliam Alves de Souza <wiliamsouza83@gmail.com> 
     284    Don Spaulding <donspauldingii@gmail.com> 
    284285    Bjørn Stabell <bjorn@exoweb.net> 
    285286    Georgi Stanojevski <glisha@gmail.com> 
     
    326327    Gary Wilson <gary.wilson@gmail.com> 
    327328    Jakub Wiśniowski <restless.being@gmail.com> 
     329    Maciej Wiśniowski <pigletto@gmail.com> 
    328330    wojtek 
    329331    ye7cakf02@sneakemail.com 
  • django/branches/newforms-admin/django/contrib/admin/templatetags/admin_modify.py

    r6073 r6417  
    4141 
    4242    def __init__(self, bound_field_var): 
    43         self.bound_field_var = bound_field_var 
     43        self.bound_field_var = template.Variable(bound_field_var) 
    4444 
    4545    def get_nodelist(cls, klass): 
     
    6565 
    6666    def render(self, context): 
    67         bound_field = template.resolve_variable(self.bound_field_var, context) 
     67        bound_field = self.bound_field_var.resolve(context) 
    6868 
    6969        context.push() 
  • django/branches/newforms-admin/django/contrib/auth/backends.py

    r4265 r6417  
     1from django.db import connection 
    12from django.contrib.auth.models import User 
    23 
     
    1516            return None 
    1617 
     18    def get_group_permissions(self, user_obj): 
     19        "Returns a list of permission strings that this user has through his/her groups." 
     20        if not hasattr(user_obj, '_group_perm_cache'): 
     21            cursor = connection.cursor() 
     22            # The SQL below works out to the following, after DB quoting: 
     23            # cursor.execute(""" 
     24            #     SELECT ct."app_label", p."codename" 
     25            #     FROM "auth_permission" p, "auth_group_permissions" gp, "auth_user_groups" ug, "django_content_type" ct 
     26            #     WHERE p."id" = gp."permission_id" 
     27            #         AND gp."group_id" = ug."group_id" 
     28            #         AND ct."id" = p."content_type_id" 
     29            #         AND ug."user_id" = %s, [self.id]) 
     30            qn = connection.ops.quote_name 
     31            sql = """ 
     32                SELECT ct.%s, p.%s 
     33                FROM %s p, %s gp, %s ug, %s ct 
     34                WHERE p.%s = gp.%s 
     35                    AND gp.%s = ug.%s 
     36                    AND ct.%s = p.%s 
     37                    AND ug.%s = %%s""" % ( 
     38                qn('app_label'), qn('codename'), 
     39                qn('auth_permission'), qn('auth_group_permissions'), 
     40                qn('auth_user_groups'), qn('django_content_type'), 
     41                qn('id'), qn('permission_id'), 
     42                qn('group_id'), qn('group_id'), 
     43                qn('id'), qn('content_type_id'), 
     44                qn('user_id'),) 
     45            cursor.execute(sql, [user_obj.id]) 
     46            user_obj._group_perm_cache = set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()]) 
     47        return user_obj._group_perm_cache 
     48     
     49    def get_all_permissions(self, user_obj): 
     50        if not hasattr(user_obj, '_perm_cache'): 
     51            user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()]) 
     52            user_obj._perm_cache.update(self.get_group_permissions(user_obj)) 
     53        return user_obj._perm_cache 
     54 
     55    def has_perm(self, user_obj, perm): 
     56        return perm in self.get_all_permissions(user_obj) 
     57 
     58    def has_module_perms(self, user_obj, app_label): 
     59        return bool(len([p for p in self.get_all_permissions(user_obj) if p[:p.index('.')] == app_label])) 
     60 
    1761    def get_user(self, user_id): 
    1862        try: 
  • django/branches/newforms-admin/django/contrib/auth/models.py

    r6342 r6417  
     1from django.contrib import auth 
    12from django.core import validators 
    23from django.core.exceptions import ImproperlyConfigured 
    3 from django.db import connection, models 
     4from django.db import models 
    45from django.db.models.manager import EmptyManager 
    56from django.contrib.contenttypes.models import ContentType 
     
    196197 
    197198    def get_group_permissions(self): 
    198         "Returns a list of permission strings that this user has through his/her groups." 
    199         if not hasattr(self, '_group_perm_cache'): 
    200             cursor = connection.cursor() 
    201             # The SQL below works out to the following, after DB quoting: 
    202             # cursor.execute(""" 
    203             #     SELECT ct."app_label", p."codename" 
    204             #     FROM "auth_permission" p, "auth_group_permissions" gp, "auth_user_groups" ug, "django_content_type" ct 
    205             #     WHERE p."id" = gp."permission_id" 
    206             #         AND gp."group_id" = ug."group_id" 
    207             #         AND ct."id" = p."content_type_id" 
    208             #         AND ug."user_id" = %s, [self.id]) 
    209             qn = connection.ops.quote_name 
    210             sql = """ 
    211                 SELECT ct.%s, p.%s 
    212                 FROM %s p, %s gp, %s ug, %s ct 
    213                 WHERE p.%s = gp.%s 
    214                     AND gp.%s = ug.%s 
    215                     AND ct.%s = p.%s 
    216                     AND ug.%s = %%s""" % ( 
    217                 qn('app_label'), qn('codename'), 
    218                 qn('auth_permission'), qn('auth_group_permissions'), 
    219                 qn('auth_user_groups'), qn('django_content_type'), 
    220                 qn('id'), qn('permission_id'), 
    221                 qn('group_id'), qn('group_id'), 
    222                 qn('id'), qn('content_type_id'), 
    223                 qn('user_id'),) 
    224             cursor.execute(sql, [self.id]) 
    225             self._group_perm_cache = set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()]) 
    226         return self._group_perm_cache 
     199        """ 
     200        Returns a list of permission strings that this user has through 
     201        his/her groups. This method queries all available auth backends. 
     202        """ 
     203        permissions = set() 
     204        for backend in auth.get_backends(): 
     205            if hasattr(backend, "get_group_permissions"): 
     206                permissions.update(backend.get_group_permissions(self)) 
     207        return permissions 
    227208 
    228209    def get_all_permissions(self): 
    229         if not hasattr(self, '_perm_cache'): 
    230             self._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in self.user_permissions.select_related()]) 
    231             self._perm_cache.update(self.get_group_permissions()) 
    232         return self._perm_cache 
     210        permissions = set() 
     211        for backend in auth.get_backends(): 
     212            if hasattr(backend, "get_all_permissions"): 
     213                permissions.update(backend.get_all_permissions(self)) 
     214        return permissions  
    233215 
    234216    def has_perm(self, perm): 
    235         "Returns True if the user has the specified permission." 
     217        """ 
     218        Returns True if the user has the specified permission. This method 
     219        queries all available auth backends, but returns immediately if any 
     220        backend returns True. Thus, a user who has permission from a single 
     221        auth backend is assumed to have permission in general. 
     222        """ 
     223        # Inactive users have no permissions. 
    236224        if not self.is_active: 
    237225            return False 
     226         
     227        # Superusers have all permissions. 
    238228        if self.is_superuser: 
    239229            return True 
    240         return perm in self.get_all_permissions() 
     230             
     231        # Otherwise we need to check the backends. 
     232        for backend in auth.get_backends(): 
     233            if hasattr(backend, "has_perm"): 
     234                if backend.has_perm(self, perm): 
     235                    return True 
     236        return False 
    241237 
    242238    def has_perms(self, perm_list): 
    243         "Returns True if the user has each of the specified permissions.
     239        """Returns True if the user has each of the specified permissions.""
    244240        for perm in perm_list: 
    245241            if not self.has_perm(perm): 
     
    248244 
    249245    def has_module_perms(self, app_label): 
    250         "Returns True if the user has any permissions in the given app label." 
     246        """ 
     247        Returns True if the user has any permissions in the given app 
     248        label. Uses pretty much the same logic as has_perm, above. 
     249        """ 
    251250        if not self.is_active: 
    252251            return False 
     252 
    253253        if self.is_superuser: 
    254254            return True 
    255         return bool(len([p for p in self.get_all_permissions() if p[:p.index('.')] == app_label])) 
     255 
     256        for backend in auth.get_backends(): 
     257            if hasattr(backend, "has_module_perms"): 
     258                if backend.has_module_perms(self, app_label): 
     259                    return True 
     260        return False 
    256261 
    257262    def get_and_delete_messages(self): 
     
    286291class Message(models.Model): 
    287292    """ 
    288     The message system is a lightweight way to queue messages for given users. A message is associated with a User instance (so it is only applicable for registered users). There's no concept of expiration or timestamps. Messages are created by the Django admin after successful actions. For example, "The poll Foo was created successfully." is a message. 
     293    The message system is a lightweight way to queue messages for given 
     294    users. A message is associated with a User instance (so it is only 
     295    applicable for registered users). There's no concept of expiration or 
     296    timestamps. Messages are created by the Django admin after successful 
     297    actions. For example, "The poll Foo was created successfully." is a 
     298    message. 
    289299    """ 
    290300    user = models.ForeignKey(User) 
  • django/branches/newforms-admin/django/contrib/comments/templatetags/comments.py

    r5918 r6417  
    2020        is_public=True): 
    2121        self.content_type = content_type 
     22        if obj_id_lookup_var is not None: 
     23            obj_id_lookup_var = template.Variable(obj_id_lookup_var) 
    2224        self.obj_id_lookup_var, self.obj_id, self.free = obj_id_lookup_var, obj_id, free 
    2325        self.photos_optional, self.photos_required = photos_optional, photos_required 
     
    3335        if self.obj_id_lookup_var is not None: 
    3436            try: 
    35                 self.obj_id = template.resolve_variable(self.obj_id_lookup_var, context) 
     37                self.obj_id = self.obj_id_lookup_var.resolve(context) 
    3638            except template.VariableDoesNotExist: 
    3739                return '' 
     
    7678    def __init__(self, package, module, context_var_name, obj_id, var_name, free): 
    7779        self.package, self.module = package, module 
     80        if context_var_name is not None: 
     81            context_var_name = template.Variable(context_var_name) 
    7882        self.context_var_name, self.obj_id = context_var_name, obj_id 
    7983        self.var_name, self.free = var_name, free 
     
    8387        manager = self.free and FreeComment.objects or Comment.objects 
    8488        if self.context_var_name is not None: 
    85             self.obj_id = template.resolve_variable(self.context_var_name, context) 
     89            self.obj_id = self.context_var_name.resolve(context) 
    8690        comment_count = manager.filter(object_id__exact=self.obj_id, 
    8791            content_type__app_label__exact=self.package, 
     
    9397    def __init__(self, package, module, context_var_name, obj_id, var_name, free, ordering, extra_kwargs=None): 
    9498        self.package, self.module = package, module 
     99        if context_var_name is not None: 
     100            context_var_name = template.Variable(context_var_name) 
    95101        self.context_var_name, self.obj_id = context_var_name, obj_id 
    96102        self.var_name, self.free = var_name, free 
     
    103109        if self.context_var_name is not None: 
    104110            try: 
    105                 self.obj_id = template.resolve_variable(self.context_var_name, context) 
     111                self.obj_id = self.context_var_name.resolve(context) 
    106112            except template.VariableDoesNotExist: 
    107113                return '' 
  • django/branches/newforms-admin/django/contrib/sessions/backends/base.py

    r6371 r6417  
    1717    Base class for all Session classes. 
    1818    """ 
    19  
    2019    TEST_COOKIE_NAME = 'testcookie' 
    2120    TEST_COOKIE_VALUE = 'worked' 
     
    6059    def delete_test_cookie(self): 
    6160        del self[self.TEST_COOKIE_NAME] 
    62          
     61 
    6362    def encode(self, session_dict): 
    6463        "Returns the given session dictionary pickled and encoded as a string." 
     
    7877        except: 
    7978            return {} 
    80          
     79 
    8180    def _get_new_session_key(self): 
    8281        "Returns session key that isn't being used." 
    8382        # The random module is seeded when this Apache child is created. 
    8483        # Use settings.SECRET_KEY as added salt. 
     84        try: 
     85            pid = os.getpid() 
     86        except AttributeError: 
     87            # No getpid() in Jython, for example 
     88            pid = 1 
    8589        while 1: 
    86             session_key = md5.new("%s%s%s%s" % (random.randint(0, sys.maxint - 1),  
    87                                   os.getpid(), time.time(), settings.SECRET_KEY)).hexdigest() 
     90            session_key = md5.new("%s%s%s%s" % (random.randint(0, sys.maxint - 1), 
     91                                  pid, time.time(), settings.SECRET_KEY)).hexdigest() 
    8892            if not self.exists(session_key): 
    8993                break 
    9094        return session_key 
    91          
     95 
    9296    def _get_session_key(self): 
    9397        if self._session_key: 
     
    96100            self._session_key = self._get_new_session_key() 
    97101            return self._session_key 
    98      
     102 
    99103    def _set_session_key(self, session_key): 
    100104        self._session_key = session_key 
    101      
     105 
    102106    session_key = property(_get_session_key, _set_session_key) 
    103107 
     
    115119 
    116120    _session = property(_get_session) 
    117      
     121 
    118122    # Methods that child classes must implement. 
    119      
     123 
    120124    def exists(self, session_key): 
    121125        """ 
     
    141145        """ 
    142146        raise NotImplementedError 
    143          
  • django/branches/newforms-admin/django/core/management/base.py

    r6342 r6417  
    1010    pass 
    1111 
     12def handle_default_options(options): 
     13    """ 
     14    Include any default options that all commands should accept 
     15    here so that ManagementUtility can handle them before searching 
     16    for user commands. 
     17    """ 
     18    if options.settings: 
     19        os.environ['DJANGO_SETTINGS_MODULE'] = options.settings 
     20    if options.pythonpath: 
     21        sys.path.insert(0, options.pythonpath) 
     22                 
    1223class BaseCommand(object): 
    1324    # Metadata about this command. 
     
    5667        parser = self.create_parser(argv[0], argv[1]) 
    5768        options, args = parser.parse_args(argv[2:]) 
    58         if options.settings: 
    59             os.environ['DJANGO_SETTINGS_MODULE'] = options.settings 
    60         if options.pythonpath: 
    61             sys.path.insert(0, options.pythonpath) 
     69        handle_default_options(options) 
    6270        self.execute(*args, **options.__dict__) 
    6371 
  • django/branches/newforms-admin/django/core/management/__init__.py

    r6095 r6417  
    11import django 
     2from django.core.management.base import BaseCommand, CommandError, handle_default_options  
    23from optparse import OptionParser 
    34import os 
    45import sys 
     6from imp import find_module 
    57 
    68# For backwards compatibility: get_version() used to be in this module. 
    79get_version = django.get_version 
    810 
    9 def load_command_class(name): 
    10     """ 
    11     Given a command name, returns the Command class instance. Raises 
    12     ImportError if it doesn't exist. 
    13     """ 
    14     # Let the ImportError propogate. 
    15     return getattr(__import__('django.core.management.commands.%s' % name, {}, {}, ['Command']), 'Command')() 
     11# A cache of loaded commands, so that call_command  
     12# doesn't have to reload every time it is called 
     13_commands = None 
     14 
     15def find_commands(management_dir): 
     16    """ 
     17    Given a path to a management directory, return a list of all the command names  
     18    that are available. Returns an empty list if no commands are defined. 
     19    """ 
     20    command_dir = os.path.join(management_dir,'commands') 
     21    try: 
     22        return [f[:-3] for f in os.listdir(command_dir) if not f.startswith('_') and f.endswith('.py')] 
     23    except OSError: 
     24        return [] 
     25 
     26def find_management_module(app_name): 
     27    """ 
     28    Determine the path to the management module for the application named, 
     29    without acutally importing the application or the management module. 
     30 
     31    Raises ImportError if the management module cannot be found for any reason. 
     32    """ 
     33    parts = app_name.split('.') 
     34    parts.append('management') 
     35    parts.reverse() 
     36    path = None 
     37    while parts: 
     38        part = parts.pop() 
     39        f,path,descr = find_module(part, path and [path] or None) 
     40    return path 
     41     
     42def load_command_class(app_name, name): 
     43    """ 
     44    Given a command name and an application name, returns the Command  
     45    class instance. All errors raised by the importation process 
     46    (ImportError, AttributeError) are allowed to propagate. 
     47    """ 
     48    return getattr(__import__('%s.management.commands.%s' % (app_name, name),  
     49                   {}, {}, ['Command']), 'Command')() 
     50 
     51def get_commands(load_user_commands=True, project_directory=None): 
     52    """ 
     53    Returns a dictionary of commands against the application in which 
     54    those commands can be found. This works by looking for a  
     55    management.commands package in django.core, and in each installed  
     56    application -- if a commands package exists, all commands in that 
     57    package are registered. 
     58 
     59    Core commands are always included; user-defined commands will also 
     60    be included if ``load_user_commands`` is True. If a project directory 
     61    is provided, the startproject command will be disabled, and the 
     62    startapp command will be modified to use that directory. 
     63 
     64    The dictionary is in the format {command_name: app_name}. Key-value 
     65    pairs from this dictionary can then be used in calls to  
     66    load_command_class(app_name, command_name) 
     67     
     68    If a specific version of a command must be loaded (e.g., with the 
     69    startapp command), the instantiated module can be placed in the 
     70    dictionary in place of the application name. 
     71     
     72    The dictionary is cached on the first call, and reused on subsequent 
     73    calls. 
     74    """ 
     75    global _commands 
     76    if _commands is None: 
     77        _commands = dict([(name, 'django.core')  
     78                          for name in find_commands(__path__[0])]) 
     79        if load_user_commands: 
     80            # Get commands from all installed apps 
     81            from django.conf import settings 
     82            for app_name in settings.INSTALLED_APPS: 
     83                try: 
     84                    path = find_management_module(app_name) 
     85                    _commands.update(dict([(name, app_name)  
     86                                           for name in find_commands(path)])) 
     87                except ImportError: 
     88                    pass # No management module - ignore this app 
     89                     
     90        if project_directory: 
     91            # Remove the "startproject" command from self.commands, because 
     92            # that's a django-admin.py command, not a manage.py command. 
     93            del _commands['startproject'] 
     94 
     95            # Override the startapp command so that it always uses the 
     96            # project_directory, not the current working directory  
     97            # (which is default). 
     98            from django.core.management.commands.startapp import ProjectCommand 
     99            _commands['startapp'] = ProjectCommand(project_directory) 
     100 
     101    return _commands 
    16102 
    17103def call_command(name, *args, **options): 
     
    26112        call_command('sqlall', 'myapp') 
    27113    """ 
    28     klass = load_command_class(name) 
     114    try: 
     115        app_name = get_commands()[name] 
     116        if isinstance(app_name, BaseCommand):  
     117            # If the command is already loaded, use it directly. 
     118            klass = app_name 
     119        else: 
     120            klass = load_command_class(app_name, name) 
     121    except KeyError: 
     122        raise CommandError, "Unknown command: %r" % name 
    29123    return klass.execute(*args, **options) 
     124     
     125class LaxOptionParser(OptionParser):  
     126    """ 
     127    An option parser that doesn't raise any errors on unknown options. 
     128     
     129    This is needed because the --settings and --pythonpath options affect 
     130    the commands (and thus the options) that are available to the user.  
     131    """ 
     132    def error(self, msg):  
     133            pass 
    30134 
    31135class ManagementUtility(object): 
     
    39143        self.argv = argv or sys.argv[:] 
    40144        self.prog_name = os.path.basename(self.argv[0]) 
    41         self.commands = self.default_commands() 
    42  
    43     def default_commands(self): 
    44         """ 
    45         Returns a dictionary of instances of all available Command classes. 
    46  
    47         This works by looking for and loading all Python modules in the 
    48         django.core.management.commands package. 
    49  
    50         The dictionary is in the format {name: command_instance}. 
    51         """ 
    52         command_dir = os.path.join(__path__[0], 'commands') 
    53         names = [f[:-3] for f in os.listdir(command_dir) if not f.startswith('_') and f.endswith('.py')] 
    54         return dict([(name, load_command_class(name)) for name in names]) 
    55  
     145        self.project_directory = None 
     146        self.user_commands = False 
     147         
    56148    def main_help_text(self): 
    57149        """ 
     
    62154        usage.append("Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name) 
    63155        usage.append('Available subcommands:') 
    64         commands = self.commands.keys() 
     156        commands = get_commands(self.user_commands, self.project_directory).keys() 
    65157        commands.sort() 
    66158        for cmd in commands: 
     
    75167        """ 
    76168        try: 
    77             return self.commands[subcommand] 
     169            app_name = get_commands(self.user_commands, self.project_directory)[subcommand] 
     170            if isinstance(app_name, BaseCommand):  
     171                # If the command is already loaded, use it directly. 
     172                klass = app_name 
     173            else: 
     174                klass = load_command_class(app_name, subcommand) 
    78175        except KeyError: 
    79176            sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % (subcommand, self.prog_name)) 
    80177            sys.exit(1) 
    81  
     178        return klass 
     179         
    82180    def execute(self): 
    83181        """ 
     
    85183        being run, creates a parser appropriate to that command, and runs it. 
    86184        """ 
     185        # Preprocess options to extract --settings and --pythonpath. These options 
     186        # could affect the commands that are available, so they must be processed 
     187        # early 
     188        parser = LaxOptionParser(version=get_version(),  
     189                                 option_list=BaseCommand.option_list)  
     190        try: 
     191            options, args = parser.parse_args(self.argv)  
     192            handle_default_options(options) 
     193        except:  
     194