commit 05d735adf2b89d9db0579b0f2c5c92ee042d9c66 Author: Serge Dewailly Date: Thu May 23 15:43:25 2013 +0200 * Appication ovpnmanager + version django-1 en production sur Marie diff --git a/Django-1.0/AUTHORS b/Django-1.0/AUTHORS new file mode 100644 index 0000000..71179a0 --- /dev/null +++ b/Django-1.0/AUTHORS @@ -0,0 +1,437 @@ +Django was originally created in late 2003 at World Online, the Web division +of the Lawrence Journal-World newspaper in Lawrence, Kansas. + +The PRIMARY AUTHORS are (and/or have been): + + * Adrian Holovaty + * Simon Willison + * Jacob Kaplan-Moss + * Wilson Miner + * Malcolm Tredinnick + * Georg "Hugo" Bauer + * Luke Plant + * Russell Keith-Magee + * Robert Wittams + * Gary Wilson + * Brian Rosner + +More information on the main contributors to Django can be found in +docs/internals/committers.txt. + +And here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS -- +people who have submitted patches, reported bugs, added translations, helped +answer newbie questions, and generally made Django that much better: + + ajs + alang@bright-green.com + Marty Alchin + Ahmad Alhashemi + Daniel Alves Barbosa de Oliveira Vaz + AgarFu + Dagur Páll Ammendrup + Collin Anderson + Jeff Anderson + Andreas + andy@jadedplanet.net + Fabrice Aneche + ant9000@netwise.it + Florian Apolloner + arien + David Ascher + atlithorn + Jökull Sólberg Auðunsson + Arthur + av0000@mail.ru + David Avsajanishvili + Mike Axiak + Niran Babalola + Morten Bagai + Mikaël Barbero + Jiri Barton + Ned Batchelder + batiste@dosimple.ch + Batman + Shannon -jj Behrens + Esdras Beleza + Chris Bennett + James Bennett + Julian Bez + Arvis Bickovskis + Paul Bissex + Simon Blanchard + David Blewett + Matt Boersma + boobsd@gmail.com + Andrew Brehaut + brut.alll@gmail.com + btoll@bestweb.net + Jonathan Buchanan + Keith Bussell + Chris Cahoon + Juan Manuel Caicedo + Trevor Caira + Ricardo Javier Cárdenes Medina + Jeremy Carbaugh + Graham Carlyle + Antonio Cavedoni + C8E + cedric@terramater.net + Chris Chamberlin + Amit Chakradeo + ChaosKCW + Sengtha Chay + ivan.chelubeev@gmail.com + Bryan Chow + Antonis Christofides + Michal Chruszcz + Can Burak Çilingir + Ian Clelland + Russell Cloran + colin@owlfish.com + crankycoder@gmail.com + Paul Collier + Pete Crosier + Matt Croydon + Leah Culver + flavio.curella@gmail.com + Jure Cuhalev + John D'Agostino + dackze+django@gmail.com + Mihai Damian + David Danier + Dirk Datzert + Jonathan Daugherty (cygnus) + dave@thebarproject.com + david@kazserve.org + Jason Davies (Esaj) + Richard Davies + Alex Dedul + deric@monowerks.com + Max Derkachev + Rajesh Dhawan + Sander Dijkhuis + Jordan Dimov + dne@mayonnaise.net + dready + Maximillian Dornseif + Jeremy Dunck + Andrew Durdin + dusk@woofle.net + Andy Dustman + Clint Ecker + Nick Efford + eibaan@gmail.com + enlight + Enrico + A. Murat Eren + Ludvig Ericson + eriks@win.tue.nl + Dirk Eschler + Marc Fargas + Szilveszter Farkas + favo@exoweb.net + fdr + Dmitri Fedortchenko + Jonathan Feignberg + Liang Feng + Bill Fenner + Stefane Fermgier + Afonso Fernández Nogueira + J. Pablo Fernandez + Maciej Fijalkowski + Matthew Flanagan + Eric Floehr + Eric Florenzano + Vincent Foley + Rudolph Froger + Jorge Gajon + gandalf@owca.info + Marc Garcia + Alex Gaynor + Andy Gayton + Baishampayan Ghose + Dimitris Glezos + glin@seznam.cz + martin.glueck@gmail.com + Artyom Gnilov + Ben Godfrey + GomoX + Guilherme Mesquita Gondim + Mario Gonzalez + pradeep.gowda@gmail.com + Collin Grady + Simon Greenhill + Owen Griffiths + Espen Grindhaug + Thomas Güttler + Horst Gutmann + dAniel hAhler + hambaloney + Brian Harring + Brant Harris + Hawkeye + Joe Heck + Joel Heenan + Mikko Hellsing + Sebastian Hillig + hipertracker@gmail.com + Deryck Hodge + Brett Hoerner + Eric Holscher + Ian Holsman + Kieran Holland + Sung-Jin Hong + Richard House + Robert Rock Howard + John Huddleston + Rob Hudson + Jason Huggins + Hyun Mi Ae + Ibon + Tom Insam + Baurzhan Ismagulov + james_027@yahoo.com + jcrasta@gmail.com + jdetaeye + Zak Johnson + Nis Jørgensen + Michael Josephson + jpellerin@gmail.com + Julia Elman + junzhang.jn@gmail.com + Grigory Fateyev + Antti Kaihola + Bahadır Kandemir + Karderio + Nagy Károly + Erik Karulf + Ben Dean Kawamura + Ian G. Kelly + Thomas Kerpe + Ossama M. Khayat + Ben Khoo + Garth Kidd + kilian + Sune Kirkeby + Bastian Kleineidam + Cameron Knight (ckknight) + Nena Kojadin + Igor Kolar + Gasper Koren + Martin Kosír + Meir Kriheli + Bruce Kroeze + krzysiek.pawlik@silvermedia.pl + Joseph Kocherhans + konrad@gwu.edu + knox + David Krauth + kurtiss@meetro.com + Panos Laganakos + lakin.wecker@gmail.com + Nick Lane + Stuart Langridge + Paul Lanier + Nicola Larosa + Finn Gruwier Larsen + Lau Bech Lauritzen + Rune Rønde Laursen + Eugene Lazutkin + lcordier@point45.com + Jeong-Min Lee + Jannis Leidel + Christopher Lenz + lerouxb@gmail.com + Piotr Lewandowski + Waylan Limberg + limodou + Philip Lindborg + Simon Litchfield + Daniel Lindsley + Trey Long + msaelices + Matt McClanahan + Frantisek Malina + Martin Maney + masonsimon+django@gmail.com + Manuzhai + Petr Marhoun + Petar Marić + Nuno Mariz + Marijn Vriens + mark@junklight.com + Orestis Markou + Takashi Matsuo + Yasushi Masuda + mattycakes@gmail.com + Jason McBrayer + Kevin McConnell + mccutchen@gmail.com + Christian Metts + michael.mcewan@gmail.com + michal@plovarna.cz + Slawek Mikula + mitakummaa@gmail.com + mmarshall + Andreas Mock + Reza Mohammadi + Aljosa Mohorovic + Ramiro Morales + Eric Moritz + mrmachine + Robin Munn + James Murty + msundstr + Robert Myers + Nebojša Dorđević + Doug Napoleone + Gopal Narayanan + Fraser Nevett + Sam Newman + Afonso Fernández Nogueira + Neal Norwitz + Todd O'Bryan + oggie rob + oggy + Jay Parlar + Carlos Eduardo de Paula + pavithran s + Barry Pederson + permonik@mesias.brnonet.cz + peter@mymart.com + pgross@thoughtworks.com + phaedo + Julien Phalip + phil@produxion.net + phil.h.smith@gmail.com + Gustavo Picon + Michael Placentra II + Luke Plant + plisk + Mihai Preda + Daniel Poelzleithner + polpak@yahoo.com + Matthias Pronk + Jyrki Pulliainen + Thejaswi Puthraya + Johann Queuniet + Jan Rademaker + Michael Radziej + Laurent Rahuel + Luciano Ramalho + Amit Ramon + Philippe Raoult + Massimiliano Ravelli + Brian Ray + remco@diji.biz + David Reynolds + rhettg@gmail.com + ricardojbarrios@gmail.com + Mike Richardson + Matt Riggott + Henrique Romano + Armin Ronacher + Daniel Roseman + Brian Rosner + Rozza + Oliver Rutherfurd + ryankanno + Manuel Saelices + Ivan Sagalaev (Maniac) + Vinay Sajip + David Schein + scott@staplefish.com + Ilya Semenov + serbaut@gmail.com + John Shaffer + Pete Shinners + Leo Shklovskii + jason.sidabras@gmail.com + Brenton Simpson + Jozko Skrablin + Ben Slavin + sloonz + SmileyChris + Warren Smith + smurf@smurf.noris.de + Vsevolod Solovyov + sopel + Leo Soto + Wiliam Alves de Souza + Don Spaulding + Bjørn Stabell + Georgi Stanojevski + starrynight + Vasiliy Stavenko + Thomas Steinacher + Johan C. Stöver + nowell strite + Thomas Stromberg + Sundance + SuperJared + Radek Švarz + Swaroop C H + Aaron Swartz + Ville Säävuori + Mart Sõmermaa + Christian Tanzer + Tyler Tarabula + Tyson Tate + Frank Tegtmeyer + Terry Huang + thebjorn + Zach Thompson + Michael Thornhill + Deepak Thukral + tibimicu@gmx.net + tobias@neuyork.de + Tom Tobin + Joe Topjian + torne-django@wolfpuppy.org.uk + Karen Tracey + Jeff Triplett + tstromberg@google.com + Makoto Tsuyuki + tt@gurgle.no + David Tulig + Amit Upadhyay + Geert Vanderkelen + I.S. van Oostveen + viestards.lists@gmail.com + George Vilches + Vlado + Milton Waddams + Chris Wagner + wam-djangobug@wamber.net + Wang Chun + Filip Wasilewski + Dan Watson + Joel Watts + Chris Wesseling + James Wheare + Mike Wiacek + charly.wilhelm@gmail.com + Rachel Willmer + Gary Wilson + Jakub Wilk + Jakub Wiśniowski + Maciej Wiśniowski + wojtek + Jason Yan + ye7cakf02@sneakemail.com + ymasuda@ethercube.com + Jarek Zgoda + Cheng Zhang + +A big THANK YOU goes to: + + Rob Curley and Ralph Gage for letting us open-source Django. + + Frank Wiles for making excellent arguments for open-sourcing, and for + his sage sysadmin advice. + + Ian Bicking for convincing Adrian to ditch code generation. + + Mark Pilgrim for diveintopython.org. + + Guido van Rossum for creating Python. diff --git a/Django-1.0/INSTALL b/Django-1.0/INSTALL new file mode 100644 index 0000000..23e24c0 --- /dev/null +++ b/Django-1.0/INSTALL @@ -0,0 +1,22 @@ +Thanks for downloading Django. + +To install it, make sure you have Python 2.3 or greater installed. Then run +this command from the command prompt: + + python setup.py install + +Note this requires a working Internet connection if you don't already have the +Python utility "setuptools" installed. + +AS AN ALTERNATIVE, you can just copy the entire "django" directory to Python's +site-packages directory, which is located wherever your Python installation +lives. Some places you might check are: + + /usr/lib/python2.4/site-packages (Unix, Python 2.4) + /usr/lib/python2.3/site-packages (Unix, Python 2.3) + C:\\PYTHON\site-packages (Windows) + +This second solution does not require a working Internet connection; it +bypasses "setuptools" entirely. + +For more detailed instructions, see docs/install.txt. diff --git a/Django-1.0/LICENSE b/Django-1.0/LICENSE new file mode 100644 index 0000000..d0c3f28 --- /dev/null +++ b/Django-1.0/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Django Software Foundation and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of Django nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Django-1.0/MANIFEST.in b/Django-1.0/MANIFEST.in new file mode 100644 index 0000000..57ce117 --- /dev/null +++ b/Django-1.0/MANIFEST.in @@ -0,0 +1,16 @@ +include README +include AUTHORS +include INSTALL +include LICENSE +include MANIFEST.in +recursive-include docs * +recursive-include scripts * +recursive-include examples * +recursive-include extras * +recursive-include django/conf/locale * +recursive-include django/contrib/admin/templates * +recursive-include django/contrib/admin/media * +recursive-include django/contrib/admindocs/templates * +recursive-include django/contrib/comments/templates * +recursive-include django/contrib/databrowse/templates * +recursive-include django/contrib/sitemaps/templates * diff --git a/Django-1.0/README b/Django-1.0/README new file mode 100644 index 0000000..720b6c7 --- /dev/null +++ b/Django-1.0/README @@ -0,0 +1,38 @@ +Django is a high-level Python Web framework that encourages rapid development +and clean, pragmatic design. + +All documentation is in the "docs" directory and online at +http://docs.djangoproject.com/en/dev/. If you're just getting started, here's +how we recommend you read the docs: + + * First, read docs/intro/install.txt for instructions on installing Django. + + * Next, work through the tutorials in order (docs/intro/tutorial01.txt, + docs/intro/tutorial02.txt, etc.). + + * If you want to set up an actual deployment server, read + docs/howto/deployment/modpython.txt for instructions on running Django + under mod_python. + + * You'll probably want to read through the topical guides (in docs/topics) + next; from there you can jump to the HOWTOs (in docs/howto) for specific + problems, and check out the reference (docs/ref) for gory details. + +Docs are updated rigorously. If you find any problems in the docs, or think they +should be clarified in any way, please take 30 seconds to fill out a ticket +here: + +http://code.djangoproject.com/newticket + +To get more help: + + * Join the #django channel on irc.freenode.net. Lots of helpful people + hang out there. Read the archives at http://oebfare.com/logger/django/. + + * Join the django-users mailing list, or read the archives, at + http://groups.google.com/group/django-users. + +To contribute to Django: + + * Check out http://www.djangoproject.com/community/ for information + about getting involved. diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/__init__.py new file mode 100644 index 0000000..9e9e6f2 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/__init__.py @@ -0,0 +1,9 @@ +VERSION = (1, 0, 'final') + +def get_version(): + "Returns the version as a human-format string." + v = '.'.join([str(i) for i in VERSION[:-1]]) + if VERSION[-1]: + from django.utils.version import get_svn_revision + v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision()) + return v diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/compile-messages.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/compile-messages.py new file mode 100644 index 0000000..0deaf6a --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/compile-messages.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +if __name__ == "__main__": + import sys + name = sys.argv[0] + args = ' '.join(sys.argv[1:]) + print >> sys.stderr, "%s has been moved into django-admin.py" % name + print >> sys.stderr, 'Please run "django-admin.py compilemessages %s" instead.'% args + print >> sys.stderr + sys.exit(1) + diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/daily_cleanup.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/daily_cleanup.py new file mode 100644 index 0000000..c9f4cb9 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/daily_cleanup.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python + +""" +Daily cleanup job. + +Can be run as a cronjob to clean out old data from the database (only expired +sessions at the moment). +""" + +from django.core import management + +if __name__ == "__main__": + management.call_command('cleanup') diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/django-admin.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/django-admin.py new file mode 100644 index 0000000..f518cdc --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/django-admin.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +from django.core import management + +if __name__ == "__main__": + management.execute_from_command_line() diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/make-messages.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/make-messages.py new file mode 100644 index 0000000..1c84416 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/make-messages.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +if __name__ == "__main__": + import sys + name = sys.argv[0] + args = ' '.join(sys.argv[1:]) + print >> sys.stderr, "%s has been moved into django-admin.py" % name + print >> sys.stderr, 'Please run "django-admin.py makemessages %s" instead.'% args + print >> sys.stderr + sys.exit(1) + diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/profiling/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/profiling/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/profiling/gather_profile_stats.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/profiling/gather_profile_stats.py new file mode 100644 index 0000000..0fd2b7f --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/profiling/gather_profile_stats.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +""" +gather_profile_stats.py /path/to/dir/of/profiles + +Note that the aggregated profiles must be read with pstats.Stats, not +hotshot.stats (the formats are incompatible) +""" + +from hotshot import stats +import pstats +import sys, os + +def gather_stats(p): + profiles = {} + for f in os.listdir(p): + if f.endswith('.agg.prof'): + path = f[:-9] + prof = pstats.Stats(os.path.join(p, f)) + elif f.endswith('.prof'): + bits = f.split('.') + path = ".".join(bits[:-3]) + prof = stats.load(os.path.join(p, f)) + else: + continue + print "Processing %s" % f + if path in profiles: + profiles[path].add(prof) + else: + profiles[path] = prof + os.unlink(os.path.join(p, f)) + for (path, prof) in profiles.items(): + prof.dump_stats(os.path.join(p, "%s.agg.prof" % path)) + +if __name__ == '__main__': + gather_stats(sys.argv[1]) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/unique-messages.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/unique-messages.py new file mode 100644 index 0000000..c601a9e --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/bin/unique-messages.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +import os +import sys + +def unique_messages(): + basedir = None + + if os.path.isdir(os.path.join('conf', 'locale')): + basedir = os.path.abspath(os.path.join('conf', 'locale')) + elif os.path.isdir('locale'): + basedir = os.path.abspath('locale') + else: + print "this script should be run from the django svn tree or your project or app tree" + sys.exit(1) + + for (dirpath, dirnames, filenames) in os.walk(basedir): + for f in filenames: + if f.endswith('.po'): + sys.stderr.write('processing file %s in %s\n' % (f, dirpath)) + pf = os.path.splitext(os.path.join(dirpath, f))[0] + cmd = 'msguniq "%s.po"' % pf + stdout = os.popen(cmd) + msg = stdout.read() + open('%s.po' % pf, 'w').write(msg) + +if __name__ == "__main__": + unique_messages() diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/__init__.py new file mode 100644 index 0000000..fc69bed --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/__init__.py @@ -0,0 +1,153 @@ +""" +Settings and configuration for Django. + +Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment +variable, and then from django.conf.global_settings; see the global settings file for +a list of all possible variables. +""" + +import os +import time # Needed for Windows +from django.conf import global_settings + +ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" + +class LazySettings(object): + """ + A lazy proxy for either global Django settings or a custom settings object. + The user can manually configure settings prior to using them. Otherwise, + Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. + """ + def __init__(self): + # _target must be either None or something that supports attribute + # access (getattr, hasattr, etc). + self._target = None + + def __getattr__(self, name): + if self._target is None: + self._import_settings() + if name == '__members__': + # Used to implement dir(obj), for example. + return self._target.get_all_members() + return getattr(self._target, name) + + def __setattr__(self, name, value): + if name == '_target': + # Assign directly to self.__dict__, because otherwise we'd call + # __setattr__(), which would be an infinite loop. + self.__dict__['_target'] = value + else: + if self._target is None: + self._import_settings() + setattr(self._target, name, value) + + def _import_settings(self): + """ + Load the settings module pointed to by the environment variable. This + is used the first time we need any settings at all, if the user has not + previously configured the settings manually. + """ + try: + settings_module = os.environ[ENVIRONMENT_VARIABLE] + if not settings_module: # If it's set but is an empty string. + raise KeyError + except KeyError: + # NOTE: This is arguably an EnvironmentError, but that causes + # problems with Python's interactive help. + raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) + + self._target = Settings(settings_module) + + def configure(self, default_settings=global_settings, **options): + """ + Called to manually configure the settings. The 'default_settings' + parameter sets where to retrieve any unspecified values from (its + argument must support attribute access (__getattr__)). + """ + if self._target != None: + raise RuntimeError, 'Settings already configured.' + holder = UserSettingsHolder(default_settings) + for name, value in options.items(): + setattr(holder, name, value) + self._target = holder + + def configured(self): + """ + Returns True if the settings have already been configured. + """ + return bool(self._target) + configured = property(configured) + +class Settings(object): + def __init__(self, settings_module): + # update this dict from global settings (but only for ALL_CAPS settings) + for setting in dir(global_settings): + if setting == setting.upper(): + setattr(self, setting, getattr(global_settings, setting)) + + # store the settings module in case someone later cares + self.SETTINGS_MODULE = settings_module + + try: + mod = __import__(self.SETTINGS_MODULE, {}, {}, ['']) + except ImportError, e: + raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) + + # Settings that should be converted into tuples if they're mistakenly entered + # as strings. + tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") + + for setting in dir(mod): + if setting == setting.upper(): + setting_value = getattr(mod, setting) + if setting in tuple_settings and type(setting_value) == str: + setting_value = (setting_value,) # In case the user forgot the comma. + setattr(self, setting, setting_value) + + # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list + # of all those apps. + new_installed_apps = [] + for app in self.INSTALLED_APPS: + if app.endswith('.*'): + appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__) + app_subdirs = os.listdir(appdir) + app_subdirs.sort() + for d in app_subdirs: + if d.isalpha() and os.path.isdir(os.path.join(appdir, d)): + new_installed_apps.append('%s.%s' % (app[:-2], d)) + else: + new_installed_apps.append(app) + self.INSTALLED_APPS = new_installed_apps + + if hasattr(time, 'tzset'): + # Move the time zone info into os.environ. See ticket #2315 for why + # we don't do this unconditionally (breaks Windows). + os.environ['TZ'] = self.TIME_ZONE + time.tzset() + + def get_all_members(self): + return dir(self) + +class UserSettingsHolder(object): + """ + Holder for user configured settings. + """ + # SETTINGS_MODULE doesn't make much sense in the manually configured + # (standalone) case. + SETTINGS_MODULE = None + + def __init__(self, default_settings): + """ + Requests for configuration variables not in this class are satisfied + from the module specified in default_settings (if possible). + """ + self.default_settings = default_settings + + def __getattr__(self, name): + return getattr(self.default_settings, name) + + def get_all_members(self): + return dir(self) + dir(self.default_settings) + +settings = LazySettings() + diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/models.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/views.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/views.py new file mode 100644 index 0000000..60f00ef --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/app_template/views.py @@ -0,0 +1 @@ +# Create your views here. diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/global_settings.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/global_settings.py new file mode 100644 index 0000000..9085120 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/global_settings.py @@ -0,0 +1,401 @@ +# Default Django settings. Override these with settings in the module +# pointed-to by the DJANGO_SETTINGS_MODULE environment variable. + +# This is defined here as a do-nothing function because we can't import +# django.utils.translation -- that module depends on the settings. +gettext_noop = lambda s: s + +#################### +# CORE # +#################### + +DEBUG = False +TEMPLATE_DEBUG = False + +# Whether the framework should propagate raw exceptions rather than catching +# them. This is useful under some testing siutations and should never be used +# on a live site. +DEBUG_PROPAGATE_EXCEPTIONS = False + +# Whether to use the "Etag" header. This saves bandwidth but slows down performance. +USE_ETAGS = False + +# People who get code error notifications. +# In the format (('Full Name', 'email@domain.com'), ('Full Name', 'anotheremail@domain.com')) +ADMINS = () + +# Tuple of IP addresses, as strings, that: +# * See debug comments, when DEBUG is true +# * Receive x-headers +INTERNAL_IPS = () + +# Local time zone for this installation. All choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all +# systems may support all possibilities). +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +# Languages we provide translations for, out of the box. The language name +# should be the utf-8 encoded local name for the language. +LANGUAGES = ( + ('ar', gettext_noop('Arabic')), + ('bn', gettext_noop('Bengali')), + ('bg', gettext_noop('Bulgarian')), + ('ca', gettext_noop('Catalan')), + ('cs', gettext_noop('Czech')), + ('cy', gettext_noop('Welsh')), + ('da', gettext_noop('Danish')), + ('de', gettext_noop('German')), + ('el', gettext_noop('Greek')), + ('en', gettext_noop('English')), + ('es', gettext_noop('Spanish')), + ('et', gettext_noop('Estonian')), + ('es-ar', gettext_noop('Argentinean Spanish')), + ('eu', gettext_noop('Basque')), + ('fa', gettext_noop('Persian')), + ('fi', gettext_noop('Finnish')), + ('fr', gettext_noop('French')), + ('ga', gettext_noop('Irish')), + ('gl', gettext_noop('Galician')), + ('hu', gettext_noop('Hungarian')), + ('he', gettext_noop('Hebrew')), + ('hr', gettext_noop('Croatian')), + ('is', gettext_noop('Icelandic')), + ('it', gettext_noop('Italian')), + ('ja', gettext_noop('Japanese')), + ('ka', gettext_noop('Georgian')), + ('ko', gettext_noop('Korean')), + ('km', gettext_noop('Khmer')), + ('kn', gettext_noop('Kannada')), + ('lv', gettext_noop('Latvian')), + ('lt', gettext_noop('Lithuanian')), + ('mk', gettext_noop('Macedonian')), + ('nl', gettext_noop('Dutch')), + ('no', gettext_noop('Norwegian')), + ('pl', gettext_noop('Polish')), + ('pt', gettext_noop('Portugese')), + ('pt-br', gettext_noop('Brazilian Portuguese')), + ('ro', gettext_noop('Romanian')), + ('ru', gettext_noop('Russian')), + ('sk', gettext_noop('Slovak')), + ('sl', gettext_noop('Slovenian')), + ('sr', gettext_noop('Serbian')), + ('sv', gettext_noop('Swedish')), + ('ta', gettext_noop('Tamil')), + ('te', gettext_noop('Telugu')), + ('tr', gettext_noop('Turkish')), + ('uk', gettext_noop('Ukrainian')), + ('zh-cn', gettext_noop('Simplified Chinese')), + ('zh-tw', gettext_noop('Traditional Chinese')), +) + +# Languages using BiDi (right-to-left) layout +LANGUAGES_BIDI = ("he", "ar", "fa") + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True +LOCALE_PATHS = () +LANGUAGE_COOKIE_NAME = 'django_language' + +# Not-necessarily-technical managers of the site. They get broken link +# notifications and other various e-mails. +MANAGERS = ADMINS + +# Default content type and charset to use for all HttpResponse objects, if a +# MIME type isn't manually specified. These are used to construct the +# Content-Type header. +DEFAULT_CONTENT_TYPE = 'text/html' +DEFAULT_CHARSET = 'utf-8' + +# Encoding of files read from disk (template and initial SQL files). +FILE_CHARSET = 'utf-8' + +# E-mail address that error messages come from. +SERVER_EMAIL = 'root@localhost' + +# Whether to send broken-link e-mails. +SEND_BROKEN_LINK_EMAILS = False + +# Database connection info. +DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +DATABASE_NAME = '' # Or path to database file if using sqlite3. +DATABASE_USER = '' # Not used with sqlite3. +DATABASE_PASSWORD = '' # Not used with sqlite3. +DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. +DATABASE_OPTIONS = {} # Set to empty dictionary for default. + +# Host for sending e-mail. +EMAIL_HOST = 'localhost' + +# Port for sending e-mail. +EMAIL_PORT = 25 + +# Optional SMTP authentication information for EMAIL_HOST. +EMAIL_HOST_USER = '' +EMAIL_HOST_PASSWORD = '' +EMAIL_USE_TLS = False + +# List of strings representing installed apps. +INSTALLED_APPS = () + +# List of locations of the template source files, in search order. +TEMPLATE_DIRS = () + +# List of callables that know how to import templates from various sources. +# See the comments in django/core/template/loader.py for interface +# documentation. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +# 'django.template.loaders.eggs.load_template_source', +) + +# List of processors used by RequestContext to populate the context. +# Each one should be a callable that takes the request object as its +# only parameter and returns a dictionary to add to the context. +TEMPLATE_CONTEXT_PROCESSORS = ( + 'django.core.context_processors.auth', + 'django.core.context_processors.debug', + 'django.core.context_processors.i18n', + 'django.core.context_processors.media', +# 'django.core.context_processors.request', +) + +# Output to use in template system for invalid (e.g. misspelled) variables. +TEMPLATE_STRING_IF_INVALID = '' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# Default e-mail address to use for various automated correspondence from +# the site managers. +DEFAULT_FROM_EMAIL = 'webmaster@localhost' + +# Subject-line prefix for email messages send with django.core.mail.mail_admins +# or ...mail_managers. Make sure to include the trailing space. +EMAIL_SUBJECT_PREFIX = '[Django] ' + +# Whether to append trailing slashes to URLs. +APPEND_SLASH = True + +# Whether to prepend the "www." subdomain to URLs that don't have it. +PREPEND_WWW = False + +# Override the server-derived value of SCRIPT_NAME +FORCE_SCRIPT_NAME = None + +# List of compiled regular expression objects representing User-Agent strings +# that are not allowed to visit any page, systemwide. Use this for bad +# robots/crawlers. Here are a few examples: +# import re +# DISALLOWED_USER_AGENTS = ( +# re.compile(r'^NaverBot.*'), +# re.compile(r'^EmailSiphon.*'), +# re.compile(r'^SiteSucker.*'), +# re.compile(r'^sohu-search') +# ) +DISALLOWED_USER_AGENTS = () + +ABSOLUTE_URL_OVERRIDES = {} + +# Tuple of strings representing allowed prefixes for the {% ssi %} tag. +# Example: ('/home/html', '/var/www') +ALLOWED_INCLUDE_ROOTS = () + +# If this is a admin settings module, this should be a list of +# settings modules (in the format 'foo.bar.baz') for which this admin +# is an admin. +ADMIN_FOR = () + +# 404s that may be ignored. +IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf') +IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php') + +# A secret key for this particular Django installation. Used in secret-key +# hashing algorithms. Set this in your settings, or Django will complain +# loudly. +SECRET_KEY = '' + +# Path to the "jing" executable -- needed to validate XMLFields +JING_PATH = "/usr/bin/jing" + +# Default file storage mechanism that holds media. +DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. +# Example: "http://media.lawrence.com" +MEDIA_URL = '' + +# List of upload handler classes to be applied in order. +FILE_UPLOAD_HANDLERS = ( + 'django.core.files.uploadhandler.MemoryFileUploadHandler', + 'django.core.files.uploadhandler.TemporaryFileUploadHandler', +) + +# Maximum size, in bytes, of a request before it will be streamed to the +# file system instead of into memory. +FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB + +# Directory in which upload streamed files will be temporarily saved. A value of +# `None` will make Django use the operating system's default temporary directory +# (i.e. "/tmp" on *nix systems). +FILE_UPLOAD_TEMP_DIR = None + +# The numeric mode to set newly-uploaded files to. The value should be a mode +# you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html. +FILE_UPLOAD_PERMISSIONS = None + +# Default formatting for date objects. See all available format strings here: +# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now +DATE_FORMAT = 'N j, Y' + +# Default formatting for datetime objects. See all available format strings here: +# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now +DATETIME_FORMAT = 'N j, Y, P' + +# Default formatting for time objects. See all available format strings here: +# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now +TIME_FORMAT = 'P' + +# Default formatting for date objects when only the year and month are relevant. +# See all available format strings here: +# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now +YEAR_MONTH_FORMAT = 'F Y' + +# Default formatting for date objects when only the month and day are relevant. +# See all available format strings here: +# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now +MONTH_DAY_FORMAT = 'F j' + +# Do you want to manage transactions manually? +# Hint: you really don't! +TRANSACTIONS_MANAGED = False + +# The User-Agent string to use when checking for URL validity through the +# isExistingURL validator. +from django import get_version +URL_VALIDATOR_USER_AGENT = "Django/%s (http://www.djangoproject.com)" % get_version() + +# The tablespaces to use for each model when not specified otherwise. +DEFAULT_TABLESPACE = '' +DEFAULT_INDEX_TABLESPACE = '' + +############## +# MIDDLEWARE # +############## + +# List of middleware classes to use. Order is important; in the request phase, +# this middleware classes will be applied in the order given, and in the +# response phase the middleware will be applied in reverse order. +MIDDLEWARE_CLASSES = ( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +# 'django.middleware.http.ConditionalGetMiddleware', +# 'django.middleware.gzip.GZipMiddleware', + 'django.middleware.common.CommonMiddleware', +) + +############ +# SESSIONS # +############ + +SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. +SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). +SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. +SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). +SESSION_COOKIE_PATH = '/' # The path of the session cookie. +SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. +SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed. +SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data +SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default. + +######### +# CACHE # +######### + +# The cache backend to use. See the docstring in django.core.cache for the +# possible values. +CACHE_BACKEND = 'locmem://' +CACHE_MIDDLEWARE_KEY_PREFIX = '' +CACHE_MIDDLEWARE_SECONDS = 600 + +#################### +# COMMENTS # +#################### + +COMMENTS_ALLOW_PROFANITIES = False + +# The profanities that will trigger a validation error in the +# 'hasNoProfanities' validator. All of these should be in lowercase. +PROFANITIES_LIST = ('asshat', 'asshead', 'asshole', 'cunt', 'fuck', 'gook', 'nigger', 'shit') + +# The group ID that designates which users are banned. +# Set to None if you're not using it. +COMMENTS_BANNED_USERS_GROUP = None + +# The group ID that designates which users can moderate comments. +# Set to None if you're not using it. +COMMENTS_MODERATORS_GROUP = None + +# The group ID that designates the users whose comments should be e-mailed to MANAGERS. +# Set to None if you're not using it. +COMMENTS_SKETCHY_USERS_GROUP = None + +# The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each +# user. Set this to 0 if you want to disable it. +COMMENTS_FIRST_FEW = 0 + +# A tuple of IP addresses that have been banned from participating in various +# Django-powered features. +BANNED_IPS = () + +################## +# AUTHENTICATION # +################## + +AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) + +LOGIN_URL = '/accounts/login/' + +LOGOUT_URL = '/accounts/logout/' + +LOGIN_REDIRECT_URL = '/accounts/profile/' + +# The number of days a password reset link is valid for +PASSWORD_RESET_TIMEOUT_DAYS = 3 + +########### +# TESTING # +########### + +# The name of the method to use to invoke the test suite +TEST_RUNNER = 'django.test.simple.run_tests' + +# The name of the database to use for testing purposes. +# If None, a name of 'test_' + DATABASE_NAME will be assumed +TEST_DATABASE_NAME = None + +# Strings used to set the character set and collation order for the test +# database. These values are passed literally to the server, so they are +# backend-dependent. If None, no special settings are sent (system defaults are +# used). +TEST_DATABASE_CHARSET = None +TEST_DATABASE_COLLATION = None + +############ +# FIXTURES # +############ + +# The list of directories to search for fixtures +FIXTURE_DIRS = () diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/manage.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/manage.py new file mode 100644 index 0000000..5e78ea9 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/manage.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/settings.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/settings.py new file mode 100644 index 0000000..bbf005d --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/settings.py @@ -0,0 +1,79 @@ +# Django settings for {{ project_name }} project. + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@domain.com'), +) + +MANAGERS = ADMINS + +DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +DATABASE_NAME = '' # Or path to database file if using sqlite3. +DATABASE_USER = '' # Not used with sqlite3. +DATABASE_PASSWORD = '' # Not used with sqlite3. +DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# If running in a Windows environment this must be set to the same as your +# system time zone. +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# Make this unique, and don't share it with anybody. +SECRET_KEY = '' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +# 'django.template.loaders.eggs.load_template_source', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +) + +ROOT_URLCONF = '{{ project_name }}.urls' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', +) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/urls.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/urls.py new file mode 100644 index 0000000..af1d1db --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/project_template/urls.py @@ -0,0 +1,17 @@ +from django.conf.urls.defaults import * + +# Uncomment the next two lines to enable the admin: +# from django.contrib import admin +# admin.autodiscover() + +urlpatterns = patterns('', + # Example: + # (r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), + + # Uncomment the admin/doc line below and add 'django.contrib.admindocs' + # to INSTALLED_APPS to enable admin documentation: + # (r'^admin/doc/', include('django.contrib.admindocs.urls')), + + # Uncomment the next line to enable the admin: + # (r'^admin/(.*)', admin.site.root), +) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/defaults.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/defaults.py new file mode 100644 index 0000000..26cdd3e --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/defaults.py @@ -0,0 +1,32 @@ +from django.core.urlresolvers import RegexURLPattern, RegexURLResolver +from django.core.exceptions import ImproperlyConfigured + +__all__ = ['handler404', 'handler500', 'include', 'patterns', 'url'] + +handler404 = 'django.views.defaults.page_not_found' +handler500 = 'django.views.defaults.server_error' + +include = lambda urlconf_module: [urlconf_module] + +def patterns(prefix, *args): + pattern_list = [] + for t in args: + if isinstance(t, (list, tuple)): + t = url(prefix=prefix, *t) + elif isinstance(t, RegexURLPattern): + t.add_prefix(prefix) + pattern_list.append(t) + return pattern_list + +def url(regex, view, kwargs=None, name=None, prefix=''): + if type(view) == list: + # For include(...) processing. + return RegexURLResolver(regex, view[0], kwargs) + else: + if isinstance(view, basestring): + if not view: + raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex) + if prefix: + view = prefix + '.' + view + return RegexURLPattern(regex, view, kwargs, name) + diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/i18n.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/i18n.py new file mode 100644 index 0000000..00e2d60 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/i18n.py @@ -0,0 +1,5 @@ +from django.conf.urls.defaults import * + +urlpatterns = patterns('', + (r'^setlang/$', 'django.views.i18n.set_language'), +) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/shortcut.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/shortcut.py new file mode 100644 index 0000000..135f3be --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/conf/urls/shortcut.py @@ -0,0 +1,5 @@ +from django.conf.urls.defaults import * + +urlpatterns = patterns('django.views', + (r'^(?P\d+)/(?P.*)/$', 'defaults.shortcut'), +) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/__init__.py new file mode 100644 index 0000000..8396ffc --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/__init__.py @@ -0,0 +1,40 @@ +from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL +from django.contrib.admin.options import StackedInline, TabularInline +from django.contrib.admin.sites import AdminSite, site + +def autodiscover(): + """ + Auto-discover INSTALLED_APPS admin.py modules and fail silently when + not present. This forces an import on them to register any admin bits they + may want. + """ + import imp + from django.conf import settings + + for app in settings.INSTALLED_APPS: + # For each app, we need to look for an admin.py inside that app's + # package. We can't use os.path here -- recall that modules may be + # imported different ways (think zip files) -- so we need to get + # the app's __path__ and look for admin.py on that path. + + # Step 1: find out the app's __path__ Import errors here will (and + # should) bubble up, but a missing __path__ (which is legal, but weird) + # fails silently -- apps that do weird things with __path__ might + # need to roll their own admin registration. + try: + app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__ + except AttributeError: + continue + + # Step 2: use imp.find_module to find the app's admin.py. For some + # reason imp.find_module raises ImportError if the app can't be found + # but doesn't actually try to import the module. So skip this app if + # its admin.py doesn't exist + try: + imp.find_module('admin', app_path) + except ImportError: + continue + + # Step 3: import the app's admin file. If this has errors we want them + # to bubble up. + __import__("%s.admin" % app) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/filterspecs.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/filterspecs.py new file mode 100644 index 0000000..d6a4a0b --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/filterspecs.py @@ -0,0 +1,179 @@ +""" +FilterSpec encapsulates the logic for displaying filters in the Django admin. +Filters are specified in models with the "list_filter" option. + +Each filter subclass knows how to display a filter for a field that passes a +certain test -- e.g. being a DateField or ForeignKey. +""" + +from django.db import models +from django.utils.encoding import smart_unicode, iri_to_uri +from django.utils.translation import ugettext as _ +from django.utils.html import escape +from django.utils.safestring import mark_safe +import datetime + +class FilterSpec(object): + filter_specs = [] + def __init__(self, f, request, params, model, model_admin): + self.field = f + self.params = params + + def register(cls, test, factory): + cls.filter_specs.append((test, factory)) + register = classmethod(register) + + def create(cls, f, request, params, model, model_admin): + for test, factory in cls.filter_specs: + if test(f): + return factory(f, request, params, model, model_admin) + create = classmethod(create) + + def has_output(self): + return True + + def choices(self, cl): + raise NotImplementedError() + + def title(self): + return self.field.verbose_name + + def output(self, cl): + t = [] + if self.has_output(): + t.append(_(u'

By %s:

\n
    \n') % escape(self.title())) + + for choice in self.choices(cl): + t.append(u'%s\n' % \ + ((choice['selected'] and ' class="selected"' or ''), + iri_to_uri(choice['query_string']), + choice['display'])) + t.append('
\n\n') + return mark_safe("".join(t)) + +class RelatedFilterSpec(FilterSpec): + def __init__(self, f, request, params, model, model_admin): + super(RelatedFilterSpec, self).__init__(f, request, params, model, model_admin) + if isinstance(f, models.ManyToManyField): + self.lookup_title = f.rel.to._meta.verbose_name + else: + self.lookup_title = f.verbose_name + self.lookup_kwarg = '%s__%s__exact' % (f.name, f.rel.to._meta.pk.name) + self.lookup_val = request.GET.get(self.lookup_kwarg, None) + self.lookup_choices = f.rel.to._default_manager.all() + + def has_output(self): + return len(self.lookup_choices) > 1 + + def title(self): + return self.lookup_title + + def choices(self, cl): + yield {'selected': self.lookup_val is None, + 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), + 'display': _('All')} + for val in self.lookup_choices: + pk_val = getattr(val, self.field.rel.to._meta.pk.attname) + yield {'selected': self.lookup_val == smart_unicode(pk_val), + 'query_string': cl.get_query_string({self.lookup_kwarg: pk_val}), + 'display': val} + +FilterSpec.register(lambda f: bool(f.rel), RelatedFilterSpec) + +class ChoicesFilterSpec(FilterSpec): + def __init__(self, f, request, params, model, model_admin): + super(ChoicesFilterSpec, self).__init__(f, request, params, model, model_admin) + self.lookup_kwarg = '%s__exact' % f.name + self.lookup_val = request.GET.get(self.lookup_kwarg, None) + + def choices(self, cl): + yield {'selected': self.lookup_val is None, + 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), + 'display': _('All')} + for k, v in self.field.choices: + yield {'selected': smart_unicode(k) == self.lookup_val, + 'query_string': cl.get_query_string({self.lookup_kwarg: k}), + 'display': v} + +FilterSpec.register(lambda f: bool(f.choices), ChoicesFilterSpec) + +class DateFieldFilterSpec(FilterSpec): + def __init__(self, f, request, params, model, model_admin): + super(DateFieldFilterSpec, self).__init__(f, request, params, model, model_admin) + + self.field_generic = '%s__' % self.field.name + + self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)]) + + today = datetime.date.today() + one_week_ago = today - datetime.timedelta(days=7) + today_str = isinstance(self.field, models.DateTimeField) and today.strftime('%Y-%m-%d 23:59:59') or today.strftime('%Y-%m-%d') + + self.links = ( + (_('Any date'), {}), + (_('Today'), {'%s__year' % self.field.name: str(today.year), + '%s__month' % self.field.name: str(today.month), + '%s__day' % self.field.name: str(today.day)}), + (_('Past 7 days'), {'%s__gte' % self.field.name: one_week_ago.strftime('%Y-%m-%d'), + '%s__lte' % f.name: today_str}), + (_('This month'), {'%s__year' % self.field.name: str(today.year), + '%s__month' % f.name: str(today.month)}), + (_('This year'), {'%s__year' % self.field.name: str(today.year)}) + ) + + def title(self): + return self.field.verbose_name + + def choices(self, cl): + for title, param_dict in self.links: + yield {'selected': self.date_params == param_dict, + 'query_string': cl.get_query_string(param_dict, [self.field_generic]), + 'display': title} + +FilterSpec.register(lambda f: isinstance(f, models.DateField), DateFieldFilterSpec) + +class BooleanFieldFilterSpec(FilterSpec): + def __init__(self, f, request, params, model, model_admin): + super(BooleanFieldFilterSpec, self).__init__(f, request, params, model, model_admin) + self.lookup_kwarg = '%s__exact' % f.name + self.lookup_kwarg2 = '%s__isnull' % f.name + self.lookup_val = request.GET.get(self.lookup_kwarg, None) + self.lookup_val2 = request.GET.get(self.lookup_kwarg2, None) + + def title(self): + return self.field.verbose_name + + def choices(self, cl): + for k, v in ((_('All'), None), (_('Yes'), '1'), (_('No'), '0')): + yield {'selected': self.lookup_val == v and not self.lookup_val2, + 'query_string': cl.get_query_string({self.lookup_kwarg: v}, [self.lookup_kwarg2]), + 'display': k} + if isinstance(self.field, models.NullBooleanField): + yield {'selected': self.lookup_val2 == 'True', + 'query_string': cl.get_query_string({self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]), + 'display': _('Unknown')} + +FilterSpec.register(lambda f: isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField), BooleanFieldFilterSpec) + +# This should be registered last, because it's a last resort. For example, +# if a field is eligible to use the BooleanFieldFilterSpec, that'd be much +# more appropriate, and the AllValuesFilterSpec won't get used for it. +class AllValuesFilterSpec(FilterSpec): + def __init__(self, f, request, params, model, model_admin): + super(AllValuesFilterSpec, self).__init__(f, request, params, model, model_admin) + self.lookup_val = request.GET.get(f.name, None) + self.lookup_choices = model_admin.queryset(request).distinct().order_by(f.name).values(f.name) + + def title(self): + return self.field.verbose_name + + def choices(self, cl): + yield {'selected': self.lookup_val is None, + 'query_string': cl.get_query_string({}, [self.field.name]), + 'display': _('All')} + for val in self.lookup_choices: + val = smart_unicode(val[self.field.name]) + yield {'selected': self.lookup_val == val, + 'query_string': cl.get_query_string({self.field.name: val}), + 'display': val} +FilterSpec.register(lambda f: True, AllValuesFilterSpec) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/helpers.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/helpers.py new file mode 100644 index 0000000..00e1f88 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/helpers.py @@ -0,0 +1,154 @@ + +from django import forms +from django.conf import settings +from django.utils.html import escape +from django.utils.safestring import mark_safe +from django.utils.encoding import force_unicode +from django.contrib.admin.util import flatten_fieldsets +from django.contrib.contenttypes.models import ContentType + +class AdminForm(object): + def __init__(self, form, fieldsets, prepopulated_fields): + self.form, self.fieldsets = form, fieldsets + self.prepopulated_fields = [{ + 'field': form[field_name], + 'dependencies': [form[f] for f in dependencies] + } for field_name, dependencies in prepopulated_fields.items()] + + def __iter__(self): + for name, options in self.fieldsets: + yield Fieldset(self.form, name, **options) + + def first_field(self): + try: + fieldset_name, fieldset_options = self.fieldsets[0] + field_name = fieldset_options['fields'][0] + if not isinstance(field_name, basestring): + field_name = field_name[0] + return self.form[field_name] + except (KeyError, IndexError): + pass + try: + return iter(self.form).next() + except StopIteration: + return None + + def _media(self): + media = self.form.media + for fs in self: + media = media + fs.media + return media + media = property(_media) + +class Fieldset(object): + def __init__(self, form, name=None, fields=(), classes=(), description=None): + self.form = form + self.name, self.fields = name, fields + self.classes = u' '.join(classes) + self.description = description + + def _media(self): + if 'collapse' in self.classes: + return forms.Media(js=['%sjs/admin/CollapsedFieldsets.js' % settings.ADMIN_MEDIA_PREFIX]) + return forms.Media() + media = property(_media) + + def __iter__(self): + for field in self.fields: + yield Fieldline(self.form, field) + +class Fieldline(object): + def __init__(self, form, field): + self.form = form # A django.forms.Form instance + if isinstance(field, basestring): + self.fields = [field] + else: + self.fields = field + + def __iter__(self): + for i, field in enumerate(self.fields): + yield AdminField(self.form, field, is_first=(i == 0)) + + def errors(self): + return mark_safe(u'\n'.join([self.form[f].errors.as_ul() for f in self.fields]).strip('\n')) + +class AdminField(object): + def __init__(self, form, field, is_first): + self.field = form[field] # A django.forms.BoundField instance + self.is_first = is_first # Whether this field is first on the line + self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) + + def label_tag(self): + classes = [] + if self.is_checkbox: + classes.append(u'vCheckboxLabel') + contents = force_unicode(escape(self.field.label)) + else: + contents = force_unicode(escape(self.field.label)) + u':' + if self.field.field.required: + classes.append(u'required') + if not self.is_first: + classes.append(u'inline') + attrs = classes and {'class': u' '.join(classes)} or {} + return self.field.label_tag(contents=contents, attrs=attrs) + +class InlineAdminFormSet(object): + """ + A wrapper around an inline formset for use in the admin system. + """ + def __init__(self, inline, formset, fieldsets): + self.opts = inline + self.formset = formset + self.fieldsets = fieldsets + + def __iter__(self): + for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()): + yield InlineAdminForm(self.formset, form, self.fieldsets, self.opts.prepopulated_fields, original) + for form in self.formset.extra_forms: + yield InlineAdminForm(self.formset, form, self.fieldsets, self.opts.prepopulated_fields, None) + + def fields(self): + for field_name in flatten_fieldsets(self.fieldsets): + yield self.formset.form.base_fields[field_name] + + def _media(self): + media = self.opts.media + self.formset.media + for fs in self: + media = media + fs.media + return media + media = property(_media) + +class InlineAdminForm(AdminForm): + """ + A wrapper around an inline form for use in the admin system. + """ + def __init__(self, formset, form, fieldsets, prepopulated_fields, original): + self.formset = formset + self.original = original + if original is not None: + self.original.content_type_id = ContentType.objects.get_for_model(original).pk + self.show_url = original and hasattr(original, 'get_absolute_url') + super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields) + + def pk_field(self): + return AdminField(self.form, self.formset._pk_field.name, False) + + def deletion_field(self): + from django.forms.formsets import DELETION_FIELD_NAME + return AdminField(self.form, DELETION_FIELD_NAME, False) + + def ordering_field(self): + from django.forms.formsets import ORDERING_FIELD_NAME + return AdminField(self.form, ORDERING_FIELD_NAME, False) + +class AdminErrorList(forms.util.ErrorList): + """ + Stores all errors for the form/formsets in an add/change stage view. + """ + def __init__(self, form, inline_formsets): + if form.is_bound: + self.extend(form.errors.values()) + for inline_formset in inline_formsets: + self.extend(inline_formset.non_form_errors()) + for errors_in_inline_form in inline_formset.errors: + self.extend(errors_in_inline_form.values()) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/models.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/models.py new file mode 100644 index 0000000..259884f --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/models.py @@ -0,0 +1,54 @@ +from django.db import models +from django.contrib.contenttypes.models import ContentType +from django.contrib.auth.models import User +from django.contrib.admin.util import quote +from django.utils.translation import ugettext_lazy as _ +from django.utils.encoding import smart_unicode +from django.utils.safestring import mark_safe + +ADDITION = 1 +CHANGE = 2 +DELETION = 3 + +class LogEntryManager(models.Manager): + def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''): + e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message) + e.save() + +class LogEntry(models.Model): + action_time = models.DateTimeField(_('action time'), auto_now=True) + user = models.ForeignKey(User) + content_type = models.ForeignKey(ContentType, blank=True, null=True) + object_id = models.TextField(_('object id'), blank=True, null=True) + object_repr = models.CharField(_('object repr'), max_length=200) + action_flag = models.PositiveSmallIntegerField(_('action flag')) + change_message = models.TextField(_('change message'), blank=True) + objects = LogEntryManager() + class Meta: + verbose_name = _('log entry') + verbose_name_plural = _('log entries') + db_table = 'django_admin_log' + ordering = ('-action_time',) + + def __repr__(self): + return smart_unicode(self.action_time) + + def is_addition(self): + return self.action_flag == ADDITION + + def is_change(self): + return self.action_flag == CHANGE + + def is_deletion(self): + return self.action_flag == DELETION + + def get_edited_object(self): + "Returns the edited object represented by this log entry" + return self.content_type.get_object_for_this_type(pk=self.object_id) + + def get_admin_url(self): + """ + Returns the admin URL to edit the object represented by this log entry. + This is relative to the Django admin index page. + """ + return mark_safe(u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id))) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/options.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/options.py new file mode 100644 index 0000000..ba48ded --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/options.py @@ -0,0 +1,816 @@ +from django import forms, template +from django.forms.formsets import all_valid +from django.forms.models import modelform_factory, inlineformset_factory +from django.forms.models import BaseInlineFormSet +from django.contrib.contenttypes.models import ContentType +from django.contrib.admin import widgets +from django.contrib.admin import helpers +from django.contrib.admin.util import quote, unquote, flatten_fieldsets, get_deleted_objects +from django.core.exceptions import PermissionDenied +from django.db import models, transaction +from django.http import Http404, HttpResponse, HttpResponseRedirect +from django.shortcuts import get_object_or_404, render_to_response +from django.utils.html import escape +from django.utils.safestring import mark_safe +from django.utils.text import capfirst, get_text_list +from django.utils.translation import ugettext as _ +from django.utils.encoding import force_unicode +try: + set +except NameError: + from sets import Set as set # Python 2.3 fallback + +HORIZONTAL, VERTICAL = 1, 2 +# returns the
    class for a given radio_admin field +get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') + +class IncorrectLookupParameters(Exception): + pass + +class BaseModelAdmin(object): + """Functionality common to both ModelAdmin and InlineAdmin.""" + raw_id_fields = () + fields = None + exclude = None + fieldsets = None + form = forms.ModelForm + filter_vertical = () + filter_horizontal = () + radio_fields = {} + prepopulated_fields = {} + + def formfield_for_dbfield(self, db_field, **kwargs): + """ + Hook for specifying the form Field instance for a given database Field + instance. + + If kwargs are given, they're passed to the form Field's constructor. + """ + + # If the field specifies choices, we don't need to look for special + # admin widgets - we just need to use a select widget of some kind. + if db_field.choices: + if db_field.name in self.radio_fields: + # If the field is named as a radio_field, use a RadioSelect + kwargs['widget'] = widgets.AdminRadioSelect(attrs={ + 'class': get_ul_class(self.radio_fields[db_field.name]), + }) + kwargs['choices'] = db_field.get_choices( + include_blank = db_field.blank, + blank_choice=[('', _('None'))] + ) + return db_field.formfield(**kwargs) + else: + # Otherwise, use the default select widget. + return db_field.formfield(**kwargs) + + # For DateTimeFields, use a special field and widget. + if isinstance(db_field, models.DateTimeField): + kwargs['form_class'] = forms.SplitDateTimeField + kwargs['widget'] = widgets.AdminSplitDateTime() + return db_field.formfield(**kwargs) + + # For DateFields, add a custom CSS class. + if isinstance(db_field, models.DateField): + kwargs['widget'] = widgets.AdminDateWidget + return db_field.formfield(**kwargs) + + # For TimeFields, add a custom CSS class. + if isinstance(db_field, models.TimeField): + kwargs['widget'] = widgets.AdminTimeWidget + return db_field.formfield(**kwargs) + + # For TextFields, add a custom CSS class. + if isinstance(db_field, models.TextField): + kwargs['widget'] = widgets.AdminTextareaWidget + return db_field.formfield(**kwargs) + + # For URLFields, add a custom CSS class. + if isinstance(db_field, models.URLField): + kwargs['widget'] = widgets.AdminURLFieldWidget + return db_field.formfield(**kwargs) + + # For IntegerFields, add a custom CSS class. + if isinstance(db_field, models.IntegerField): + kwargs['widget'] = widgets.AdminIntegerFieldWidget + return db_field.formfield(**kwargs) + + # For CommaSeparatedIntegerFields, add a custom CSS class. + if isinstance(db_field, models.CommaSeparatedIntegerField): + kwargs['widget'] = widgets.AdminCommaSeparatedIntegerFieldWidget + return db_field.formfield(**kwargs) + + # For TextInputs, add a custom CSS class. + if isinstance(db_field, models.CharField): + kwargs['widget'] = widgets.AdminTextInputWidget + return db_field.formfield(**kwargs) + + # For FileFields and ImageFields add a link to the current file. + if isinstance(db_field, models.ImageField) or isinstance(db_field, models.FileField): + kwargs['widget'] = widgets.AdminFileWidget + return db_field.formfield(**kwargs) + + # For ForeignKey or ManyToManyFields, use a special widget. + if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): + if isinstance(db_field, models.ForeignKey) and db_field.name in self.raw_id_fields: + kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel) + elif isinstance(db_field, models.ForeignKey) and db_field.name in self.radio_fields: + kwargs['widget'] = widgets.AdminRadioSelect(attrs={ + 'class': get_ul_class(self.radio_fields[db_field.name]), + }) + kwargs['empty_label'] = db_field.blank and _('None') or None + else: + if isinstance(db_field, models.ManyToManyField): + # If it uses an intermediary model, don't show field in admin. + if db_field.rel.through is not None: + return None + elif db_field.name in self.raw_id_fields: + kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel) + kwargs['help_text'] = '' + elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)): + kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical)) + # Wrap the widget's render() method with a method that adds + # extra HTML to the end of the rendered output. + formfield = db_field.formfield(**kwargs) + # Don't wrap raw_id fields. Their add function is in the popup window. + if not db_field.name in self.raw_id_fields: + # formfield can be None if it came from a OneToOneField with + # parent_link=True + if formfield is not None: + formfield.widget = widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field.rel, self.admin_site) + return formfield + + # For any other type of field, just call its formfield() method. + return db_field.formfield(**kwargs) + + def _declared_fieldsets(self): + if self.fieldsets: + return self.fieldsets + elif self.fields: + return [(None, {'fields': self.fields})] + return None + declared_fieldsets = property(_declared_fieldsets) + +class ModelAdmin(BaseModelAdmin): + "Encapsulates all admin options and functionality for a given model." + __metaclass__ = forms.MediaDefiningClass + + list_display = ('__str__',) + list_display_links = () + list_filter = () + list_select_related = False + list_per_page = 100 + search_fields = () + date_hierarchy = None + save_as = False + save_on_top = False + ordering = None + inlines = [] + + # Custom templates (designed to be over-ridden in subclasses) + change_form_template = None + change_list_template = None + delete_confirmation_template = None + object_history_template = None + + def __init__(self, model, admin_site): + self.model = model + self.opts = model._meta + self.admin_site = admin_site + self.inline_instances = [] + for inline_class in self.inlines: + inline_instance = inline_class(self.model, self.admin_site) + self.inline_instances.append(inline_instance) + super(ModelAdmin, self).__init__() + + def __call__(self, request, url): + # Delegate to the appropriate method, based on the URL. + if url is None: + return self.changelist_view(request) + elif url == "add": + return self.add_view(request) + elif url.endswith('/history'): + return self.history_view(request, unquote(url[:-8])) + elif url.endswith('/delete'): + return self.delete_view(request, unquote(url[:-7])) + else: + return self.change_view(request, unquote(url)) + + def _media(self): + from django.conf import settings + + js = ['js/core.js', 'js/admin/RelatedObjectLookups.js'] + if self.prepopulated_fields: + js.append('js/urlify.js') + if self.opts.get_ordered_objects(): + js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js']) + + return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js]) + media = property(_media) + + def has_add_permission(self, request): + "Returns True if the given request has permission to add an object." + opts = self.opts + return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) + + def has_change_permission(self, request, obj=None): + """ + Returns True if the given request has permission to change the given + Django model instance. + + If `obj` is None, this should return True if the given request has + permission to change *any* object of the given type. + """ + opts = self.opts + return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission()) + + def has_delete_permission(self, request, obj=None): + """ + Returns True if the given request has permission to change the given + Django model instance. + + If `obj` is None, this should return True if the given request has + permission to delete *any* object of the given type. + """ + opts = self.opts + return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission()) + + def queryset(self, request): + """ + Returns a QuerySet of all model instances that can be edited by the + admin site. This is used by changelist_view. + """ + qs = self.model._default_manager.get_query_set() + # TODO: this should be handled by some parameter to the ChangeList. + ordering = self.ordering or () # otherwise we might try to *None, which is bad ;) + if ordering: + qs = qs.order_by(*ordering) + return qs + + def get_fieldsets(self, request, obj=None): + "Hook for specifying fieldsets for the add form." + if self.declared_fieldsets: + return self.declared_fieldsets + form = self.get_form(request, obj) + return [(None, {'fields': form.base_fields.keys()})] + + def get_form(self, request, obj=None, **kwargs): + """ + Returns a Form class for use in the admin add view. This is used by + add_view and change_view. + """ + if self.declared_fieldsets: + fields = flatten_fieldsets(self.declared_fieldsets) + else: + fields = None + if self.exclude is None: + exclude = [] + else: + exclude = self.exclude + defaults = { + "form": self.form, + "fields": fields, + "exclude": exclude + kwargs.get("exclude", []), + "formfield_callback": self.formfield_for_dbfield, + } + defaults.update(kwargs) + return modelform_factory(self.model, **defaults) + + def get_formsets(self, request, obj=None): + for inline in self.inline_instances: + yield inline.get_formset(request, obj) + + def log_addition(self, request, object): + """ + Log that an object has been successfully added. + + The default implementation creates an admin LogEntry object. + """ + from django.contrib.admin.models import LogEntry, ADDITION + LogEntry.objects.log_action( + user_id = request.user.pk, + content_type_id = ContentType.objects.get_for_model(object).pk, + object_id = object.pk, + object_repr = force_unicode(object), + action_flag = ADDITION + ) + + def log_change(self, request, object, message): + """ + Log that an object has been successfully changed. + + The default implementation creates an admin LogEntry object. + """ + from django.contrib.admin.models import LogEntry, CHANGE + LogEntry.objects.log_action( + user_id = request.user.pk, + content_type_id = ContentType.objects.get_for_model(object).pk, + object_id = object.pk, + object_repr = force_unicode(object), + action_flag = CHANGE, + change_message = message + ) + + def log_deletion(self, request, object, object_repr): + """ + Log that an object has been successfully deleted. Note that since the + object is deleted, it might no longer be safe to call *any* methods + on the object, hence this method getting object_repr. + + The default implementation creates an admin LogEntry object. + """ + from django.contrib.admin.models import LogEntry, DELETION + LogEntry.objects.log_action( + user_id = request.user.id, + content_type_id = ContentType.objects.get_for_model(self.model).pk, + object_id = object.pk, + object_repr = object_repr, + action_flag = DELETION + ) + + + def construct_change_message(self, request, form, formsets): + """ + Construct a change message from a changed object. + """ + change_message = [] + if form.changed_data: + change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) + + if formsets: + for formset in formsets: + for added_object in formset.new_objects: + change_message.append(_('Added %(name)s "%(object)s".') + % {'name': added_object._meta.verbose_name, + 'object': added_object}) + for changed_object, changed_fields in formset.changed_objects: + change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') + % {'list': get_text_list(changed_fields, _('and')), + 'name': changed_object._meta.verbose_name, + 'object': changed_object}) + for deleted_object in formset.deleted_objects: + change_message.append(_('Deleted %(name)s "%(object)s".') + % {'name': deleted_object._meta.verbose_name, + 'object': deleted_object}) + change_message = ' '.join(change_message) + return change_message or _('No fields changed.') + + def message_user(self, request, message): + """ + Send a message to the user. The default implementation + posts a message using the auth Message object. + """ + request.user.message_set.create(message=message) + + def save_form(self, request, form, change): + """ + Given a ModelForm return an unsaved instance. ``change`` is True if + the object is being changed, and False if it's being added. + """ + return form.save(commit=False) + + def save_model(self, request, obj, form, change): + """ + Given a model instance save it to the database. + """ + obj.save() + + def save_formset(self, request, form, formset, change): + """ + Given an inline formset save it to the database. + """ + formset.save() + + def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): + opts = self.model._meta + app_label = opts.app_label + ordered_objects = opts.get_ordered_objects() + context.update({ + 'add': add, + 'change': change, + 'has_add_permission': self.has_add_permission(request), + 'has_change_permission': self.has_change_permission(request, obj), + 'has_delete_permission': self.has_delete_permission(request, obj), + 'has_file_field': True, # FIXME - this should check if form or formsets have a FileField, + 'has_absolute_url': hasattr(self.model, 'get_absolute_url'), + 'ordered_objects': ordered_objects, + 'form_url': mark_safe(form_url), + 'opts': opts, + 'content_type_id': ContentType.objects.get_for_model(self.model).id, + 'save_as': self.save_as, + 'save_on_top': self.save_on_top, + 'root_path': self.admin_site.root_path, + }) + return render_to_response(self.change_form_template or [ + "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), + "admin/%s/change_form.html" % app_label, + "admin/change_form.html" + ], context, context_instance=template.RequestContext(request)) + + def response_add(self, request, obj, post_url_continue='../%s/'): + """ + Determines the HttpResponse for the add_view stage. + """ + opts = obj._meta + pk_value = obj._get_pk_val() + + msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} + # Here, we distinguish between different save types by checking for + # the presence of keys in request.POST. + if request.POST.has_key("_continue"): + self.message_user(request, msg + ' ' + _("You may edit it again below.")) + if request.POST.has_key("_popup"): + post_url_continue += "?_popup=1" + return HttpResponseRedirect(post_url_continue % pk_value) + + if request.POST.has_key("_popup"): + return HttpResponse('' % \ + # escape() calls force_unicode. + (escape(pk_value), escape(obj))) + elif request.POST.has_key("_addanother"): + self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) + return HttpResponseRedirect(request.path) + else: + self.message_user(request, msg) + + # Figure out where to redirect. If the user has change permission, + # redirect to the change-list page for this object. Otherwise, + # redirect to the admin index. + if self.has_change_permission(request, None): + post_url = '../' + else: + post_url = '../../../' + return HttpResponseRedirect(post_url) + + def response_change(self, request, obj): + """ + Determines the HttpResponse for the change_view stage. + """ + opts = obj._meta + pk_value = obj._get_pk_val() + + msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} + if request.POST.has_key("_continue"): + self.message_user(request, msg + ' ' + _("You may edit it again below.")) + if request.REQUEST.has_key('_popup'): + return HttpResponseRedirect(request.path + "?_popup=1") + else: + return HttpResponseRedirect(request.path) + elif request.POST.has_key("_saveasnew"): + msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': obj} + self.message_user(request, msg) + return HttpResponseRedirect("../%s/" % pk_value) + elif request.POST.has_key("_addanother"): + self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) + return HttpResponseRedirect("../add/") + else: + self.message_user(request, msg) + return HttpResponseRedirect("../") + + def add_view(self, request, form_url='', extra_context=None): + "The 'add' admin view for this model." + model = self.model + opts = model._meta + app_label = opts.app_label + + if not self.has_add_permission(request): + raise PermissionDenied + + if self.has_change_permission(request, None): + # redirect to list view + post_url = '../' + else: + # Object list will give 'Permission Denied', so go back to admin home + post_url = '../../../' + + ModelForm = self.get_form(request) + formsets = [] + if request.method == 'POST': + form = ModelForm(request.POST, request.FILES) + if form.is_valid(): + form_validated = True + new_object = self.save_form(request, form, change=False) + else: + form_validated = False + new_object = self.model() + for FormSet in self.get_formsets(request): + formset = FormSet(data=request.POST, files=request.FILES, + instance=new_object, + save_as_new=request.POST.has_key("_saveasnew")) + formsets.append(formset) + if all_valid(formsets) and form_validated: + self.save_model(request, new_object, form, change=False) + form.save_m2m() + for formset in formsets: + self.save_formset(request, form, formset, change=False) + + self.log_addition(request, new_object) + return self.response_add(request, new_object) + else: + # Prepare the dict of initial data from the request. + # We have to special-case M2Ms as a list of comma-separated PKs. + initial = dict(request.GET.items()) + for k in initial: + try: + f = opts.get_field(k) + except models.FieldDoesNotExist: + continue + if isinstance(f, models.ManyToManyField): + initial[k] = initial[k].split(",") + form = ModelForm(initial=initial) + for FormSet in self.get_formsets(request): + formset = FormSet(instance=self.model()) + formsets.append(formset) + + adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields) + media = self.media + adminForm.media + + inline_admin_formsets = [] + for inline, formset in zip(self.inline_instances, formsets): + fieldsets = list(inline.get_fieldsets(request)) + inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets) + inline_admin_formsets.append(inline_admin_formset) + media = media + inline_admin_formset.media + + context = { + 'title': _('Add %s') % force_unicode(opts.verbose_name), + 'adminform': adminForm, + 'is_popup': request.REQUEST.has_key('_popup'), + 'show_delete': False, + 'media': mark_safe(media), + 'inline_admin_formsets': inline_admin_formsets, + 'errors': helpers.AdminErrorList(form, formsets), + 'root_path': self.admin_site.root_path, + 'app_label': app_label, + } + context.update(extra_context or {}) + return self.render_change_form(request, context, add=True) + add_view = transaction.commit_on_success(add_view) + + def change_view(self, request, object_id, extra_context=None): + "The 'change' admin view for this model." + model = self.model + opts = model._meta + app_label = opts.app_label + + try: + obj = model._default_manager.get(pk=object_id) + except model.DoesNotExist: + # Don't raise Http404 just yet, because we haven't checked + # permissions yet. We don't want an unauthenticated user to be able + # to determine whether a given object exists. + obj = None + + if not self.has_change_permission(request, obj): + raise PermissionDenied + + if obj is None: + raise Http404('%s object with primary key %r does not exist.' % (force_unicode(opts.verbose_name), escape(object_id))) + + if request.POST and request.POST.has_key("_saveasnew"): + return self.add_view(request, form_url='../../add/') + + ModelForm = self.get_form(request, obj) + formsets = [] + if request.method == 'POST': + form = ModelForm(request.POST, request.FILES, instance=obj) + if form.is_valid(): + form_validated = True + new_object = self.save_form(request, form, change=True) + else: + form_validated = False + new_object = obj + for FormSet in self.get_formsets(request, new_object): + formset = FormSet(request.POST, request.FILES, + instance=new_object) + formsets.append(formset) + + if all_valid(formsets) and form_validated: + self.save_model(request, new_object, form, change=True) + form.save_m2m() + for formset in formsets: + self.save_formset(request, form, formset, change=True) + + change_message = self.construct_change_message(request, form, formsets) + self.log_change(request, new_object, change_message) + return self.response_change(request, new_object) + else: + form = ModelForm(instance=obj) + for FormSet in self.get_formsets(request, obj): + formset = FormSet(instance=obj) + formsets.append(formset) + + adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields) + media = self.media + adminForm.media + + inline_admin_formsets = [] + for inline, formset in zip(self.inline_instances, formsets): + fieldsets = list(inline.get_fieldsets(request, obj)) + inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets) + inline_admin_formsets.append(inline_admin_formset) + media = media + inline_admin_formset.media + + context = { + 'title': _('Change %s') % force_unicode(opts.verbose_name), + 'adminform': adminForm, + 'object_id': object_id, + 'original': obj, + 'is_popup': request.REQUEST.has_key('_popup'), + 'media': mark_safe(media), + 'inline_admin_formsets': inline_admin_formsets, + 'errors': helpers.AdminErrorList(form, formsets), + 'root_path': self.admin_site.root_path, + 'app_label': app_label, + } + context.update(extra_context or {}) + return self.render_change_form(request, context, change=True, obj=obj) + change_view = transaction.commit_on_success(change_view) + + def changelist_view(self, request, extra_context=None): + "The 'change list' admin view for this model." + from django.contrib.admin.views.main import ChangeList, ERROR_FLAG + opts = self.model._meta + app_label = opts.app_label + if not self.has_change_permission(request, None): + raise PermissionDenied + try: + cl = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter, + self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self) + except IncorrectLookupParameters: + # Wacky lookup parameters were given, so redirect to the main + # changelist page, without parameters, and pass an 'invalid=1' + # parameter via the query string. If wacky parameters were given and + # the 'invalid=1' parameter was already in the query string, something + # is screwed up with the database, so display an error page. + if ERROR_FLAG in request.GET.keys(): + return render_to_response('admin/invalid_setup.html', {'title': _('Database error')}) + return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1') + + context = { + 'title': cl.title, + 'is_popup': cl.is_popup, + 'cl': cl, + 'has_add_permission': self.has_add_permission(request), + 'root_path': self.admin_site.root_path, + 'app_label': app_label, + } + context.update(extra_context or {}) + return render_to_response(self.change_list_template or [ + 'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()), + 'admin/%s/change_list.html' % app_label, + 'admin/change_list.html' + ], context, context_instance=template.RequestContext(request)) + + def delete_view(self, request, object_id, extra_context=None): + "The 'delete' admin view for this model." + opts = self.model._meta + app_label = opts.app_label + + try: + obj = self.model._default_manager.get(pk=object_id) + except self.model.DoesNotExist: + # Don't raise Http404 just yet, because we haven't checked + # permissions yet. We don't want an unauthenticated user to be able + # to determine whether a given object exists. + obj = None + + if not self.has_delete_permission(request, obj): + raise PermissionDenied + + if obj is None: + raise Http404('%s object with primary key %r does not exist.' % (force_unicode(opts.verbose_name), escape(object_id))) + + # Populate deleted_objects, a data structure of all related objects that + # will also be deleted. + deleted_objects = [mark_safe(u'%s: %s' % (escape(force_unicode(capfirst(opts.verbose_name))), quote(object_id), escape(obj))), []] + perms_needed = set() + get_deleted_objects(deleted_objects, perms_needed, request.user, obj, opts, 1, self.admin_site) + + if request.POST: # The user has already confirmed the deletion. + if perms_needed: + raise PermissionDenied + obj_display = str(obj) + obj.delete() + + self.log_deletion(request, obj, obj_display) + self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)}) + + if not self.has_change_permission(request, None): + return HttpResponseRedirect("../../../../") + return HttpResponseRedirect("../../") + + context = { + "title": _("Are you sure?"), + "object_name": force_unicode(opts.verbose_name), + "object": obj, + "deleted_objects": deleted_objects, + "perms_lacking": perms_needed, + "opts": opts, + "root_path": self.admin_site.root_path, + "app_label": app_label, + } + context.update(extra_context or {}) + return render_to_response(self.delete_confirmation_template or [ + "admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()), + "admin/%s/delete_confirmation.html" % app_label, + "admin/delete_confirmation.html" + ], context, context_instance=template.RequestContext(request)) + + def history_view(self, request, object_id, extra_context=None): + "The 'history' admin view for this model." + from django.contrib.admin.models import LogEntry + model = self.model + opts = model._meta + app_label = opts.app_label + action_list = LogEntry.objects.filter( + object_id = object_id, + content_type__id__exact = ContentType.objects.get_for_model(model).id + ).select_related().order_by('action_time') + # If no history was found, see whether this object even exists. + obj = get_object_or_404(model, pk=object_id) + context = { + 'title': _('Change history: %s') % force_unicode(obj), + 'action_list': action_list, + 'module_name': capfirst(force_unicode(opts.verbose_name_plural)), + 'object': obj, + 'root_path': self.admin_site.root_path, + 'app_label': app_label, + } + context.update(extra_context or {}) + return render_to_response(self.object_history_template or [ + "admin/%s/%s/object_history.html" % (opts.app_label, opts.object_name.lower()), + "admin/%s/object_history.html" % opts.app_label, + "admin/object_history.html" + ], context, context_instance=template.RequestContext(request)) + +class InlineModelAdmin(BaseModelAdmin): + """ + Options for inline editing of ``model`` instances. + + Provide ``name`` to specify the attribute name of the ``ForeignKey`` from + ``model`` to its parent. This is required if ``model`` has more than one + ``ForeignKey`` to its parent. + """ + model = None + fk_name = None + formset = BaseInlineFormSet + extra = 3 + max_num = 0 + template = None + verbose_name = None + verbose_name_plural = None + + def __init__(self, parent_model, admin_site): + self.admin_site = admin_site + self.parent_model = parent_model + self.opts = self.model._meta + super(InlineModelAdmin, self).__init__() + if self.verbose_name is None: + self.verbose_name = self.model._meta.verbose_name + if self.verbose_name_plural is None: + self.verbose_name_plural = self.model._meta.verbose_name_plural + + def _media(self): + from django.conf import settings + js = [] + if self.prepopulated_fields: + js.append('js/urlify.js') + if self.filter_vertical or self.filter_horizontal: + js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js']) + return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js]) + media = property(_media) + + def get_formset(self, request, obj=None, **kwargs): + """Returns a BaseInlineFormSet class for use in admin add/change views.""" + if self.declared_fieldsets: + fields = flatten_fieldsets(self.declared_fieldsets) + else: + fields = None + if self.exclude is None: + exclude = [] + else: + exclude = self.exclude + defaults = { + "form": self.form, + "formset": self.formset, + "fk_name": self.fk_name, + "fields": fields, + "exclude": exclude + kwargs.get("exclude", []), + "formfield_callback": self.formfield_for_dbfield, + "extra": self.extra, + "max_num": self.max_num, + } + defaults.update(kwargs) + return inlineformset_factory(self.parent_model, self.model, **defaults) + + def get_fieldsets(self, request, obj=None): + if self.declared_fieldsets: + return self.declared_fieldsets + form = self.get_formset(request).form + return [(None, {'fields': form.base_fields.keys()})] + +class StackedInline(InlineModelAdmin): + template = 'admin/edit_inline/stacked.html' + +class TabularInline(InlineModelAdmin): + template = 'admin/edit_inline/tabular.html' diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/sites.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/sites.py new file mode 100644 index 0000000..0be93a2 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/sites.py @@ -0,0 +1,384 @@ +import base64 +import re +from django import http, template +from django.contrib.admin import ModelAdmin +from django.contrib.auth import authenticate, login +from django.db.models.base import ModelBase +from django.core.exceptions import ImproperlyConfigured +from django.shortcuts import render_to_response +from django.utils.safestring import mark_safe +from django.utils.text import capfirst +from django.utils.translation import ugettext_lazy, ugettext as _ +from django.views.decorators.cache import never_cache +from django.conf import settings +from django.utils.hashcompat import md5_constructor + +ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") +LOGIN_FORM_KEY = 'this_is_the_login_form' + +class AlreadyRegistered(Exception): + pass + +class NotRegistered(Exception): + pass + +class AdminSite(object): + """ + An AdminSite object encapsulates an instance of the Django admin application, ready + to be hooked in to your URLConf. Models are registered with the AdminSite using the + register() method, and the root() method can then be used as a Django view function + that presents a full admin interface for the collection of registered models. + """ + + index_template = None + login_template = None + app_index_template = None + + def __init__(self): + self._registry = {} # model_class class -> admin_class instance + + def register(self, model_or_iterable, admin_class=None, **options): + """ + Registers the given model(s) with the given admin class. + + The model(s) should be Model classes, not instances. + + If an admin class isn't given, it will use ModelAdmin (the default + admin options). If keyword arguments are given -- e.g., list_display -- + they'll be applied as options to the admin class. + + If a model is already registered, this will raise AlreadyRegistered. + """ + # Don't import the humongous validation code unless required + if admin_class and settings.DEBUG: + from django.contrib.admin.validation import validate + else: + validate = lambda model, adminclass: None + + if not admin_class: + admin_class = ModelAdmin + if isinstance(model_or_iterable, ModelBase): + model_or_iterable = [model_or_iterable] + for model in model_or_iterable: + if model in self._registry: + raise AlreadyRegistered('The model %s is already registered' % model.__name__) + + # If we got **options then dynamically construct a subclass of + # admin_class with those **options. + if options: + # For reasons I don't quite understand, without a __module__ + # the created class appears to "live" in the wrong place, + # which causes issues later on. + options['__module__'] = __name__ + admin_class = type("%sAdmin" % model.__name__, (admin_class,), options) + + # Validate (which might be a no-op) + validate(admin_class, model) + + # Instantiate the admin class to save in the registry + self._registry[model] = admin_class(model, self) + + def unregister(self, model_or_iterable): + """ + Unregisters the given model(s). + + If a model isn't already registered, this will raise NotRegistered. + """ + if isinstance(model_or_iterable, ModelBase): + model_or_iterable = [model_or_iterable] + for model in model_or_iterable: + if model not in self._registry: + raise NotRegistered('The model %s is not registered' % model.__name__) + del self._registry[model] + + def has_permission(self, request): + """ + Returns True if the given HttpRequest has permission to view + *at least one* page in the admin site. + """ + return request.user.is_authenticated() and request.user.is_staff + + def check_dependencies(self): + """ + Check that all things needed to run the admin have been correctly installed. + + The default implementation checks that LogEntry, ContentType and the + auth context processor are installed. + """ + from django.conf import settings + from django.contrib.admin.models import LogEntry + from django.contrib.contenttypes.models import ContentType + + if not LogEntry._meta.installed: + raise ImproperlyConfigured("Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin application.") + if not ContentType._meta.installed: + raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting in order to use the admin application.") + if 'django.core.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS: + raise ImproperlyConfigured("Put 'django.core.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.") + + def root(self, request, url): + """ + Handles main URL routing for the admin app. + + `url` is the remainder of the URL -- e.g. 'comments/comment/'. + """ + if request.method == 'GET' and not request.path.endswith('/'): + return http.HttpResponseRedirect(request.path + '/') + + if settings.DEBUG: + self.check_dependencies() + + # Figure out the admin base URL path and stash it for later use + self.root_path = re.sub(re.escape(url) + '$', '', request.path) + + url = url.rstrip('/') # Trim trailing slash, if it exists. + + # The 'logout' view doesn't require that the person is logged in. + if url == 'logout': + return self.logout(request) + + # Check permission to continue or display login form. + if not self.has_permission(request): + return self.login(request) + + if url == '': + return self.index(request) + elif url == 'password_change': + return self.password_change(request) + elif url == 'password_change/done': + return self.password_change_done(request) + elif url == 'jsi18n': + return self.i18n_javascript(request) + # urls starting with 'r/' are for the "show in web" links + elif url.startswith('r/'): + from django.views.defaults import shortcut + return shortcut(request, *url.split('/')[1:]) + else: + if '/' in url: + return self.model_page(request, *url.split('/', 2)) + else: + return self.app_index(request, url) + + raise http.Http404('The requested admin page does not exist.') + + def model_page(self, request, app_label, model_name, rest_of_url=None): + """ + Handles the model-specific functionality of the admin site, delegating + to the appropriate ModelAdmin class. + """ + from django.db import models + model = models.get_model(app_label, model_name) + if model is None: + raise http.Http404("App %r, model %r, not found." % (app_label, model_name)) + try: + admin_obj = self._registry[model] + except KeyError: + raise http.Http404("This model exists but has not been registered with the admin site.") + return admin_obj(request, rest_of_url) + model_page = never_cache(model_page) + + def password_change(self, request): + """ + Handles the "change password" task -- both form display and validation. + """ + from django.contrib.auth.views import password_change + return password_change(request, + post_change_redirect='%spassword_change/done/' % self.root_path) + + def password_change_done(self, request): + """ + Displays the "success" page after a password change. + """ + from django.contrib.auth.views import password_change_done + return password_change_done(request) + + def i18n_javascript(self, request): + """ + Displays the i18n JavaScript that the Django admin requires. + + This takes into account the USE_I18N setting. If it's set to False, the + generated JavaScript will be leaner and faster. + """ + if settings.USE_I18N: + from django.views.i18n import javascript_catalog + else: + from django.views.i18n import null_javascript_catalog as javascript_catalog + return javascript_catalog(request, packages='django.conf') + + def logout(self, request): + """ + Logs out the user for the given HttpRequest. + + This should *not* assume the user is already logged in. + """ + from django.contrib.auth.views import logout + return logout(request) + logout = never_cache(logout) + + def login(self, request): + """ + Displays the login form for the given HttpRequest. + """ + from django.contrib.auth.models import User + + # If this isn't already the login page, display it. + if not request.POST.has_key(LOGIN_FORM_KEY): + if request.POST: + message = _("Please log in again, because your session has expired.") + else: + message = "" + return self.display_login_form(request, message) + + # Check that the user accepts cookies. + if not request.session.test_cookie_worked(): + message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") + return self.display_login_form(request, message) + else: + request.session.delete_test_cookie() + + # Check the password. + username = request.POST.get('username', None) + password = request.POST.get('password', None) + user = authenticate(username=username, password=password) + if user is None: + message = ERROR_MESSAGE + if u'@' in username: + # Mistakenly entered e-mail address instead of username? Look it up. + try: + user = User.objects.get(email=username) + except (User.DoesNotExist, User.MultipleObjectsReturned): + message = _("Usernames cannot contain the '@' character.") + else: + if user.check_password(password): + message = _("Your e-mail address is not your username." + " Try '%s' instead.") % user.username + else: + message = _("Usernames cannot contain the '@' character.") + return self.display_login_form(request, message) + + # The user data is correct; log in the user in and continue. + else: + if user.is_active and user.is_staff: + login(request, user) + return http.HttpResponseRedirect(request.get_full_path()) + else: + return self.display_login_form(request, ERROR_MESSAGE) + login = never_cache(login) + + def index(self, request, extra_context=None): + """ + Displays the main admin index page, which lists all of the installed + apps that have been registered in this site. + """ + app_dict = {} + user = request.user + for model, model_admin in self._registry.items(): + app_label = model._meta.app_label + has_module_perms = user.has_module_perms(app_label) + + if has_module_perms: + perms = { + 'add': model_admin.has_add_permission(request), + 'change': model_admin.has_change_permission(request), + 'delete': model_admin.has_delete_permission(request), + } + + # Check whether user has any perm for this module. + # If so, add the module to the model_list. + if True in perms.values(): + model_dict = { + 'name': capfirst(model._meta.verbose_name_plural), + 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())), + 'perms': perms, + } + if app_label in app_dict: + app_dict[app_label]['models'].append(model_dict) + else: + app_dict[app_label] = { + 'name': app_label.title(), + 'app_url': app_label, + 'has_module_perms': has_module_perms, + 'models': [model_dict], + } + + # Sort the apps alphabetically. + app_list = app_dict.values() + app_list.sort(lambda x, y: cmp(x['name'], y['name'])) + + # Sort the models alphabetically within each app. + for app in app_list: + app['models'].sort(lambda x, y: cmp(x['name'], y['name'])) + + context = { + 'title': _('Site administration'), + 'app_list': app_list, + 'root_path': self.root_path, + } + context.update(extra_context or {}) + return render_to_response(self.index_template or 'admin/index.html', context, + context_instance=template.RequestContext(request) + ) + index = never_cache(index) + + def display_login_form(self, request, error_message='', extra_context=None): + request.session.set_test_cookie() + context = { + 'title': _('Log in'), + 'app_path': request.get_full_path(), + 'error_message': error_message, + 'root_path': self.root_path, + } + context.update(extra_context or {}) + return render_to_response(self.login_template or 'admin/login.html', context, + context_instance=template.RequestContext(request) + ) + + def app_index(self, request, app_label, extra_context=None): + user = request.user + has_module_perms = user.has_module_perms(app_label) + app_dict = {} + for model, model_admin in self._registry.items(): + if app_label == model._meta.app_label: + if has_module_perms: + perms = { + 'add': user.has_perm("%s.%s" % (app_label, model._meta.get_add_permission())), + 'change': user.has_perm("%s.%s" % (app_label, model._meta.get_change_permission())), + 'delete': user.has_perm("%s.%s" % (app_label, model._meta.get_delete_permission())), + } + # Check whether user has any perm for this module. + # If so, add the module to the model_list. + if True in perms.values(): + model_dict = { + 'name': capfirst(model._meta.verbose_name_plural), + 'admin_url': '%s/' % model.__name__.lower(), + 'perms': perms, + } + if app_dict: + app_dict['models'].append(model_dict), + else: + # First time around, now that we know there's + # something to display, add in the necessary meta + # information. + app_dict = { + 'name': app_label.title(), + 'app_url': '', + 'has_module_perms': has_module_perms, + 'models': [model_dict], + } + if not app_dict: + raise http.Http404('The requested admin page does not exist.') + # Sort the models alphabetically within each app. + app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name'])) + context = { + 'title': _('%s administration') % capfirst(app_label), + 'app_list': [app_dict], + 'root_path': self.root_path, + } + context.update(extra_context or {}) + return render_to_response(self.app_index_template or 'admin/app_index.html', context, + context_instance=template.RequestContext(request) + ) + +# This global object represents the default admin site, for the common case. +# You can instantiate AdminSite in your own code to create a custom admin site. +site = AdminSite() diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_list.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_list.py new file mode 100644 index 0000000..21e87f5 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_list.py @@ -0,0 +1,316 @@ +from django.conf import settings +from django.contrib.admin.views.main import ALL_VAR, EMPTY_CHANGELIST_VALUE +from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR +from django.core.exceptions import ObjectDoesNotExist +from django.db import models +from django.utils import dateformat +from django.utils.html import escape, conditional_escape +from django.utils.text import capfirst +from django.utils.safestring import mark_safe +from django.utils.translation import get_date_formats, get_partial_date_formats, ugettext as _ +from django.utils.encoding import smart_unicode, smart_str, force_unicode +from django.template import Library +import datetime + +register = Library() + +DOT = '.' + +def paginator_number(cl,i): + if i == DOT: + return u'... ' + elif i == cl.page_num: + return mark_safe(u'%d ' % (i+1)) + else: + return mark_safe(u'%d ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1)) +paginator_number = register.simple_tag(paginator_number) + +def pagination(cl): + paginator, page_num = cl.paginator, cl.page_num + + pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page + if not pagination_required: + page_range = [] + else: + ON_EACH_SIDE = 3 + ON_ENDS = 2 + + # If there are 10 or fewer pages, display links to every page. + # Otherwise, do some fancy + if paginator.num_pages <= 10: + page_range = range(paginator.num_pages) + else: + # Insert "smart" pagination links, so that there are always ON_ENDS + # links at either end of the list of pages, and there are always + # ON_EACH_SIDE links at either end of the "current page" link. + page_range = [] + if page_num > (ON_EACH_SIDE + ON_ENDS): + page_range.extend(range(0, ON_EACH_SIDE - 1)) + page_range.append(DOT) + page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1)) + else: + page_range.extend(range(0, page_num + 1)) + if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): + page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1)) + page_range.append(DOT) + page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages)) + else: + page_range.extend(range(page_num + 1, paginator.num_pages)) + + need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page + return { + 'cl': cl, + 'pagination_required': pagination_required, + 'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}), + 'page_range': page_range, + 'ALL_VAR': ALL_VAR, + '1': 1, + } +pagination = register.inclusion_tag('admin/pagination.html')(pagination) + +def result_headers(cl): + lookup_opts = cl.lookup_opts + + for i, field_name in enumerate(cl.list_display): + attr = None + try: + f = lookup_opts.get_field(field_name) + admin_order_field = None + except models.FieldDoesNotExist: + # For non-field list_display values, check for the function + # attribute "short_description". If that doesn't exist, fall back + # to the method name. And __str__ and __unicode__ are special-cases. + if field_name == '__unicode__': + header = force_unicode(lookup_opts.verbose_name) + elif field_name == '__str__': + header = smart_str(lookup_opts.verbose_name) + else: + if callable(field_name): + attr = field_name # field_name can be a callable + else: + try: + attr = getattr(cl.model_admin, field_name) + except AttributeError: + try: + attr = getattr(cl.model, field_name) + except AttributeError: + raise AttributeError, \ + "'%s' model or '%s' objects have no attribute '%s'" % \ + (lookup_opts.object_name, cl.model_admin.__class__, field_name) + + try: + header = attr.short_description + except AttributeError: + if callable(field_name): + header = field_name.__name__ + else: + header = field_name + header = header.replace('_', ' ') + + # It is a non-field, but perhaps one that is sortable + admin_order_field = getattr(attr, "admin_order_field", None) + if not admin_order_field: + yield {"text": header} + continue + + # So this _is_ a sortable non-field. Go to the yield + # after the else clause. + else: + if isinstance(f.rel, models.ManyToOneRel) and f.null: + yield {"text": f.verbose_name} + continue + else: + header = f.verbose_name + + th_classes = [] + new_order_type = 'asc' + if field_name == cl.order_field or admin_order_field == cl.order_field: + th_classes.append('sorted %sending' % cl.order_type.lower()) + new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()] + + yield {"text": header, + "sortable": True, + "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), + "class_attrib": mark_safe(th_classes and ' class="%s"' % ' '.join(th_classes) or '')} + +def _boolean_icon(field_val): + BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} + return mark_safe(u'%s' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)) + +def items_for_result(cl, result): + first = True + pk = cl.lookup_opts.pk.attname + for field_name in cl.list_display: + row_class = '' + try: + f = cl.lookup_opts.get_field(field_name) + except models.FieldDoesNotExist: + # For non-field list_display values, the value is either a method, + # property or returned via a callable. + try: + if callable(field_name): + attr = field_name + value = attr(result) + elif hasattr(cl.model_admin, field_name) and \ + not field_name == '__str__' and not field_name == '__unicode__': + attr = getattr(cl.model_admin, field_name) + value = attr(result) + else: + attr = getattr(result, field_name) + if callable(attr): + value = attr() + else: + value = attr + allow_tags = getattr(attr, 'allow_tags', False) + boolean = getattr(attr, 'boolean', False) + if boolean: + allow_tags = True + result_repr = _boolean_icon(value) + else: + result_repr = smart_unicode(value) + except (AttributeError, ObjectDoesNotExist): + result_repr = EMPTY_CHANGELIST_VALUE + else: + # Strip HTML tags in the resulting text, except if the + # function has an "allow_tags" attribute set to True. + if not allow_tags: + result_repr = escape(result_repr) + else: + result_repr = mark_safe(result_repr) + else: + field_val = getattr(result, f.attname) + + if isinstance(f.rel, models.ManyToOneRel): + if field_val is not None: + result_repr = escape(getattr(result, f.name)) + else: + result_repr = EMPTY_CHANGELIST_VALUE + # Dates and times are special: They're formatted in a certain way. + elif isinstance(f, models.DateField) or isinstance(f, models.TimeField): + if field_val: + (date_format, datetime_format, time_format) = get_date_formats() + if isinstance(f, models.DateTimeField): + result_repr = capfirst(dateformat.format(field_val, datetime_format)) + elif isinstance(f, models.TimeField): + result_repr = capfirst(dateformat.time_format(field_val, time_format)) + else: + result_repr = capfirst(dateformat.format(field_val, date_format)) + else: + result_repr = EMPTY_CHANGELIST_VALUE + row_class = ' class="nowrap"' + # Booleans are special: We use images. + elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField): + result_repr = _boolean_icon(field_val) + # DecimalFields are special: Zero-pad the decimals. + elif isinstance(f, models.DecimalField): + if field_val is not None: + result_repr = ('%%.%sf' % f.decimal_places) % field_val + else: + result_repr = EMPTY_CHANGELIST_VALUE + # Fields with choices are special: Use the representation + # of the choice. + elif f.choices: + result_repr = dict(f.choices).get(field_val, EMPTY_CHANGELIST_VALUE) + else: + result_repr = escape(field_val) + if force_unicode(result_repr) == '': + result_repr = mark_safe(' ') + # If list_display_links not defined, add the link tag to the first field + if (first and not cl.list_display_links) or field_name in cl.list_display_links: + table_tag = {True:'th', False:'td'}[first] + first = False + url = cl.url_for_result(result) + # Convert the pk to something that can be used in Javascript. + # Problem cases are long ints (23L) and non-ASCII strings. + if cl.to_field: + attr = str(cl.to_field) + else: + attr = pk + result_id = repr(force_unicode(getattr(result, attr)))[1:] + yield mark_safe(u'<%s%s>%s' % \ + (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) + else: + yield mark_safe(u'%s' % (row_class, conditional_escape(result_repr))) + +def results(cl): + for res in cl.result_list: + yield list(items_for_result(cl,res)) + +def result_list(cl): + return {'cl': cl, + 'result_headers': list(result_headers(cl)), + 'results': list(results(cl))} +result_list = register.inclusion_tag("admin/change_list_results.html")(result_list) + +def date_hierarchy(cl): + if cl.date_hierarchy: + field_name = cl.date_hierarchy + year_field = '%s__year' % field_name + month_field = '%s__month' % field_name + day_field = '%s__day' % field_name + field_generic = '%s__' % field_name + year_lookup = cl.params.get(year_field) + month_lookup = cl.params.get(month_field) + day_lookup = cl.params.get(day_field) + year_month_format, month_day_format = get_partial_date_formats() + + link = lambda d: mark_safe(cl.get_query_string(d, [field_generic])) + + if year_lookup and month_lookup and day_lookup: + day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup)) + return { + 'show': True, + 'back': { + 'link': link({year_field: year_lookup, month_field: month_lookup}), + 'title': dateformat.format(day, year_month_format) + }, + 'choices': [{'title': dateformat.format(day, month_day_format)}] + } + elif year_lookup and month_lookup: + days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day') + return { + 'show': True, + 'back': { + 'link': link({year_field: year_lookup}), + 'title': year_lookup + }, + 'choices': [{ + 'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}), + 'title': dateformat.format(day, month_day_format) + } for day in days] + } + elif year_lookup: + months = cl.query_set.filter(**{year_field: year_lookup}).dates(field_name, 'month') + return { + 'show' : True, + 'back': { + 'link' : link({}), + 'title': _('All dates') + }, + 'choices': [{ + 'link': link({year_field: year_lookup, month_field: month.month}), + 'title': dateformat.format(month, year_month_format) + } for month in months] + } + else: + years = cl.query_set.dates(field_name, 'year') + return { + 'show': True, + 'choices': [{ + 'link': link({year_field: year.year}), + 'title': year.year + } for year in years] + } +date_hierarchy = register.inclusion_tag('admin/date_hierarchy.html')(date_hierarchy) + +def search_form(cl): + return { + 'cl': cl, + 'show_result_count': cl.result_count != cl.full_result_count, + 'search_var': SEARCH_VAR + } +search_form = register.inclusion_tag('admin/search_form.html')(search_form) + +def admin_list_filter(cl, spec): + return {'title': spec.title(), 'choices' : list(spec.choices(cl))} +admin_list_filter = register.inclusion_tag('admin/filter.html')(admin_list_filter) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_modify.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_modify.py new file mode 100644 index 0000000..19042fa --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/admin_modify.py @@ -0,0 +1,39 @@ +from django import template + +register = template.Library() + +def prepopulated_fields_js(context): + """ + Creates a list of prepopulated_fields that should render Javascript for + the prepopulated fields for both the admin form and inlines. + """ + prepopulated_fields = [] + if context['add'] and 'adminform' in context: + prepopulated_fields.extend(context['adminform'].prepopulated_fields) + if 'inline_admin_formsets' in context: + for inline_admin_formset in context['inline_admin_formsets']: + for inline_admin_form in inline_admin_formset: + if inline_admin_form.original is None: + prepopulated_fields.extend(inline_admin_form.prepopulated_fields) + context.update({'prepopulated_fields': prepopulated_fields}) + return context +prepopulated_fields_js = register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True)(prepopulated_fields_js) + +def submit_row(context): + opts = context['opts'] + change = context['change'] + is_popup = context['is_popup'] + save_as = context['save_as'] + return { + 'onclick_attrib': (opts.get_ordered_objects() and change + and 'onclick="submitOrderForm();"' or ''), + 'show_delete_link': (not is_popup and context['has_delete_permission'] + and (change or context['show_delete'])), + 'show_save_as_new': not is_popup and change and save_as, + 'show_save_and_add_another': context['has_add_permission'] and + not is_popup and (not save_as or context['add']), + 'show_save_and_continue': not is_popup and context['has_change_permission'], + 'is_popup': is_popup, + 'show_save': True + } +submit_row = register.inclusion_tag('admin/submit_line.html', takes_context=True)(submit_row) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/adminmedia.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/adminmedia.py new file mode 100644 index 0000000..7786343 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/adminmedia.py @@ -0,0 +1,14 @@ +from django.template import Library + +register = Library() + +def admin_media_prefix(): + """ + Returns the string contained in the setting ADMIN_MEDIA_PREFIX. + """ + try: + from django.conf import settings + except ImportError: + return '' + return settings.ADMIN_MEDIA_PREFIX +admin_media_prefix = register.simple_tag(admin_media_prefix) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/log.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/log.py new file mode 100644 index 0000000..8d52d2e --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/templatetags/log.py @@ -0,0 +1,56 @@ +from django import template +from django.contrib.admin.models import LogEntry + +register = template.Library() + +class AdminLogNode(template.Node): + def __init__(self, limit, varname, user): + self.limit, self.varname, self.user = limit, varname, user + + def __repr__(self): + return "" + + def render(self, context): + if self.user is None: + context[self.varname] = LogEntry.objects.all().select_related()[:self.limit] + else: + if not self.user.isdigit(): + self.user = context[self.user].id + context[self.varname] = LogEntry.objects.filter(user__id__exact=self.user).select_related()[:self.limit] + return '' + +class DoGetAdminLog: + """ + Populates a template variable with the admin log for the given criteria. + + Usage:: + + {% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %} + + Examples:: + + {% get_admin_log 10 as admin_log for_user 23 %} + {% get_admin_log 10 as admin_log for_user user %} + {% get_admin_log 10 as admin_log %} + + Note that ``context_var_containing_user_obj`` can be a hard-coded integer + (user ID) or the name of a template context variable containing the user + object whose ID you want. + """ + def __init__(self, tag_name): + self.tag_name = tag_name + + def __call__(self, parser, token): + tokens = token.contents.split() + if len(tokens) < 4: + raise template.TemplateSyntaxError, "'%s' statements require two arguments" % self.tag_name + if not tokens[1].isdigit(): + raise template.TemplateSyntaxError, "First argument in '%s' must be an integer" % self.tag_name + if tokens[2] != 'as': + raise template.TemplateSyntaxError, "Second argument in '%s' must be 'as'" % self.tag_name + if len(tokens) > 4: + if tokens[4] != 'for_user': + raise template.TemplateSyntaxError, "Fourth argument in '%s' must be 'for_user'" % self.tag_name + return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None)) + +register.tag('get_admin_log', DoGetAdminLog('get_admin_log')) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/util.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/util.py new file mode 100644 index 0000000..17213ea --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/util.py @@ -0,0 +1,151 @@ +from django.core.exceptions import ObjectDoesNotExist +from django.db import models +from django.utils.html import escape +from django.utils.safestring import mark_safe +from django.utils.text import capfirst +from django.utils.encoding import force_unicode +from django.utils.translation import ugettext as _ + + +def quote(s): + """ + Ensure that primary key values do not confuse the admin URLs by escaping + any '/', '_' and ':' characters. Similar to urllib.quote, except that the + quoting is slightly different so that it doesn't get automatically + unquoted by the Web browser. + """ + if not isinstance(s, basestring): + return s + res = list(s) + for i in range(len(res)): + c = res[i] + if c in """:/_#?;@&=+$,"<>%\\""": + res[i] = '_%02X' % ord(c) + return ''.join(res) + +def unquote(s): + """ + Undo the effects of quote(). Based heavily on urllib.unquote(). + """ + mychr = chr + myatoi = int + list = s.split('_') + res = [list[0]] + myappend = res.append + del list[0] + for item in list: + if item[1:2]: + try: + myappend(mychr(myatoi(item[:2], 16)) + item[2:]) + except ValueError: + myappend('_' + item) + else: + myappend('_' + item) + return "".join(res) + +def flatten_fieldsets(fieldsets): + """Returns a list of field names from an admin fieldsets structure.""" + field_names = [] + for name, opts in fieldsets: + for field in opts['fields']: + # type checking feels dirty, but it seems like the best way here + if type(field) == tuple: + field_names.extend(field) + else: + field_names.append(field) + return field_names + +def _nest_help(obj, depth, val): + current = obj + for i in range(depth): + current = current[-1] + current.append(val) + +def get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current_depth, admin_site): + "Helper function that recursively populates deleted_objects." + nh = _nest_help # Bind to local variable for performance + if current_depth > 16: + return # Avoid recursing too deep. + opts_seen = [] + for related in opts.get_all_related_objects(): + has_admin = related.model in admin_site._registry + if related.opts in opts_seen: + continue + opts_seen.append(related.opts) + rel_opts_name = related.get_accessor_name() + if isinstance(related.field.rel, models.OneToOneRel): + try: + sub_obj = getattr(obj, rel_opts_name) + except ObjectDoesNotExist: + pass + else: + if has_admin: + p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission()) + if not user.has_perm(p): + perms_needed.add(related.opts.verbose_name) + # We don't care about populating deleted_objects now. + continue + if not has_admin: + # Don't display link to edit, because it either has no + # admin or is edited inline. + nh(deleted_objects, current_depth, [u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), sub_obj), []]) + else: + # Display a link to the admin page. + nh(deleted_objects, current_depth, [mark_safe(u'%s: %s' % + (escape(force_unicode(capfirst(related.opts.verbose_name))), + related.opts.app_label, + related.opts.object_name.lower(), + sub_obj._get_pk_val(), sub_obj)), []]) + get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2, admin_site) + else: + has_related_objs = False + for sub_obj in getattr(obj, rel_opts_name).all(): + has_related_objs = True + if not has_admin: + # Don't display link to edit, because it either has no + # admin or is edited inline. + nh(deleted_objects, current_depth, [u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), sub_obj), []]) + else: + # Display a link to the admin page. + nh(deleted_objects, current_depth, [mark_safe(u'%s: %s' % \ + (escape(force_unicode(capfirst(related.opts.verbose_name))), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(sub_obj))), []]) + get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2, admin_site) + # If there were related objects, and the user doesn't have + # permission to delete them, add the missing perm to perms_needed. + if has_admin and has_related_objs: + p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission()) + if not user.has_perm(p): + perms_needed.add(related.opts.verbose_name) + for related in opts.get_all_related_many_to_many_objects(): + has_admin = related.model in admin_site._registry + if related.opts in opts_seen: + continue + opts_seen.append(related.opts) + rel_opts_name = related.get_accessor_name() + has_related_objs = False + + # related.get_accessor_name() could return None for symmetrical relationships + if rel_opts_name: + rel_objs = getattr(obj, rel_opts_name, None) + if rel_objs: + has_related_objs = True + + if has_related_objs: + for sub_obj in rel_objs.all(): + if not has_admin: + # Don't display link to edit, because it either has no + # admin or is edited inline. + nh(deleted_objects, current_depth, [_('One or more %(fieldname)s in %(name)s: %(obj)s') % \ + {'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name), 'obj': escape(sub_obj)}, []]) + else: + # Display a link to the admin page. + nh(deleted_objects, current_depth, [ + mark_safe((_('One or more %(fieldname)s in %(name)s:') % {'fieldname': escape(force_unicode(related.field.verbose_name)), 'name': escape(force_unicode(related.opts.verbose_name))}) + \ + (u' %s' % \ + (related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(sub_obj)))), []]) + # If there were related objects, and the user doesn't have + # permission to change them, add the missing perm to perms_needed. + if has_admin and has_related_objs: + p = u'%s.%s' % (related.opts.app_label, related.opts.get_change_permission()) + if not user.has_perm(p): + perms_needed.add(related.opts.verbose_name) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/validation.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/validation.py new file mode 100644 index 0000000..13d3a9d --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/validation.py @@ -0,0 +1,277 @@ +try: + set +except NameError: + from sets import Set as set # Python 2.3 fallback + +from django.core.exceptions import ImproperlyConfigured +from django.db import models +from django.forms.models import BaseModelForm, BaseModelFormSet, fields_for_model +from django.contrib.admin.options import flatten_fieldsets, BaseModelAdmin +from django.contrib.admin.options import HORIZONTAL, VERTICAL + +__all__ = ['validate'] + +def validate(cls, model): + """ + Does basic ModelAdmin option validation. Calls custom validation + classmethod in the end if it is provided in cls. The signature of the + custom validation classmethod should be: def validate(cls, model). + """ + # Before we can introspect models, they need to be fully loaded so that + # inter-relations are set up correctly. We force that here. + models.get_apps() + + opts = model._meta + validate_base(cls, model) + + # list_display + if hasattr(cls, 'list_display'): + check_isseq(cls, 'list_display', cls.list_display) + for idx, field in enumerate(cls.list_display): + if not callable(field): + if not hasattr(cls, field): + if not hasattr(model, field): + try: + opts.get_field(field) + except models.FieldDoesNotExist: + raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r." + % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)) + f = fetch_attr(cls, model, opts, "list_display[%d]" % idx, field) + if isinstance(f, models.ManyToManyField): + raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported." + % (cls.__name__, idx, field)) + + # list_display_links + if hasattr(cls, 'list_display_links'): + check_isseq(cls, 'list_display_links', cls.list_display_links) + for idx, field in enumerate(cls.list_display_links): + fetch_attr(cls, model, opts, 'list_display_links[%d]' % idx, field) + if field not in cls.list_display: + raise ImproperlyConfigured("'%s.list_display_links[%d]'" + "refers to '%s' which is not defined in 'list_display'." + % (cls.__name__, idx, field)) + + # list_filter + if hasattr(cls, 'list_filter'): + check_isseq(cls, 'list_filter', cls.list_filter) + for idx, field in enumerate(cls.list_filter): + get_field(cls, model, opts, 'list_filter[%d]' % idx, field) + + # list_per_page = 100 + if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int): + raise ImproperlyConfigured("'%s.list_per_page' should be a integer." + % cls.__name__) + + # search_fields = () + if hasattr(cls, 'search_fields'): + check_isseq(cls, 'search_fields', cls.search_fields) + + # date_hierarchy = None + if cls.date_hierarchy: + f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy) + if not isinstance(f, (models.DateField, models.DateTimeField)): + raise ImproperlyConfigured("'%s.date_hierarchy is " + "neither an instance of DateField nor DateTimeField." + % cls.__name__) + + # ordering = None + if cls.ordering: + check_isseq(cls, 'ordering', cls.ordering) + for idx, field in enumerate(cls.ordering): + if field == '?' and len(cls.ordering) != 1: + raise ImproperlyConfigured("'%s.ordering' has the random " + "ordering marker '?', but contains other fields as " + "well. Please either remove '?' or the other fields." + % cls.__name__) + if field == '?': + continue + if field.startswith('-'): + field = field[1:] + # Skip ordering in the format field1__field2 (FIXME: checking + # this format would be nice, but it's a little fiddly). + if '__' in field: + continue + get_field(cls, model, opts, 'ordering[%d]' % idx, field) + + # list_select_related = False + # save_as = False + # save_on_top = False + for attr in ('list_select_related', 'save_as', 'save_on_top'): + if not isinstance(getattr(cls, attr), bool): + raise ImproperlyConfigured("'%s.%s' should be a boolean." + % (cls.__name__, attr)) + + # inlines = [] + if hasattr(cls, 'inlines'): + check_isseq(cls, 'inlines', cls.inlines) + for idx, inline in enumerate(cls.inlines): + if not issubclass(inline, BaseModelAdmin): + raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit " + "from BaseModelAdmin." % (cls.__name__, idx)) + if not inline.model: + raise ImproperlyConfigured("'model' is a required attribute " + "of '%s.inlines[%d]'." % (cls.__name__, idx)) + if not issubclass(inline.model, models.Model): + raise ImproperlyConfigured("'%s.inlines[%d].model' does not " + "inherit from models.Model." % (cls.__name__, idx)) + validate_base(inline, inline.model) + validate_inline(inline) + +def validate_inline(cls): + # model is already verified to exist and be a Model + if cls.fk_name: # default value is None + f = get_field(cls, cls.model, cls.model._meta, + 'fk_name', cls.fk_name) + if not isinstance(f, models.ForeignKey): + raise ImproperlyConfigured("'%s.fk_name is not an instance of " + "models.ForeignKey." % cls.__name__) + # extra = 3 + # max_num = 0 + for attr in ('extra', 'max_num'): + if not isinstance(getattr(cls, attr), int): + raise ImproperlyConfigured("'%s.%s' should be a integer." + % (cls.__name__, attr)) + + # formset + if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet): + raise ImproperlyConfigured("'%s.formset' does not inherit from " + "BaseModelFormSet." % cls.__name__) + +def validate_base(cls, model): + opts = model._meta + + # raw_id_fields + if hasattr(cls, 'raw_id_fields'): + check_isseq(cls, 'raw_id_fields', cls.raw_id_fields) + for idx, field in enumerate(cls.raw_id_fields): + f = get_field(cls, model, opts, 'raw_id_fields', field) + if not isinstance(f, (models.ForeignKey, models.ManyToManyField)): + raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must " + "be either a ForeignKey or ManyToManyField." + % (cls.__name__, idx, field)) + + # fields + if cls.fields: # default value is None + check_isseq(cls, 'fields', cls.fields) + for field in cls.fields: + check_formfield(cls, model, opts, 'fields', field) + if cls.fieldsets: + raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__) + if len(cls.fields) > len(set(cls.fields)): + raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__) + + # fieldsets + if cls.fieldsets: # default value is None + check_isseq(cls, 'fieldsets', cls.fieldsets) + for idx, fieldset in enumerate(cls.fieldsets): + check_isseq(cls, 'fieldsets[%d]' % idx, fieldset) + if len(fieldset) != 2: + raise ImproperlyConfigured("'%s.fieldsets[%d]' does not " + "have exactly two elements." % (cls.__name__, idx)) + check_isdict(cls, 'fieldsets[%d][1]' % idx, fieldset[1]) + if 'fields' not in fieldset[1]: + raise ImproperlyConfigured("'fields' key is required in " + "%s.fieldsets[%d][1] field options dict." + % (cls.__name__, idx)) + flattened_fieldsets = flatten_fieldsets(cls.fieldsets) + if len(flattened_fieldsets) > len(set(flattened_fieldsets)): + raise ImproperlyConfigured('There are duplicate field(s) in %s.fieldsets' % cls.__name__) + for field in flattened_fieldsets: + check_formfield(cls, model, opts, "fieldsets[%d][1]['fields']" % idx, field) + + # form + if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm): + raise ImproperlyConfigured("%s.form does not inherit from " + "BaseModelForm." % cls.__name__) + + # filter_vertical + if hasattr(cls, 'filter_vertical'): + check_isseq(cls, 'filter_vertical', cls.filter_vertical) + for idx, field in enumerate(cls.filter_vertical): + f = get_field(cls, model, opts, 'filter_vertical', field) + if not isinstance(f, models.ManyToManyField): + raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be " + "a ManyToManyField." % (cls.__name__, idx)) + + # filter_horizontal + if hasattr(cls, 'filter_horizontal'): + check_isseq(cls, 'filter_horizontal', cls.filter_horizontal) + for idx, field in enumerate(cls.filter_horizontal): + f = get_field(cls, model, opts, 'filter_horizontal', field) + if not isinstance(f, models.ManyToManyField): + raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be " + "a ManyToManyField." % (cls.__name__, idx)) + + # radio_fields + if hasattr(cls, 'radio_fields'): + check_isdict(cls, 'radio_fields', cls.radio_fields) + for field, val in cls.radio_fields.items(): + f = get_field(cls, model, opts, 'radio_fields', field) + if not (isinstance(f, models.ForeignKey) or f.choices): + raise ImproperlyConfigured("'%s.radio_fields['%s']' " + "is neither an instance of ForeignKey nor does " + "have choices set." % (cls.__name__, field)) + if not val in (HORIZONTAL, VERTICAL): + raise ImproperlyConfigured("'%s.radio_fields['%s']' " + "is neither admin.HORIZONTAL nor admin.VERTICAL." + % (cls.__name__, field)) + + # prepopulated_fields + if hasattr(cls, 'prepopulated_fields'): + check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields) + for field, val in cls.prepopulated_fields.items(): + f = get_field(cls, model, opts, 'prepopulated_fields', field) + if isinstance(f, (models.DateTimeField, models.ForeignKey, + models.ManyToManyField)): + raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' " + "is either a DateTimeField, ForeignKey or " + "ManyToManyField. This isn't allowed." + % (cls.__name__, field)) + check_isseq(cls, "prepopulated_fields['%s']" % field, val) + for idx, f in enumerate(val): + get_field(cls, model, + opts, "prepopulated_fields['%s'][%d]" + % (f, idx), f) + +def check_isseq(cls, label, obj): + if not isinstance(obj, (list, tuple)): + raise ImproperlyConfigured("'%s.%s' must be a list or tuple." + % (cls.__name__, label)) + +def check_isdict(cls, label, obj): + if not isinstance(obj, dict): + raise ImproperlyConfigured("'%s.%s' must be a dictionary." + % (cls.__name__, label)) + +def get_field(cls, model, opts, label, field): + try: + return opts.get_field(field) + except models.FieldDoesNotExist: + raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s'." + % (cls.__name__, label, field, model.__name__)) + +def check_formfield(cls, model, opts, label, field): + if getattr(cls.form, 'base_fields', None): + try: + cls.form.base_fields[field] + except KeyError: + raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " + "is missing from the form." % (cls.__name__, label, field)) + else: + fields = fields_for_model(model) + try: + fields[field] + except KeyError: + raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " + "is missing from the form." % (cls.__name__, label, field)) + +def fetch_attr(cls, model, opts, label, field): + try: + return opts.get_field(field) + except models.FieldDoesNotExist: + pass + try: + return getattr(model, field) + except AttributeError: + raise ImproperlyConfigured("'%s.%s' refers to '%s' that is neither a field, method or property of model '%s'." + % (cls.__name__, label, field, model.__name__)) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/decorators.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/decorators.py new file mode 100644 index 0000000..4566828 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/decorators.py @@ -0,0 +1,77 @@ +import base64 +try: + from functools import wraps +except ImportError: + from django.utils.functional import wraps # Python 2.3, 2.4 fallback. + +from django import http, template +from django.conf import settings +from django.contrib.auth.models import User +from django.contrib.auth import authenticate, login +from django.shortcuts import render_to_response +from django.utils.translation import ugettext_lazy, ugettext as _ + +ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") +LOGIN_FORM_KEY = 'this_is_the_login_form' + +def _display_login_form(request, error_message=''): + request.session.set_test_cookie() + return render_to_response('admin/login.html', { + 'title': _('Log in'), + 'app_path': request.get_full_path(), + 'error_message': error_message + }, context_instance=template.RequestContext(request)) + +def staff_member_required(view_func): + """ + Decorator for views that checks that the user is logged in and is a staff + member, displaying the login page if necessary. + """ + def _checklogin(request, *args, **kwargs): + if request.user.is_authenticated() and request.user.is_staff: + # The user is valid. Continue to the admin page. + return view_func(request, *args, **kwargs) + + assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." + + # If this isn't already the login page, display it. + if LOGIN_FORM_KEY not in request.POST: + if request.POST: + message = _("Please log in again, because your session has expired.") + else: + message = "" + return _display_login_form(request, message) + + # Check that the user accepts cookies. + if not request.session.test_cookie_worked(): + message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") + return _display_login_form(request, message) + else: + request.session.delete_test_cookie() + + # Check the password. + username = request.POST.get('username', None) + password = request.POST.get('password', None) + user = authenticate(username=username, password=password) + if user is None: + message = ERROR_MESSAGE + if '@' in username: + # Mistakenly entered e-mail address instead of username? Look it up. + users = list(User.objects.filter(email=username)) + if len(users) == 1 and users[0].check_password(password): + message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username + else: + # Either we cannot find the user, or if more than 1 + # we cannot guess which user is the correct one. + message = _("Usernames cannot contain the '@' character.") + return _display_login_form(request, message) + + # The user data is correct; log in the user in and continue. + else: + if user.is_active and user.is_staff: + login(request, user) + return http.HttpResponseRedirect(request.get_full_path()) + else: + return _display_login_form(request, ERROR_MESSAGE) + + return wraps(view_func)(_checklogin) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/main.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/main.py new file mode 100644 index 0000000..a6a206d --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/main.py @@ -0,0 +1,241 @@ +from django.contrib.admin.filterspecs import FilterSpec +from django.contrib.admin.options import IncorrectLookupParameters +from django.contrib.admin.util import quote +from django.core.paginator import Paginator, InvalidPage +from django.db import models +from django.db.models.query import QuerySet +from django.utils.encoding import force_unicode, smart_str +from django.utils.translation import ugettext +from django.utils.http import urlencode +import operator + +try: + set +except NameError: + from sets import Set as set # Python 2.3 fallback + +# The system will display a "Show all" link on the change list only if the +# total result count is less than or equal to this setting. +MAX_SHOW_ALL_ALLOWED = 200 + +# Changelist settings +ALL_VAR = 'all' +ORDER_VAR = 'o' +ORDER_TYPE_VAR = 'ot' +PAGE_VAR = 'p' +SEARCH_VAR = 'q' +TO_FIELD_VAR = 't' +IS_POPUP_VAR = 'pop' +ERROR_FLAG = 'e' + +# Text to display within change-list table cells if the value is blank. +EMPTY_CHANGELIST_VALUE = '(None)' + +class ChangeList(object): + def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, model_admin): + self.model = model + self.opts = model._meta + self.lookup_opts = self.opts + self.root_query_set = model_admin.queryset(request) + self.list_display = list_display + self.list_display_links = list_display_links + self.list_filter = list_filter + self.date_hierarchy = date_hierarchy + self.search_fields = search_fields + self.list_select_related = list_select_related + self.list_per_page = list_per_page + self.model_admin = model_admin + + # Get search parameters from the query string. + try: + self.page_num = int(request.GET.get(PAGE_VAR, 0)) + except ValueError: + self.page_num = 0 + self.show_all = ALL_VAR in request.GET + self.is_popup = IS_POPUP_VAR in request.GET + self.to_field = request.GET.get(TO_FIELD_VAR) + self.params = dict(request.GET.items()) + if PAGE_VAR in self.params: + del self.params[PAGE_VAR] + if TO_FIELD_VAR in self.params: + del self.params[TO_FIELD_VAR] + if ERROR_FLAG in self.params: + del self.params[ERROR_FLAG] + + self.order_field, self.order_type = self.get_ordering() + self.query = request.GET.get(SEARCH_VAR, '') + self.query_set = self.get_query_set() + self.get_results(request) + self.title = (self.is_popup and ugettext('Select %s') % force_unicode(self.opts.verbose_name) or ugettext('Select %s to change') % force_unicode(self.opts.verbose_name)) + self.filter_specs, self.has_filters = self.get_filters(request) + self.pk_attname = self.lookup_opts.pk.attname + + def get_filters(self, request): + filter_specs = [] + if self.list_filter: + filter_fields = [self.lookup_opts.get_field(field_name) for field_name in self.list_filter] + for f in filter_fields: + spec = FilterSpec.create(f, request, self.params, self.model, self.model_admin) + if spec and spec.has_output(): + filter_specs.append(spec) + return filter_specs, bool(filter_specs) + + def get_query_string(self, new_params=None, remove=None): + if new_params is None: new_params = {} + if remove is None: remove = [] + p = self.params.copy() + for r in remove: + for k in p.keys(): + if k.startswith(r): + del p[k] + for k, v in new_params.items(): + if v is None: + if k in p: + del p[k] + else: + p[k] = v + return '?%s' % urlencode(p) + + def get_results(self, request): + paginator = Paginator(self.query_set, self.list_per_page) + # Get the number of objects, with admin filters applied. + try: + result_count = paginator.count + # Naked except! Because we don't have any other way of validating + # "params". They might be invalid if the keyword arguments are + # incorrect, or if the values are not in the correct type (which would + # result in a database error). + except: + raise IncorrectLookupParameters + + # Get the total number of objects, with no admin filters applied. + # Perform a slight optimization: Check to see whether any filters were + # given. If not, use paginator.hits to calculate the number of objects, + # because we've already done paginator.hits and the value is cached. + if not self.query_set.query.where: + full_result_count = result_count + else: + full_result_count = self.root_query_set.count() + + can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED + multi_page = result_count > self.list_per_page + + # Get the list of objects to display on this page. + if (self.show_all and can_show_all) or not multi_page: + result_list = list(self.query_set) + else: + try: + result_list = paginator.page(self.page_num+1).object_list + except InvalidPage: + result_list = () + + self.result_count = result_count + self.full_result_count = full_result_count + self.result_list = result_list + self.can_show_all = can_show_all + self.multi_page = multi_page + self.paginator = paginator + + def get_ordering(self): + lookup_opts, params = self.lookup_opts, self.params + # For ordering, first check the "ordering" parameter in the admin + # options, then check the object's default ordering. If neither of + # those exist, order descending by ID by default. Finally, look for + # manually-specified ordering from the query string. + ordering = self.model_admin.ordering or lookup_opts.ordering or ['-' + lookup_opts.pk.name] + + if ordering[0].startswith('-'): + order_field, order_type = ordering[0][1:], 'desc' + else: + order_field, order_type = ordering[0], 'asc' + if ORDER_VAR in params: + try: + field_name = self.list_display[int(params[ORDER_VAR])] + try: + f = lookup_opts.get_field(field_name) + except models.FieldDoesNotExist: + # See whether field_name is a name of a non-field + # that allows sorting. + try: + attr = getattr(self.model, field_name) + order_field = attr.admin_order_field + except AttributeError: + pass + else: + if not isinstance(f.rel, models.ManyToOneRel) or not f.null: + order_field = f.name + except (IndexError, ValueError): + pass # Invalid ordering specified. Just use the default. + if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'): + order_type = params[ORDER_TYPE_VAR] + return order_field, order_type + + def get_query_set(self): + qs = self.root_query_set + lookup_params = self.params.copy() # a dictionary of the query string + for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR): + if i in lookup_params: + del lookup_params[i] + for key, value in lookup_params.items(): + if not isinstance(key, str): + # 'key' will be used as a keyword argument later, so Python + # requires it to be a string. + del lookup_params[key] + lookup_params[smart_str(key)] = value + + # if key ends with __in, split parameter into separate values + if key.endswith('__in'): + lookup_params[key] = value.split(',') + + # Apply lookup parameters from the query string. + qs = qs.filter(**lookup_params) + + # Use select_related() if one of the list_display options is a field + # with a relationship. + if self.list_select_related: + qs = qs.select_related() + else: + for field_name in self.list_display: + try: + f = self.lookup_opts.get_field(field_name) + except models.FieldDoesNotExist: + pass + else: + if isinstance(f.rel, models.ManyToOneRel): + qs = qs.select_related() + break + + # Set ordering. + if self.order_field: + qs = qs.order_by('%s%s' % ((self.order_type == 'desc' and '-' or ''), self.order_field)) + + # Apply keyword searches. + def construct_search(field_name): + if field_name.startswith('^'): + return "%s__istartswith" % field_name[1:] + elif field_name.startswith('='): + return "%s__iexact" % field_name[1:] + elif field_name.startswith('@'): + return "%s__search" % field_name[1:] + else: + return "%s__icontains" % field_name + + if self.search_fields and self.query: + for bit in self.query.split(): + or_queries = [models.Q(**{construct_search(field_name): bit}) for field_name in self.search_fields] + other_qs = QuerySet(self.model) + other_qs.dup_select_related(qs) + other_qs = other_qs.filter(reduce(operator.or_, or_queries)) + qs = qs & other_qs + for field_name in self.search_fields: + if '__' in field_name: + qs = qs.distinct() + break + + if self.opts.one_to_one_field: + qs = qs.complex_filter(self.opts.one_to_one_field.rel.limit_choices_to) + + return qs + + def url_for_result(self, result): + return "%s/" % quote(getattr(result, self.pk_attname)) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/template.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/template.py new file mode 100644 index 0000000..de9320b --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/views/template.py @@ -0,0 +1,77 @@ +from django import template, forms +from django.contrib.admin.views.decorators import staff_member_required +from django.template import loader +from django.shortcuts import render_to_response +from django.contrib.sites.models import Site +from django.conf import settings +from django.utils.translation import ugettext_lazy as _ + + +def template_validator(request): + """ + Displays the template validator form, which finds and displays template + syntax errors. + """ + # get a dict of {site_id : settings_module} for the validator + settings_modules = {} + for mod in settings.ADMIN_FOR: + settings_module = __import__(mod, {}, {}, ['']) + settings_modules[settings_module.SITE_ID] = settings_module + site_list = Site.objects.in_bulk(settings_modules.keys()).values() + if request.POST: + form = TemplateValidatorForm(settings_modules, site_list, + data=request.POST) + if form.is_valid(): + request.user.message_set.create(message='The template is valid.') + else: + form = TemplateValidatorForm(settings_modules, site_list) + return render_to_response('admin/template_validator.html', { + 'title': 'Template validator', + 'form': form, + }, context_instance=template.RequestContext(request)) +template_validator = staff_member_required(template_validator) + + +class TemplateValidatorForm(forms.Form): + site = forms.ChoiceField(_('site')) + template = forms.CharField( + _('template'), widget=forms.Textarea({'rows': 25, 'cols': 80})) + + def __init__(self, settings_modules, site_list, *args, **kwargs): + self.settings_modules = settings_modules + super(TemplateValidatorForm, self).__init__(*args, **kwargs) + self.fields['site'].choices = [(s.id, s.name) for s in site_list] + + def clean_template(self): + # Get the settings module. If the site isn't set, we don't raise an + # error since the site field will. + try: + site_id = int(self.cleaned_data.get('site', None)) + except (ValueError, TypeError): + return + settings_module = self.settings_modules.get(site_id, None) + if settings_module is None: + return + + # So that inheritance works in the site's context, register a new + # function for "extends" that uses the site's TEMPLATE_DIRS instead. + def new_do_extends(parser, token): + node = loader.do_extends(parser, token) + node.template_dirs = settings_module.TEMPLATE_DIRS + return node + register = template.Library() + register.tag('extends', new_do_extends) + template.builtins.append(register) + + # Now validate the template using the new TEMPLATE_DIRS, making sure to + # reset the extends function in any case. + error = None + template_string = self.cleaned_data['template'] + try: + tmpl = loader.get_template_from_string(template_string) + tmpl.render(template.Context({})) + except template.TemplateSyntaxError, e: + error = e + template.builtins.remove(register) + if error: + raise forms.ValidationError, e.args diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/widgets.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/widgets.py new file mode 100644 index 0000000..f9ddf9a --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admin/widgets.py @@ -0,0 +1,280 @@ +""" +Form Widget classes specific to the Django admin site. +""" + +import copy + +from django import forms +from django.forms.widgets import RadioFieldRenderer +from django.forms.util import flatatt +from django.utils.text import truncate_words +from django.utils.translation import ugettext as _ +from django.utils.safestring import mark_safe +from django.utils.encoding import force_unicode +from django.conf import settings + +class FilteredSelectMultiple(forms.SelectMultiple): + """ + A SelectMultiple with a JavaScript filter interface. + + Note that the resulting JavaScript assumes that the jsi18n + catalog has been loaded in the page + """ + class Media: + js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js", + settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js", + settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js") + + def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): + self.verbose_name = verbose_name + self.is_stacked = is_stacked + super(FilteredSelectMultiple, self).__init__(attrs, choices) + + def render(self, name, value, attrs=None, choices=()): + output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] + output.append(u'\n' % \ + (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX)) + return mark_safe(u''.join(output)) + +class AdminDateWidget(forms.TextInput): + class Media: + js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", + settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") + + def __init__(self, attrs={}): + super(AdminDateWidget, self).__init__(attrs={'class': 'vDateField', 'size': '10'}) + +class AdminTimeWidget(forms.TextInput): + class Media: + js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", + settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") + + def __init__(self, attrs={}): + super(AdminTimeWidget, self).__init__(attrs={'class': 'vTimeField', 'size': '8'}) + +class AdminSplitDateTime(forms.SplitDateTimeWidget): + """ + A SplitDateTime Widget that has some admin-specific styling. + """ + def __init__(self, attrs=None): + widgets = [AdminDateWidget, AdminTimeWidget] + # Note that we're calling MultiWidget, not SplitDateTimeWidget, because + # we want to define widgets. + forms.MultiWidget.__init__(self, widgets, attrs) + + def format_output(self, rendered_widgets): + return mark_safe(u'

    %s %s
    %s %s

    ' % \ + (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])) + +class AdminRadioFieldRenderer(RadioFieldRenderer): + def render(self): + """Outputs a
      for this set of radio fields.""" + return mark_safe(u'\n%s\n
    ' % ( + flatatt(self.attrs), + u'\n'.join([u'
  • %s
  • ' % force_unicode(w) for w in self])) + ) + +class AdminRadioSelect(forms.RadioSelect): + renderer = AdminRadioFieldRenderer + +class AdminFileWidget(forms.FileInput): + """ + A FileField Widget that shows its current value if it has one. + """ + def __init__(self, attrs={}): + super(AdminFileWidget, self).__init__(attrs) + + def render(self, name, value, attrs=None): + output = [] + if value and hasattr(value, "url"): + output.append('%s %s
    %s ' % \ + (_('Currently:'), value.url, value, _('Change:'))) + output.append(super(AdminFileWidget, self).render(name, value, attrs)) + return mark_safe(u''.join(output)) + +class ForeignKeyRawIdWidget(forms.TextInput): + """ + A Widget for displaying ForeignKeys in the "raw_id" interface rather than + in a box. + """ + def __init__(self, rel, attrs=None): + super(ManyToManyRawIdWidget, self).__init__(rel, attrs) + + def render(self, name, value, attrs=None): + attrs['class'] = 'vManyToManyRawIdAdminField' + if value: + value = ','.join([str(v) for v in value]) + else: + value = '' + return super(ManyToManyRawIdWidget, self).render(name, value, attrs) + + def url_parameters(self): + return self.base_url_parameters() + + def label_for_value(self, value): + return '' + + def value_from_datadict(self, data, files, name): + value = data.get(name, None) + if value and ',' in value: + return data[name].split(',') + if value: + return [value] + return None + + def _has_changed(self, initial, data): + if initial is None: + initial = [] + if data is None: + data = [] + if len(initial) != len(data): + return True + for pk1, pk2 in zip(initial, data): + if force_unicode(pk1) != force_unicode(pk2): + return True + return False + +class RelatedFieldWidgetWrapper(forms.Widget): + """ + This class is a wrapper to a given widget to add the add icon for the + admin interface. + """ + def __init__(self, widget, rel, admin_site): + self.is_hidden = widget.is_hidden + self.needs_multipart_form = widget.needs_multipart_form + self.attrs = widget.attrs + self.choices = widget.choices + self.widget = widget + self.rel = rel + # so we can check if the related object is registered with this AdminSite + self.admin_site = admin_site + + def __deepcopy__(self, memo): + obj = copy.copy(self) + obj.widget = copy.deepcopy(self.widget, memo) + obj.attrs = self.widget.attrs + memo[id(self)] = obj + return obj + + def _media(self): + return self.widget.media + media = property(_media) + + def render(self, name, value, *args, **kwargs): + rel_to = self.rel.to + related_url = '../../../%s/%s/' % (rel_to._meta.app_label, rel_to._meta.object_name.lower()) + self.widget.choices = self.choices + output = [self.widget.render(name, value, *args, **kwargs)] + if rel_to in self.admin_site._registry: # If the related object has an admin interface: + # TODO: "id_" is hard-coded here. This should instead use the correct + # API to determine the ID dynamically. + output.append(u' ' % \ + (related_url, name)) + output.append(u'%s' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another'))) + return mark_safe(u''.join(output)) + + def build_attrs(self, extra_attrs=None, **kwargs): + "Helper function for building an attribute dictionary." + self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) + return self.attrs + + def value_from_datadict(self, data, files, name): + return self.widget.value_from_datadict(data, files, name) + + def _has_changed(self, initial, data): + return self.widget._has_changed(initial, data) + + def id_for_label(self, id_): + return self.widget.id_for_label(id_) + +class AdminTextareaWidget(forms.Textarea): + def __init__(self, attrs=None): + final_attrs = {'class': 'vLargeTextField'} + if attrs is not None: + final_attrs.update(attrs) + super(AdminTextareaWidget, self).__init__(attrs=final_attrs) + +class AdminTextInputWidget(forms.TextInput): + def __init__(self, attrs=None): + final_attrs = {'class': 'vTextField'} + if attrs is not None: + final_attrs.update(attrs) + super(AdminTextInputWidget, self).__init__(attrs=final_attrs) + +class AdminURLFieldWidget(forms.TextInput): + def __init__(self, attrs=None): + final_attrs = {'class': 'vURLField'} + if attrs is not None: + final_attrs.update(attrs) + super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) + +class AdminIntegerFieldWidget(forms.TextInput): + def __init__(self, attrs=None): + final_attrs = {'class': 'vIntegerField'} + if attrs is not None: + final_attrs.update(attrs) + super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) + +class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): + def __init__(self, attrs=None): + final_attrs = {'class': 'vCommaSeparatedIntegerField'} + if attrs is not None: + final_attrs.update(attrs) + super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs) diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admindocs/__init__.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admindocs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admindocs/urls.py b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admindocs/urls.py new file mode 100644 index 0000000..57edb56 --- /dev/null +++ b/Django-1.0/build/lib.linux-x86_64-2.7/django/contrib/admindocs/urls.py @@ -0,0 +1,41 @@ +from django.conf.urls.defaults import * +from django.contrib.admindocs import views + +urlpatterns = patterns('', + url('^$', + views.doc_index, + name='django-admindocs-docroot' + ), + url('^bookmarklets/$', + views.bookmarklets, + name='django-admindocs-bookmarklets' + ), + url('^tags/$', + views.template_tag_index, + name='django-admindocs-tags' + ), + url('^filters/$', + views.template_filter_index, + name='django-admindocs-filters' + ), + url('^views/$', + views.view_index, + name='django-admindocs-views-index' + ), + url('^views/(?P[^/]+)/$', + views.view_detail, + name='django-admindocs-views-detail' + ), + url('^models/$', + views.model_index, + name='django-admindocs-models-index' + ), + url('^models/(?P[^\.]+)\.(?P[^/]+)/$', + views.model_detail, + name='django-admindocs-models-detail' + ), + url('^templates/(?P