code
stringlengths
1
1.72M
language
stringclasses
1 value
"""Refactored "safe reference" from dispatcher.py""" import weakref, traceback def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target target -- the object to be weakly referenced, if it's a bound method reference, will create a BoundMethodWeakref, otherwise creates a simple weakref. onDelete -- if provided, will have a hard reference stored to the callable to be called after the safe reference goes out of scope with the reference object, (either a weakref or a BoundMethodWeakref) as argument. """ if hasattr(target, 'im_self'): if target.im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). assert hasattr(target, 'im_func'), """safeRef target %r has im_self, but no im_func, don't know how to create reference"""%( target,) reference = BoundMethodWeakref( target=target, onDelete=onDelete ) return reference if callable(onDelete): return weakref.ref(target, onDelete) else: return weakref.ref( target ) class BoundMethodWeakref(object): """'Safe' and reusable weak references to instance methods BoundMethodWeakref objects provide a mechanism for referencing a bound method without requiring that the method object itself (which is normally a transient object) is kept alive. Instead, the BoundMethodWeakref object keeps weak references to both the object and the function which together define the instance method. Attributes: key -- the identity key for the reference, calculated by the class's calculateKey method applied to the target instance method deletionMethods -- sequence of callable objects taking single argument, a reference to this object which will be called when *either* the target object or target function is garbage collected (i.e. when this object becomes invalid). These are specified as the onDelete parameters of safeRef calls. weakSelf -- weak reference to the target object weakFunc -- weak reference to the target function Class Attributes: _allInstances -- class attribute pointing to all live BoundMethodWeakref objects indexed by the class's calculateKey(target) method applied to the target objects. This weak value dictionary is used to short-circuit creation so that multiple references to the same (object, function) pair produce the same BoundMethodWeakref instance. """ _allInstances = weakref.WeakValueDictionary() def __new__( cls, target, onDelete=None, *arguments,**named ): """Create new instance or return current instance Basically this method of construction allows us to short-circuit creation of references to already- referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletionMethods attribute updated. Otherwise the new instance is created and registered in the table of already-referenced methods. """ key = cls.calculateKey(target) current =cls._allInstances.get(key) if current is not None: current.deletionMethods.append( onDelete) return current else: base = super( BoundMethodWeakref, cls).__new__( cls ) cls._allInstances[key] = base base.__init__( target, onDelete, *arguments,**named) return base def __init__(self, target, onDelete=None): """Return a weak-reference-like instance for a bound method target -- the instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via: target.im_func.__get__( target.im_self ) which is true of built-in instance methods. onDelete -- optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object. """ def remove(weak, self=self): """Set self.isDead to true when method or instance is destroyed""" methods = self.deletionMethods[:] del self.deletionMethods[:] try: del self.__class__._allInstances[ self.key ] except KeyError: pass for function in methods: try: if callable( function ): function( self ) except Exception, e: try: traceback.print_exc() except AttributeError, err: print '''Exception during saferef %s cleanup function %s: %s'''%( self, function, e ) self.deletionMethods = [onDelete] self.key = self.calculateKey( target ) self.weakSelf = weakref.ref(target.im_self, remove) self.weakFunc = weakref.ref(target.im_func, remove) self.selfName = str(target.im_self) self.funcName = str(target.im_func.__name__) def calculateKey( cls, target ): """Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target function respectively. """ return (id(target.im_self),id(target.im_func)) calculateKey = classmethod( calculateKey ) def __str__(self): """Give a friendly representation of the object""" return """%s( %s.%s )"""%( self.__class__.__name__, self.selfName, self.funcName, ) __repr__ = __str__ def __nonzero__( self ): """Whether we are still a valid reference""" return self() is not None def __cmp__( self, other ): """Compare with another reference""" if not isinstance (other,self.__class__): return cmp( self.__class__, type(other) ) return cmp( self.key, other.key) def __call__(self): """Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weakSelf() if target is not None: function = self.weakFunc() if function is not None: return function.__get__(target) return None
Python
"""Robust apply mechanism Provides a function "call", which can sort out what arguments a given callable object can take, and subset the given arguments to match only those which are acceptable. """ def function( receiver ): """Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound """ if hasattr(receiver, '__call__'): # receiver is a class instance; assume it is callable. # Reassign receiver to the actual method that will be called. if hasattr( receiver.__call__, 'im_func') or hasattr( receiver.__call__, 'im_code'): receiver = receiver.__call__ if hasattr( receiver, 'im_func' ): # an instance-method... return receiver, receiver.im_func.func_code, 1 elif not hasattr( receiver, 'func_code'): raise ValueError('unknown reciever type %s %s'%(receiver, type(receiver))) return receiver, receiver.func_code, 0 def robustApply(receiver, *arguments, **named): """Call receiver with arguments and an appropriate subset of named """ receiver, codeObject, startIndex = function( receiver ) acceptable = codeObject.co_varnames[startIndex+len(arguments):codeObject.co_argcount] for name in codeObject.co_varnames[startIndex:startIndex+len(arguments)]: if named.has_key( name ): raise TypeError( """Argument %r specified both positionally and as a keyword for calling %r"""% ( name, receiver, ) ) if not (codeObject.co_flags & 8): # fc does not have a **kwds type parameter, therefore # remove unacceptable arguments. for arg in named.keys(): if arg not in acceptable: del named[arg] return receiver(*arguments, **named)
Python
"""Multiple-producer-multiple-consumer signal-dispatching dispatcher is the core of the PyDispatcher system, providing the primary API and the core logic for the system. Module attributes of note: Any -- Singleton used to signal either "Any Sender" or "Any Signal". See documentation of the _Any class. Anonymous -- Singleton used to signal "Anonymous Sender" See documentation of the _Anonymous class. Internal attributes: WEAKREF_TYPES -- tuple of types/classes which represent weak references to receivers, and thus must be de- referenced on retrieval to retrieve the callable object connections -- { senderkey (id) : { signal : [receivers...]}} senders -- { senderkey (id) : weakref(sender) } used for cleaning up sender references on sender deletion sendersBack -- { receiverkey (id) : [senderkey (id)...] } used for cleaning up receiver references on receiver deletion, (considerably speeds up the cleanup process vs. the original code.) """ import types, weakref from django.dispatch import saferef, robustapply, errors __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>" __cvsid__ = "$Id: dispatcher.py,v 1.9 2005/09/17 04:55:57 mcfletch Exp $" __version__ = "$Revision: 1.9 $"[11:-2] class _Parameter: """Used to represent default parameter values.""" def __repr__(self): return self.__class__.__name__ class _Any(_Parameter): """Singleton used to signal either "Any Sender" or "Any Signal" The Any object can be used with connect, disconnect, send, or sendExact to signal that the parameter given Any should react to all senders/signals, not just a particular sender/signal. """ Any = _Any() class _Anonymous(_Parameter): """Singleton used to signal "Anonymous Sender" The Anonymous object is used to signal that the sender of a message is not specified (as distinct from being "any sender"). Registering callbacks for Anonymous will only receive messages sent without senders. Sending with anonymous will only send messages to those receivers registered for Any or Anonymous. Note: The default sender for connect is Any, while the default sender for send is Anonymous. This has the effect that if you do not specify any senders in either function then all messages are routed as though there was a single sender (Anonymous) being used everywhere. """ Anonymous = _Anonymous() WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref) connections = {} senders = {} sendersBack = {} def connect(receiver, signal=Any, sender=Any, weak=True): """Connect receiver to sender for signal receiver -- a callable Python object which is to receive messages/signals/events. Receivers must be hashable objects. if weak is True, then receiver must be weak-referencable (more precisely saferef.safeRef() must be able to create a reference to the receiver). Receivers are fairly flexible in their specification, as the machinery in the robustApply module takes care of most of the details regarding figuring out appropriate subsets of the sent arguments to apply to a given receiver. Note: if receiver is itself a weak reference (a callable), it will be de-referenced by the system's machinery, so *generally* weak references are not suitable as receivers, though some use might be found for the facility whereby a higher-level library passes in pre-weakrefed receiver references. signal -- the signal to which the receiver should respond if Any, receiver will receive any signal from the indicated sender (which might also be Any, but is not necessarily Any). Otherwise must be a hashable Python object other than None (DispatcherError raised on None). sender -- the sender to which the receiver should respond if Any, receiver will receive the indicated signals from any sender. if Anonymous, receiver will only receive indicated signals from send/sendExact which do not specify a sender, or specify Anonymous explicitly as the sender. Otherwise can be any python object. weak -- whether to use weak references to the receiver By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. returns None, may raise DispatcherTypeError """ if signal is None: raise errors.DispatcherTypeError( 'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender) ) if weak: receiver = saferef.safeRef(receiver, onDelete=_removeReceiver) senderkey = id(sender) signals = connections.setdefault(senderkey, {}) # Keep track of senders for cleanup. # Is Anonymous something we want to clean up? if sender not in (None, Anonymous, Any): def remove(object, senderkey=senderkey): _removeSender(senderkey=senderkey) # Skip objects that can not be weakly referenced, which means # they won't be automatically cleaned up, but that's too bad. try: weakSender = weakref.ref(sender, remove) senders[senderkey] = weakSender except: pass receiverID = id(receiver) # get current set, remove any current references to # this receiver in the set, including back-references if signals.has_key(signal): receivers = signals[signal] _removeOldBackRefs(senderkey, signal, receiver, receivers) else: receivers = signals[signal] = [] try: current = sendersBack.get( receiverID ) if current is None: sendersBack[ receiverID ] = current = [] if senderkey not in current: current.append(senderkey) except: pass receivers.append(receiver) def disconnect(receiver, signal=Any, sender=Any, weak=True): """Disconnect receiver from sender for signal receiver -- the registered receiver to disconnect signal -- the registered signal to disconnect sender -- the registered sender to disconnect weak -- the weakref state to disconnect disconnect reverses the process of connect, the semantics for the individual elements are logically equivalent to a tuple of (receiver, signal, sender, weak) used as a key to be deleted from the internal routing tables. (The actual process is slightly more complex but the semantics are basically the same). Note: Using disconnect is not required to cleanup routing when an object is deleted, the framework will remove routes for deleted objects automatically. It's only necessary to disconnect if you want to stop routing to a live object. returns None, may raise DispatcherTypeError or DispatcherKeyError """ if signal is None: raise errors.DispatcherTypeError( 'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender) ) if weak: receiver = saferef.safeRef(receiver) senderkey = id(sender) try: signals = connections[senderkey] receivers = signals[signal] except KeyError: raise errors.DispatcherKeyError( """No receivers found for signal %r from sender %r""" %( signal, sender ) ) try: # also removes from receivers _removeOldBackRefs(senderkey, signal, receiver, receivers) except ValueError: raise errors.DispatcherKeyError( """No connection to receiver %s for signal %s from sender %s""" %( receiver, signal, sender ) ) _cleanupConnections(senderkey, signal) def getReceivers( sender = Any, signal = Any ): """Get list of receivers from global tables This utility function allows you to retrieve the raw list of receivers from the connections table for the given sender and signal pair. Note: there is no guarantee that this is the actual list stored in the connections table, so the value should be treated as a simple iterable/truth value rather than, for instance a list to which you might append new records. Normally you would use liveReceivers( getReceivers( ...)) to retrieve the actual receiver objects as an iterable object. """ existing = connections.get(id(sender)) if existing is not None: return existing.get(signal, []) return [] def liveReceivers(receivers): """Filter sequence of receivers to get resolved, live receivers This is a generator which will iterate over the passed sequence, checking for weak references and resolving them, then returning all live receivers. """ for receiver in receivers: if isinstance( receiver, WEAKREF_TYPES): # Dereference the weak reference. receiver = receiver() if receiver is not None: yield receiver else: yield receiver def getAllReceivers( sender = Any, signal = Any ): """Get list of all receivers from global tables This gets all dereferenced receivers which should receive the given signal from sender, each receiver should be produced only once by the resulting generator """ receivers = {} # Get receivers that receive *this* signal from *this* sender. # Add receivers that receive *any* signal from *this* sender. # Add receivers that receive *this* signal from *any* sender. # Add receivers that receive *any* signal from *any* sender. l = [] i = id(sender) if i in connections: sender_receivers = connections[i] if signal in sender_receivers: l.extend(sender_receivers[signal]) if signal is not Any and Any in sender_receivers: l.extend(sender_receivers[Any]) if sender is not Any: i = id(Any) if i in connections: sender_receivers = connections[i] if sender_receivers is not None: if signal in sender_receivers: l.extend(sender_receivers[signal]) if signal is not Any and Any in sender_receivers: l.extend(sender_receivers[Any]) for receiver in l: try: if not receiver in receivers: if isinstance(receiver, WEAKREF_TYPES): receiver = receiver() # this should only (rough guess) be possible if somehow, deref'ing # triggered a wipe. if receiver is None: continue receivers[receiver] = 1 yield receiver except TypeError: # dead weakrefs raise TypeError on hash... pass def send(signal=Any, sender=Anonymous, *arguments, **named): """Send signal from sender to all connected receivers. signal -- (hashable) signal value, see connect for details sender -- the sender of the signal if Any, only receivers registered for Any will receive the message. if Anonymous, only receivers registered to receive messages from Anonymous or Any will receive the message Otherwise can be any python object (normally one registered with a connect if you actually want something to occur). arguments -- positional arguments which will be passed to *all* receivers. Note that this may raise TypeErrors if the receivers do not allow the particular arguments. Note also that arguments are applied before named arguments, so they should be used with care. named -- named arguments which will be filtered according to the parameters of the receivers to only provide those acceptable to the receiver. Return a list of tuple pairs [(receiver, response), ... ] if any receiver raises an error, the error propagates back through send, terminating the dispatch loop, so it is quite possible to not have all receivers called if a raises an error. """ # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. responses = [] for receiver in getAllReceivers(sender, signal): response = robustapply.robustApply( receiver, signal=signal, sender=sender, *arguments, **named ) responses.append((receiver, response)) return responses def sendExact( signal=Any, sender=Anonymous, *arguments, **named ): """Send signal only to those receivers registered for exact message sendExact allows for avoiding Any/Anonymous registered handlers, sending only to those receivers explicitly registered for a particular signal on a particular sender. """ responses = [] for receiver in liveReceivers(getReceivers(sender, signal)): response = robustapply.robustApply( receiver, signal=signal, sender=sender, *arguments, **named ) responses.append((receiver, response)) return responses def _removeReceiver(receiver): """Remove receiver from connections.""" if not sendersBack: # During module cleanup the mapping will be replaced with None return False backKey = id(receiver) for senderkey in sendersBack.get(backKey,()): try: signals = connections[senderkey].keys() except KeyError,err: pass else: for signal in signals: try: receivers = connections[senderkey][signal] except KeyError: pass else: try: receivers.remove( receiver ) except Exception, err: pass _cleanupConnections(senderkey, signal) try: del sendersBack[ backKey ] except KeyError: pass def _cleanupConnections(senderkey, signal): """Delete any empty signals for senderkey. Delete senderkey if empty.""" try: receivers = connections[senderkey][signal] except: pass else: if not receivers: # No more connected receivers. Therefore, remove the signal. try: signals = connections[senderkey] except KeyError: pass else: del signals[signal] if not signals: # No more signal connections. Therefore, remove the sender. _removeSender(senderkey) def _removeSender(senderkey): """Remove senderkey from connections.""" _removeBackrefs(senderkey) connections.pop(senderkey, None) senders.pop(senderkey, None) def _removeBackrefs( senderkey): """Remove all back-references to this senderkey""" for receiver_list in connections.pop(senderkey, {}).values(): for receiver in receiver_list: _killBackref( receiver, senderkey ) def _removeOldBackRefs(senderkey, signal, receiver, receivers): """Kill old sendersBack references from receiver This guards against multiple registration of the same receiver for a given signal and sender leaking memory as old back reference records build up. Also removes old receiver instance from receivers """ try: index = receivers.index(receiver) # need to scan back references here and remove senderkey except ValueError: return False else: oldReceiver = receivers[index] del receivers[index] found = 0 signals = connections.get(signal) if signals is not None: for sig,recs in connections.get(signal,{}).iteritems(): if sig != signal: for rec in recs: if rec is oldReceiver: found = 1 break if not found: _killBackref( oldReceiver, senderkey ) return True return False def _killBackref( receiver, senderkey ): """Do the actual removal of back reference from receiver to senderkey""" receiverkey = id(receiver) receivers_list = sendersBack.get( receiverkey, () ) while senderkey in receivers_list: try: receivers_list.remove( senderkey ) except: break if not receivers_list: try: del sendersBack[ receiverkey ] except KeyError: pass return True
Python
"""Module implementing error-catching version of send (sendRobust)""" from django.dispatch.dispatcher import Any, Anonymous, liveReceivers, getAllReceivers from django.dispatch.robustapply import robustApply def sendRobust( signal=Any, sender=Anonymous, *arguments, **named ): """Send signal from sender to all connected receivers catching errors signal -- (hashable) signal value, see connect for details sender -- the sender of the signal if Any, only receivers registered for Any will receive the message. if Anonymous, only receivers registered to receive messages from Anonymous or Any will receive the message Otherwise can be any python object (normally one registered with a connect if you actually want something to occur). arguments -- positional arguments which will be passed to *all* receivers. Note that this may raise TypeErrors if the receivers do not allow the particular arguments. Note also that arguments are applied before named arguments, so they should be used with care. named -- named arguments which will be filtered according to the parameters of the receivers to only provide those acceptable to the receiver. Return a list of tuple pairs [(receiver, response), ... ] if any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. """ # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. responses = [] for receiver in liveReceivers(getAllReceivers(sender, signal)): try: response = robustApply( receiver, signal=signal, sender=sender, *arguments, **named ) except Exception, err: responses.append((receiver, err)) else: responses.append((receiver, response)) return responses
Python
"""Error types for dispatcher mechanism """ class DispatcherError(Exception): """Base class for all Dispatcher errors""" class DispatcherKeyError(KeyError, DispatcherError): """Error raised when unknown (sender,signal) set specified""" class DispatcherTypeError(TypeError, DispatcherError): """Error raised when inappropriate signal-type specified (None)"""
Python
"""Multi-consumer multi-producer dispatching mechanism """ __version__ = "1.0.0" __author__ = "Patrick K. O'Brien" __license__ = "BSD-style, see license.txt for details"
Python
from django.db import models from django.contrib.sites.models import Site from django.utils.translation import gettext_lazy as _ class Redirect(models.Model): site = models.ForeignKey(Site, radio_admin=models.VERTICAL) old_path = models.CharField(_('redirect from'), maxlength=200, db_index=True, help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'.")) new_path = models.CharField(_('redirect to'), maxlength=200, blank=True, help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'.")) class Meta: verbose_name = _('redirect') verbose_name_plural = _('redirects') db_table = 'django_redirect' unique_together=(('site', 'old_path'),) ordering = ('old_path',) class Admin: list_filter = ('site',) search_fields = ('old_path', 'new_path') def __str__(self): return "%s ---> %s" % (self.old_path, self.new_path)
Python
from django.contrib.redirects.models import Redirect from django import http from django.conf import settings class RedirectFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. path = request.get_full_path() try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path) except Redirect.DoesNotExist: r = None if r is None and settings.APPEND_SLASH: # Try removing the trailing slash. try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:]) except Redirect.DoesNotExist: pass if r is not None: if r == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
Python
""" USA-specific Form helpers """ from django.newforms import ValidationError from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES from django.newforms.util import smart_unicode from django.utils.translation import gettext import re phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$') class USZipCodeField(RegexField): def __init__(self, *args, **kwargs): super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$', max_length=None, min_length=None, error_message=gettext(u'Enter a zip code in the format XXXXX or XXXXX-XXXX.'), *args, **kwargs) class USPhoneNumberField(Field): def clean(self, value): super(USPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(u'Phone numbers must be in XXX-XXX-XXXX format.') class USStateField(Field): """ A form field that validates its input is a U.S. state name or abbreviation. It normalizes the input to the standard two-leter postal service abbreviation for the given state. """ def clean(self, value): from us_states import STATES_NORMALIZED # relative import super(USStateField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().lower() except AttributeError: pass else: try: return STATES_NORMALIZED[value.strip().lower()].decode('ascii') except KeyError: pass raise ValidationError(u'Enter a U.S. state or territory.') class USStateSelect(Select): """ A Select widget that uses a list of U.S. states/territories as its choices. """ def __init__(self, attrs=None): from us_states import STATE_CHOICES # relative import super(USStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
Python
""" A mapping of state misspellings/abbreviations to normalized abbreviations, and an alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('AL', 'Alabama'), ('AK', 'Alaska'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Deleware'), ('DC', 'District of Columbia'), ('FM', 'Federated States of Micronesia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MH', 'Marshall Islands'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('MP', 'Northern Mariana Islands'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PW', 'Palau'), ('PA', 'Pennsylvania'), ('PR', 'Puerto Rico'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VI', 'Virgin Islands'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming'), ) STATES_NORMALIZED = { 'ak': 'AK', 'al': 'AL', 'ala': 'AL', 'alabama': 'AL', 'alaska': 'AK', 'american samao': 'AS', 'american samoa': 'AS', 'ar': 'AR', 'ariz': 'AZ', 'arizona': 'AZ', 'ark': 'AR', 'arkansas': 'AR', 'as': 'AS', 'az': 'AZ', 'ca': 'CA', 'calf': 'CA', 'calif': 'CA', 'california': 'CA', 'co': 'CO', 'colo': 'CO', 'colorado': 'CO', 'conn': 'CT', 'connecticut': 'CT', 'ct': 'CT', 'dc': 'DC', 'de': 'DE', 'del': 'DE', 'delaware': 'DE', 'district of columbia': 'DC', 'federated states of micronesia': 'FM', 'fl': 'FL', 'fla': 'FL', 'florida': 'FL', 'fm': 'FM', 'ga': 'GA', 'georgia': 'GA', 'gu': 'GU', 'guam': 'GU', 'hawaii': 'HI', 'hi': 'HI', 'ia': 'IA', 'id': 'ID', 'idaho': 'ID', 'il': 'IL', 'ill': 'IL', 'illinois': 'IL', 'in': 'IN', 'ind': 'IN', 'indiana': 'IN', 'iowa': 'IA', 'kan': 'KS', 'kans': 'KS', 'kansas': 'KS', 'kentucky': 'KY', 'ks': 'KS', 'ky': 'KY', 'la': 'LA', 'louisiana': 'LA', 'ma': 'MA', 'maine': 'ME', 'marianas islands': 'MP', 'marianas islands of the pacific': 'MP', 'marinas islands of the pacific': 'MP', 'maryland': 'MD', 'mass': 'MA', 'massachusetts': 'MA', 'massachussetts': 'MA', 'md': 'MD', 'me': 'ME', 'mi': 'MI', 'mich': 'MI', 'michigan': 'MI', 'micronesia': 'FM', 'minn': 'MN', 'minnesota': 'MN', 'miss': 'MS', 'mississippi': 'MS', 'missouri': 'MO', 'mn': 'MN', 'mo': 'MO', 'mont': 'MT', 'montana': 'MT', 'mp': 'MP', 'ms': 'MS', 'mt': 'MT', 'n d': 'ND', 'n dak': 'ND', 'n h': 'NH', 'n j': 'NJ', 'n m': 'NM', 'n mex': 'NM', 'nc': 'NC', 'nd': 'ND', 'ne': 'NE', 'neb': 'NE', 'nebr': 'NE', 'nebraska': 'NE', 'nev': 'NV', 'nevada': 'NV', 'new hampshire': 'NH', 'new jersey': 'NJ', 'new mexico': 'NM', 'new york': 'NY', 'nh': 'NH', 'nj': 'NJ', 'nm': 'NM', 'nmex': 'NM', 'north carolina': 'NC', 'north dakota': 'ND', 'northern mariana islands': 'MP', 'nv': 'NV', 'ny': 'NY', 'oh': 'OH', 'ohio': 'OH', 'ok': 'OK', 'okla': 'OK', 'oklahoma': 'OK', 'or': 'OR', 'ore': 'OR', 'oreg': 'OR', 'oregon': 'OR', 'pa': 'PA', 'penn': 'PA', 'pennsylvania': 'PA', 'pr': 'PR', 'puerto rico': 'PR', 'rhode island': 'RI', 'ri': 'RI', 's dak': 'SD', 'sc': 'SC', 'sd': 'SD', 'sdak': 'SD', 'south carolina': 'SC', 'south dakota': 'SD', 'tenn': 'TN', 'tennessee': 'TN', 'territory of hawaii': 'HI', 'tex': 'TX', 'texas': 'TX', 'tn': 'TN', 'tx': 'TX', 'us virgin islands': 'VI', 'usvi': 'VI', 'ut': 'UT', 'utah': 'UT', 'va': 'VA', 'vermont': 'VT', 'vi': 'VI', 'viginia': 'VA', 'virgin islands': 'VI', 'virgina': 'VA', 'virginia': 'VA', 'vt': 'VT', 'w va': 'WV', 'wa': 'WA', 'wash': 'WA', 'washington': 'WA', 'west virginia': 'WV', 'wi': 'WI', 'wis': 'WI', 'wisc': 'WI', 'wisconsin': 'WI', 'wv': 'WV', 'wva': 'WV', 'wy': 'WY', 'wyo': 'WY', 'wyoming': 'WY', }
Python
""" UK-specific Form helpers """ from django.newforms.fields import RegexField from django.utils.translation import gettext class UKPostcodeField(RegexField): """ A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd """ def __init__(self, *args, **kwargs): super(UKPostcodeField, self).__init__(r'^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW]) [0-9][ABD-HJLNP-UW-Z]{2})$', max_length=None, min_length=None, error_message=gettext(u'Enter a postcode. A space is required between the two postcode parts.'), *args, **kwargs)
Python
from django.conf import settings from django.db import models from django.db.models.fields import FieldDoesNotExist class CurrentSiteManager(models.Manager): "Use this to limit objects to those associated with the current site." def __init__(self, field_name='site'): super(CurrentSiteManager, self).__init__() self.__field_name = field_name self.__is_validated = False def get_query_set(self): if not self.__is_validated: try: self.model._meta.get_field(self.__field_name) except FieldDoesNotExist: raise ValueError, "%s couldn't find a field named %s in %s." % \ (self.__class__.__name__, self.__field_name, self.model._meta.object_name) self.__is_validated = True return super(CurrentSiteManager, self).get_query_set().filter(**{self.__field_name + '__id__exact': settings.SITE_ID})
Python
from django.db import models from django.utils.translation import gettext_lazy as _ class SiteManager(models.Manager): def get_current(self): from django.conf import settings return self.get(pk=settings.SITE_ID) class Site(models.Model): domain = models.CharField(_('domain name'), maxlength=100) name = models.CharField(_('display name'), maxlength=50) objects = SiteManager() class Meta: db_table = 'django_site' verbose_name = _('site') verbose_name_plural = _('sites') ordering = ('domain',) class Admin: list_display = ('domain', 'name') search_fields = ('domain', 'name') def __str__(self): return self.domain
Python
""" Creates the default Site object. """ from django.dispatch import dispatcher from django.db.models import signals from django.contrib.sites.models import Site from django.contrib.sites import models as site_app def create_default_site(app, created_models, verbosity): if Site in created_models: if verbosity >= 2: print "Creating example.com Site object" s = Site(domain="example.com", name="example.com") s.save() dispatcher.connect(create_default_site, sender=site_app, signal=signals.post_syncdb)
Python
""" Set of "markup" template filters for Django. These filters transform plain text markup syntaxes to HTML; currently there is support for: * Textile, which requires the PyTextile library available at http://dealmeida.net/projects/textile/ * Markdown, which requires the Python-markdown library from http://www.freewisdom.org/projects/python-markdown * ReStructuredText, which requires docutils from http://docutils.sf.net/ In each case, if the required library is not installed, the filter will silently fail and return the un-marked-up text. """ from django import template from django.conf import settings register = template.Library() def textile(value): try: import textile except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError, "Error in {% textile %} filter: The Python textile library isn't installed." return value else: return textile.textile(value, encoding=settings.DEFAULT_CHARSET, output=settings.DEFAULT_CHARSET) def markdown(value): try: import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed." return value else: return markdown.markdown(value) def restructuredtext(value): try: from docutils.core import publish_parts except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError, "Error in {% restructuredtext %} filter: The Python docutils library isn't installed." return value else: docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {}) parts = publish_parts(source=value, writer_name="html4css1", settings_overrides=docutils_settings) return parts["fragment"] register.filter(textile) register.filter(markdown) register.filter(restructuredtext)
Python
from django.db import models from django.utils.translation import gettext_lazy as _ CONTENT_TYPE_CACHE = {} class ContentTypeManager(models.Manager): def get_for_model(self, model): """ Returns the ContentType object for the given model, creating the ContentType if necessary. """ opts = model._meta key = (opts.app_label, opts.object_name.lower()) try: ct = CONTENT_TYPE_CACHE[key] except KeyError: # The str() is needed around opts.verbose_name because it's a # django.utils.functional.__proxy__ object. ct, created = self.model._default_manager.get_or_create(app_label=key[0], model=key[1], defaults={'name': str(opts.verbose_name)}) CONTENT_TYPE_CACHE[key] = ct return ct def clear_cache(self): """ Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.create_contenttypes for where this gets called). """ global CONTENT_TYPE_CACHE CONTENT_TYPE_CACHE = {} class ContentType(models.Model): name = models.CharField(maxlength=100) app_label = models.CharField(maxlength=100) model = models.CharField(_('python model class name'), maxlength=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'django_content_type' ordering = ('name',) unique_together = (('app_label', 'model'),) def __str__(self): return self.name def model_class(self): "Returns the Python model class for this type of content." from django.db import models return models.get_model(self.app_label, self.model) def get_object_for_this_type(self, **kwargs): """ Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it. """ return self.model_class()._default_manager.get(**kwargs)
Python
""" Creates content types for all installed models. """ from django.dispatch import dispatcher from django.db.models import get_apps, get_models, signals def create_contenttypes(app, created_models, verbosity=2): from django.contrib.contenttypes.models import ContentType ContentType.objects.clear_cache() app_models = get_models(app) if not app_models: return for klass in app_models: opts = klass._meta try: ContentType.objects.get(app_label=opts.app_label, model=opts.object_name.lower()) except ContentType.DoesNotExist: ct = ContentType(name=str(opts.verbose_name), app_label=opts.app_label, model=opts.object_name.lower()) ct.save() if verbosity >= 2: print "Adding content type '%s | %s'" % (ct.app_label, ct.model) def create_all_contenttypes(verbosity=2): for app in get_apps(): create_contenttypes(app, None, verbosity) dispatcher.connect(create_contenttypes, signal=signals.post_syncdb) if __name__ == "__main__": create_all_contenttypes()
Python
""" Formtools Preview application. This is an abstraction of the following workflow: "Display an HTML form, force a preview, then do something with the submission." Given a django.newforms.Form object that you define, this takes care of the following: * Displays the form as HTML on a Web page. * Validates the form data once it's submitted via POST. * If it's valid, displays a preview page. * If it's not valid, redisplays the form with error messages. * At the preview page, if the preview confirmation button is pressed, calls a hook that you define -- a done() method. The framework enforces the required preview by passing a shared-secret hash to the preview page. If somebody tweaks the form parameters on the preview page, the form submission will fail the hash comparison test. Usage ===== Subclass FormPreview and define a done() method: def done(self, request, clean_data): # ... This method takes an HttpRequest object and a dictionary of the form data after it has been validated and cleaned. It should return an HttpResponseRedirect. Then, just instantiate your FormPreview subclass by passing it a Form class, and pass that to your URLconf, like so: (r'^post/$', MyFormPreview(MyForm)), The FormPreview class has a few other hooks. See the docstrings in the source code below. The framework also uses two templates: 'formtools/preview.html' and 'formtools/form.html'. You can override these by setting 'preview_template' and 'form_template' attributes on your FormPreview subclass. See django/contrib/formtools/templates for the default templates. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import Http404 from django.shortcuts import render_to_response from django.template.context import RequestContext import cPickle as pickle import md5 AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter. class FormPreview(object): preview_template = 'formtools/preview.html' form_template = 'formtools/form.html' # METHODS SUBCLASSES SHOULDN'T OVERRIDE ################################### def __init__(self, form): # form should be a Form class, not an instance. self.form, self.state = form, {} def __call__(self, request, *args, **kwargs): stage = {'1': 'preview', '2': 'post'}.get(request.POST.get(self.unused_name('stage')), 'preview') self.parse_params(*args, **kwargs) try: method = getattr(self, stage + '_' + request.method.lower()) except AttributeError: raise Http404 return method(request) def unused_name(self, name): """ Given a first-choice name, adds an underscore to the name until it reaches a name that isn't claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form. """ while 1: try: f = self.form.fields[name] except KeyError: break # This field name isn't being used by the form. name += '_' return name def preview_get(self, request): "Displays the form" f = self.form(auto_id=AUTO_ID) return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request)) def preview_post(self, request): "Validates the POST data. If valid, displays the preview page. Else, redisplays form." f = self.form(request.POST, auto_id=AUTO_ID) context = {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state} if f.is_valid(): context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_response(self.preview_template, context, context_instance=RequestContext(request)) else: return render_to_response(self.form_template, context, context_instance=RequestContext(request)) def post_post(self, request): "Validates the POST data. If valid, calls done(). Else, redisplays form." f = self.form(request.POST, auto_id=AUTO_ID) if f.is_valid(): if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')): return self.failed_hash(request) # Security hash failed. return self.done(request, f.clean_data) else: return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request)) # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ######################## def parse_params(self, *args, **kwargs): """ Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r'^contact/(?P<user_id>\d{1,6})/$', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {'user_id': 32} for a request to '/contact/32/'. You can use that user_id to make sure it's a valid user and/or save it for later, for use in done(). """ pass def security_hash(self, request, form): """ Calculates the security hash for the given Form instance. This creates a list of the form field names/values in a deterministic order, pickles the result with the SECRET_KEY setting and takes an md5 hash of that. Subclasses may want to take into account request-specific information such as the IP address. """ data = [(bf.name, bf.data) for bf in form] + [settings.SECRET_KEY] # Use HIGHEST_PROTOCOL because it's the most efficient. It requires # Python 2.3, but Django requires 2.3 anyway, so that's OK. pickled = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL) return md5.new(pickled).hexdigest() def failed_hash(self, request): "Returns an HttpResponse in the case of an invalid security hash." return self.preview_post(request) # METHODS SUBCLASSES MUST OVERRIDE ######################################## def done(self, request, clean_data): "Does something with the clean_data and returns an HttpResponseRedirect." raise NotImplementedError('You must define a done() method on your %s subclass.' % self.__class__.__name__)
Python
from django.conf import settings from django.conf.urls.defaults import * if settings.USE_I18N: i18n_view = 'django.views.i18n.javascript_catalog' else: i18n_view = 'django.views.i18n.null_javascript_catalog' urlpatterns = patterns('', ('^$', 'django.contrib.admin.views.main.index'), ('^r/(\d+)/(.*)/$', 'django.views.defaults.shortcut'), ('^jsi18n/$', i18n_view, {'packages': 'django.conf'}), ('^logout/$', 'django.contrib.auth.views.logout'), ('^password_change/$', 'django.contrib.auth.views.password_change'), ('^password_change/done/$', 'django.contrib.auth.views.password_change_done'), ('^template_validator/$', 'django.contrib.admin.views.template.template_validator'), # Documentation ('^doc/$', 'django.contrib.admin.views.doc.doc_index'), ('^doc/bookmarklets/$', 'django.contrib.admin.views.doc.bookmarklets'), ('^doc/tags/$', 'django.contrib.admin.views.doc.template_tag_index'), ('^doc/filters/$', 'django.contrib.admin.views.doc.template_filter_index'), ('^doc/views/$', 'django.contrib.admin.views.doc.view_index'), ('^doc/views/(?P<view>[^/]+)/$', 'django.contrib.admin.views.doc.view_detail'), ('^doc/models/$', 'django.contrib.admin.views.doc.model_index'), ('^doc/models/(?P<app_label>[^\.]+)\.(?P<model_name>[^/]+)/$', 'django.contrib.admin.views.doc.model_detail'), # ('^doc/templates/$', 'django.views.admin.doc.template_index'), ('^doc/templates/(?P<template>.*)/$', 'django.contrib.admin.views.doc.template_detail'), # "Add user" -- a special-case view ('^auth/user/add/$', 'django.contrib.admin.views.auth.user_add_stage'), # "Change user password" -- another special-case view ('^auth/user/(\d+)/password/$', 'django.contrib.admin.views.auth.user_change_password'), # Add/change/delete/history ('^([^/]+)/([^/]+)/$', 'django.contrib.admin.views.main.change_list'), ('^([^/]+)/([^/]+)/add/$', 'django.contrib.admin.views.main.add_stage'), ('^([^/]+)/([^/]+)/(.+)/history/$', 'django.contrib.admin.views.main.history'), ('^([^/]+)/([^/]+)/(.+)/delete/$', 'django.contrib.admin.views.main.delete_stage'), ('^([^/]+)/([^/]+)/(.+)/$', 'django.contrib.admin.views.main.change_stage'), ) del i18n_view
Python
"Misc. utility functions/classes for admin documentation generator." import re from email.Parser import HeaderParser from email.Errors import HeaderParseError try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def trim_docstring(docstring): """ Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lines = docstring.expandtabs().splitlines() indent = min([len(line) - len(line.lstrip()) for line in lines if line.lstrip()]) trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] return "\n".join(trimmed).strip() def parse_docstring(docstring): """ Parse out the parts of a docstring. Returns (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None, link_base='../..'): """ Convert the string from reST to an XHTML fragment. """ overrides = { 'doctitle_xform' : True, 'inital_header_level' : 3, "default_reference_context" : default_reference_context, "link_base" : link_base, } if thing_being_parsed: thing_being_parsed = "<%s>" % thing_being_parsed parts = docutils.core.publish_parts(text, source_path=thing_being_parsed, destination_path=None, writer_name='html', settings_overrides=overrides) return parts['fragment'] # # reST roles # ROLES = { 'model' : '%s/models/%s/', 'view' : '%s/views/%s/', 'template' : '%s/templates/%s/', 'filter' : '%s/filters/#%s', 'tag' : '%s/tags/#%s', } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] node = docutils.nodes.reference(rawtext, text, refuri=(urlbase % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] context = inliner.document.settings.default_reference_context node = docutils.nodes.reference(rawtext, text, refuri=(ROLES[context] % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE = 'cmsreference' for name, urlbase in ROLES.items(): create_reference_role(name, urlbase)
Python
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ 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, 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'), maxlength=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 str(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 "%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, self.object_id)
Python
""" 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 import datetime class FilterSpec(object): filter_specs = [] def __init__(self, f, request, params, model): 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): for test, factory in cls.filter_specs: if test(f): return factory(f, request, params, model) 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(_('<h3>By %s:</h3>\n<ul>\n') % self.title()) for choice in self.choices(cl): t.append('<li%s><a href="%s">%s</a></li>\n' % \ ((choice['selected'] and ' class="selected"' or ''), choice['query_string'] , choice['display'])) t.append('</ul>\n\n') return "".join(t) class RelatedFilterSpec(FilterSpec): def __init__(self, f, request, params, model): super(RelatedFilterSpec, self).__init__(f, request, params, model) 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 == str(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): super(ChoicesFilterSpec, self).__init__(f, request, params, model) 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': str(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): super(DateFieldFilterSpec, self).__init__(f, request, params, model) 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): super(BooleanFieldFilterSpec, self).__init__(f, request, params, model) 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): super(AllValuesFilterSpec, self).__init__(f, request, params, model) self.lookup_val = request.GET.get(f.name, None) self.lookup_choices = model._meta.admin.manager.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 = str(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)
Python
from django.contrib.admin.views.decorators import staff_member_required from django.core import validators from django import template, oldforms from django.template import loader from django.shortcuts import render_to_response from django.contrib.sites.models import Site from django.conf import settings 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 manipulator = TemplateValidator(settings_modules) new_data, errors = {}, {} if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: request.user.message_set.create(message='The template is valid.') return render_to_response('admin/template_validator.html', { 'title': 'Template validator', 'form': oldforms.FormWrapper(manipulator, new_data, errors), }, context_instance=template.RequestContext(request)) template_validator = staff_member_required(template_validator) class TemplateValidator(oldforms.Manipulator): def __init__(self, settings_modules): self.settings_modules = settings_modules site_list = Site.objects.in_bulk(settings_modules.keys()).values() self.fields = ( oldforms.SelectField('site', is_required=True, choices=[(s.id, s.name) for s in site_list]), oldforms.LargeTextField('template', is_required=True, rows=25, validator_list=[self.isValidTemplate]), ) def isValidTemplate(self, field_data, all_data): # 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(all_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 try: tmpl = loader.get_template_from_string(field_data) tmpl.render(template.Context({})) except template.TemplateSyntaxError, e: error = e template.builtins.remove(register) if error: raise validators.ValidationError, e.args
Python
from django import oldforms, template from django.conf import settings from django.contrib.admin.filterspecs import FilterSpec from django.contrib.admin.views.decorators import staff_member_required from django.views.decorators.cache import never_cache from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist, PermissionDenied from django.core.paginator import ObjectPaginator, InvalidPage from django.shortcuts import get_object_or_404, render_to_response from django.db import models from django.db.models.query import handle_legacy_orderlist, QuerySet from django.http import Http404, HttpResponse, HttpResponseRedirect from django.utils.html import escape from django.utils.text import capfirst, get_text_list import operator from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION if not LogEntry._meta.installed: raise ImproperlyConfigured, "You'll need to put 'django.contrib.admin' in your INSTALLED_APPS setting before you can use the admin application." if 'django.core.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS: raise ImproperlyConfigured, "You'll need to put 'django.core.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting before you can use the admin application." # 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' IS_POPUP_VAR = 'pop' ERROR_FLAG = 'e' # Text to display within change-list table cells if the value is blank. EMPTY_CHANGELIST_VALUE = '(None)' use_raw_id_admin = lambda field: isinstance(field.rel, (models.ManyToOneRel, models.ManyToManyRel)) and field.rel.raw_id_admin class IncorrectLookupParameters(Exception): pass 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 type(s) != type(''): 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 get_javascript_imports(opts, auto_populated_fields, field_sets): # Put in any necessary JavaScript imports. js = ['js/core.js', 'js/admin/RelatedObjectLookups.js'] if auto_populated_fields: js.append('js/urlify.js') if opts.has_field_type(models.DateTimeField) or opts.has_field_type(models.TimeField) or opts.has_field_type(models.DateField): js.extend(['js/calendar.js', 'js/admin/DateTimeShortcuts.js']) if opts.get_ordered_objects(): js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js']) if opts.admin.js: js.extend(opts.admin.js) seen_collapse = False for field_set in field_sets: if not seen_collapse and 'collapse' in field_set.classes: seen_collapse = True js.append('js/admin/CollapsedFieldsets.js') for field_line in field_set: try: for f in field_line: if f.rel and isinstance(f, models.ManyToManyField) and f.rel.filter_interface: js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js']) raise StopIteration except StopIteration: break return js class AdminBoundField(object): def __init__(self, field, field_mapping, original): self.field = field self.original = original self.form_fields = [field_mapping[name] for name in self.field.get_manipulator_field_names('')] self.element_id = self.form_fields[0].get_id() self.has_label_first = not isinstance(self.field, models.BooleanField) self.raw_id_admin = use_raw_id_admin(field) self.is_date_time = isinstance(field, models.DateTimeField) self.is_file_field = isinstance(field, models.FileField) self.needs_add_label = field.rel and (isinstance(field.rel, models.ManyToOneRel) or isinstance(field.rel, models.ManyToManyRel)) and field.rel.to._meta.admin self.hidden = isinstance(self.field, models.AutoField) self.first = False classes = [] if self.raw_id_admin: classes.append('nowrap') if max([bool(f.errors()) for f in self.form_fields]): classes.append('error') if classes: self.cell_class_attribute = ' class="%s" ' % ' '.join(classes) self._repr_filled = False if field.rel: self.related_url = '../../../%s/%s/' % (field.rel.to._meta.app_label, field.rel.to._meta.object_name.lower()) def original_value(self): if self.original: return self.original.__dict__[self.field.column] def existing_display(self): try: return self._display except AttributeError: if isinstance(self.field.rel, models.ManyToOneRel): self._display = getattr(self.original, self.field.name) elif isinstance(self.field.rel, models.ManyToManyRel): self._display = ", ".join([str(obj) for obj in getattr(self.original, self.field.name).all()]) return self._display def __repr__(self): return repr(self.__dict__) def html_error_list(self): return " ".join([form_field.html_error_list() for form_field in self.form_fields if form_field.errors]) def original_url(self): if self.is_file_field and self.original and self.field.attname: url_method = getattr(self.original, 'get_%s_url' % self.field.attname) if callable(url_method): return url_method() return '' class AdminBoundFieldLine(object): def __init__(self, field_line, field_mapping, original): self.bound_fields = [field.bind(field_mapping, original, AdminBoundField) for field in field_line] for bound_field in self: bound_field.first = True break def __iter__(self): for bound_field in self.bound_fields: yield bound_field def __len__(self): return len(self.bound_fields) class AdminBoundFieldSet(object): def __init__(self, field_set, field_mapping, original): self.name = field_set.name self.classes = field_set.classes self.description = field_set.description self.bound_field_lines = [field_line.bind(field_mapping, original, AdminBoundFieldLine) for field_line in field_set] def __iter__(self): for bound_field_line in self.bound_field_lines: yield bound_field_line def __len__(self): return len(self.bound_field_lines) def render_change_form(model, manipulator, context, add=False, change=False, form_url=''): opts = model._meta app_label = opts.app_label auto_populated_fields = [f for f in opts.fields if f.prepopulate_from] field_sets = opts.admin.get_field_sets(opts) original = getattr(manipulator, 'original_object', None) bound_field_sets = [field_set.bind(context['form'], original, AdminBoundFieldSet) for field_set in field_sets] first_form_field_id = bound_field_sets[0].bound_field_lines[0].bound_fields[0].form_fields[0].get_id(); ordered_objects = opts.get_ordered_objects() inline_related_objects = opts.get_followed_related_objects(manipulator.follow) extra_context = { 'add': add, 'change': change, 'has_delete_permission': context['perms'][app_label][opts.get_delete_permission()], 'has_change_permission': context['perms'][app_label][opts.get_change_permission()], 'has_file_field': opts.has_field_type(models.FileField), 'has_absolute_url': hasattr(model, 'get_absolute_url'), 'auto_populated_fields': auto_populated_fields, 'bound_field_sets': bound_field_sets, 'first_form_field_id': first_form_field_id, 'javascript_imports': get_javascript_imports(opts, auto_populated_fields, field_sets), 'ordered_objects': ordered_objects, 'inline_related_objects': inline_related_objects, 'form_url': form_url, 'opts': opts, 'content_type_id': ContentType.objects.get_for_model(model).id, } context.update(extra_context) return render_to_response([ "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), "admin/%s/change_form.html" % app_label, "admin/change_form.html"], context_instance=context) def index(request): return render_to_response('admin/index.html', {'title': _('Site administration')}, context_instance=template.RequestContext(request)) index = staff_member_required(never_cache(index)) def add_stage(request, app_label, model_name, show_delete=False, form_url='', post_url=None, post_url_continue='../%s/', object_id_override=None): model = models.get_model(app_label, model_name) if model is None: raise Http404("App %r, model %r, not found" % (app_label, model_name)) opts = model._meta if not request.user.has_perm(app_label + '.' + opts.get_add_permission()): raise PermissionDenied if post_url is None: if request.user.has_perm(app_label + '.' + opts.get_change_permission()): # redirect to list view post_url = '../' else: # Object list will give 'Permission Denied', so go back to admin home post_url = '../../../' manipulator = model.AddManipulator() if request.POST: new_data = request.POST.copy() if opts.has_field_type(models.FileField): new_data.update(request.FILES) errors = manipulator.get_validation_errors(new_data) manipulator.do_html2python(new_data) if not errors: new_object = manipulator.save(new_data) pk_value = new_object._get_pk_val() LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), ADDITION) msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object} # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if request.POST.has_key("_continue"): request.user.message_set.create(message=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"): if type(pk_value) is str: # Quote if string, so JavaScript doesn't think it's a variable. pk_value = '"%s"' % pk_value.replace('"', '\\"') return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % \ (pk_value, str(new_object).replace('"', '\\"'))) elif request.POST.has_key("_addanother"): request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name)) return HttpResponseRedirect(request.path) else: request.user.message_set.create(message=msg) return HttpResponseRedirect(post_url) else: # Add default data. new_data = manipulator.flatten_data() # Override the defaults with GET params, if they exist. new_data.update(dict(request.GET.items())) errors = {} # Populate the FormWrapper. form = oldforms.FormWrapper(manipulator, new_data, errors) c = template.RequestContext(request, { 'title': _('Add %s') % opts.verbose_name, 'form': form, 'is_popup': request.REQUEST.has_key('_popup'), 'show_delete': show_delete, }) if object_id_override is not None: c['object_id'] = object_id_override return render_change_form(model, manipulator, c, add=True) add_stage = staff_member_required(never_cache(add_stage)) def change_stage(request, app_label, model_name, object_id): model = models.get_model(app_label, model_name) object_id = unquote(object_id) if model is None: raise Http404("App %r, model %r, not found" % (app_label, model_name)) opts = model._meta if not request.user.has_perm(app_label + '.' + opts.get_change_permission()): raise PermissionDenied if request.POST and request.POST.has_key("_saveasnew"): return add_stage(request, app_label, model_name, form_url='../../add/') try: manipulator = model.ChangeManipulator(object_id) except model.DoesNotExist: raise Http404('%s object with primary key %r does not exist' % (model_name, escape(object_id))) if request.POST: new_data = request.POST.copy() if opts.has_field_type(models.FileField): new_data.update(request.FILES) errors = manipulator.get_validation_errors(new_data) manipulator.do_html2python(new_data) if not errors: new_object = manipulator.save(new_data) pk_value = new_object._get_pk_val() # Construct the change message. change_message = [] if manipulator.fields_added: change_message.append(_('Added %s.') % get_text_list(manipulator.fields_added, _('and'))) if manipulator.fields_changed: change_message.append(_('Changed %s.') % get_text_list(manipulator.fields_changed, _('and'))) if manipulator.fields_deleted: change_message.append(_('Deleted %s.') % get_text_list(manipulator.fields_deleted, _('and'))) change_message = ' '.join(change_message) if not change_message: change_message = _('No fields changed.') LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), CHANGE, change_message) msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object} if request.POST.has_key("_continue"): request.user.message_set.create(message=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"): request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object}) return HttpResponseRedirect("../%s/" % pk_value) elif request.POST.has_key("_addanother"): request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name)) return HttpResponseRedirect("../add/") else: request.user.message_set.create(message=msg) return HttpResponseRedirect("../") else: # Populate new_data with a "flattened" version of the current data. new_data = manipulator.flatten_data() # TODO: do this in flatten_data... # If the object has ordered objects on its admin page, get the existing # order and flatten it into a comma-separated list of IDs. id_order_list = [] for rel_obj in opts.get_ordered_objects(): id_order_list.extend(getattr(manipulator.original_object, 'get_%s_order' % rel_obj.object_name.lower())()) if id_order_list: new_data['order_'] = ','.join(map(str, id_order_list)) errors = {} # Populate the FormWrapper. form = oldforms.FormWrapper(manipulator, new_data, errors) form.original = manipulator.original_object form.order_objects = [] #TODO Should be done in flatten_data / FormWrapper construction for related in opts.get_followed_related_objects(): wrt = related.opts.order_with_respect_to if wrt and wrt.rel and wrt.rel.to == opts: func = getattr(manipulator.original_object, 'get_%s_list' % related.get_accessor_name()) orig_list = func() form.order_objects.extend(orig_list) c = template.RequestContext(request, { 'title': _('Change %s') % opts.verbose_name, 'form': form, 'object_id': object_id, 'original': manipulator.original_object, 'is_popup': request.REQUEST.has_key('_popup'), }) return render_change_form(model, manipulator, c, change=True) change_stage = staff_member_required(never_cache(change_stage)) 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): "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(): 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 related.opts.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 related.field.rel.edit_inline or not related.opts.admin: # Don't display link to edit, because it either has no # admin or is edited inline. nh(deleted_objects, current_depth, ['%s: %s' % (capfirst(related.opts.verbose_name), sub_obj), []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, ['%s: <a href="../../../../%s/%s/%s/">%s</a>' % \ (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) else: has_related_objs = False for sub_obj in getattr(obj, rel_opts_name).all(): has_related_objs = True if related.field.rel.edit_inline or not related.opts.admin: # Don't display link to edit, because it either has no # admin or is edited inline. nh(deleted_objects, current_depth, ['%s: %s' % (capfirst(related.opts.verbose_name), escape(str(sub_obj))), []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, ['%s: <a href="../../../../%s/%s/%s/">%s</a>' % \ (capfirst(related.opts.verbose_name), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(str(sub_obj))), []]) _get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2) # If there were related objects, and the user doesn't have # permission to delete them, add the missing perm to perms_needed. if related.opts.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(): 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 related.field.rel.edit_inline or not related.opts.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': related.field.verbose_name, 'name': related.opts.verbose_name, 'obj': escape(str(sub_obj))}, []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, [ (_('One or more %(fieldname)s in %(name)s:') % {'fieldname': related.field.verbose_name, 'name':related.opts.verbose_name}) + \ (' <a href="../../../../%s/%s/%s/">%s</a>' % \ (related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(str(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 related.opts.admin and has_related_objs: p = '%s.%s' % (related.opts.app_label, related.opts.get_change_permission()) if not user.has_perm(p): perms_needed.add(related.opts.verbose_name) def delete_stage(request, app_label, model_name, object_id): import sets model = models.get_model(app_label, model_name) object_id = unquote(object_id) if model is None: raise Http404("App %r, model %r, not found" % (app_label, model_name)) opts = model._meta if not request.user.has_perm(app_label + '.' + opts.get_delete_permission()): raise PermissionDenied obj = get_object_or_404(model, pk=object_id) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. deleted_objects = ['%s: <a href="../../%s/">%s</a>' % (capfirst(opts.verbose_name), object_id, escape(str(obj))), []] perms_needed = sets.Set() _get_deleted_objects(deleted_objects, perms_needed, request.user, obj, opts, 1) if request.POST: # The user has already confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = str(obj) obj.delete() LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, object_id, obj_display, DELETION) request.user.message_set.create(message=_('The %(name)s "%(obj)s" was deleted successfully.') % {'name': opts.verbose_name, 'obj': obj_display}) return HttpResponseRedirect("../../") extra_context = { "title": _("Are you sure?"), "object_name": opts.verbose_name, "object": obj, "deleted_objects": deleted_objects, "perms_lacking": perms_needed, "opts": model._meta, } return render_to_response(["admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower() ), "admin/%s/delete_confirmation.html" % app_label , "admin/delete_confirmation.html"], extra_context, context_instance=template.RequestContext(request)) delete_stage = staff_member_required(never_cache(delete_stage)) def history(request, app_label, model_name, object_id): model = models.get_model(app_label, model_name) object_id = unquote(object_id) if model is None: raise Http404("App %r, model %r, not found" % (app_label, model_name)) 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) extra_context = { 'title': _('Change history: %s') % obj, 'action_list': action_list, 'module_name': capfirst(model._meta.verbose_name_plural), 'object': obj, } return render_to_response(["admin/%s/%s/object_history.html" % (app_label, model._meta.object_name.lower()), "admin/%s/object_history.html" % app_label , "admin/object_history.html"], extra_context, context_instance=template.RequestContext(request)) history = staff_member_required(never_cache(history)) class ChangeList(object): def __init__(self, request, model): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.manager = self.opts.admin.manager # 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 = request.GET.has_key(ALL_VAR) self.is_popup = request.GET.has_key(IS_POPUP_VAR) self.params = dict(request.GET.items()) if self.params.has_key(PAGE_VAR): del self.params[PAGE_VAR] if self.params.has_key(ERROR_FLAG): 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 _('Select %s') % self.opts.verbose_name or _('Select %s to change') % 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.lookup_opts.admin.list_filter and not self.opts.one_to_one_field: filter_fields = [self.lookup_opts.get_field(field_name) \ for field_name in self.lookup_opts.admin.list_filter] for f in filter_fields: spec = FilterSpec.create(f, request, self.params, self.model) 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 p.has_key(k) and v is None: del p[k] elif v is not None: p[k] = v return '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20') def get_results(self, request): paginator = ObjectPaginator(self.query_set, self.lookup_opts.admin.list_per_page) # Get the number of objects, with admin filters applied. try: result_count = paginator.hits # 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 isinstance(self.query_set._filters, models.Q) and not self.query_set._filters.kwargs: full_result_count = result_count else: full_result_count = self.manager.count() can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED multi_page = result_count > self.lookup_opts.admin.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.get_page(self.page_num) 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 = lookup_opts.admin.ordering or lookup_opts.ordering or ['-' + lookup_opts.pk.name] # Normalize it to new-style ordering. ordering = handle_legacy_orderlist(ordering) if ordering[0].startswith('-'): order_field, order_type = ordering[0][1:], 'desc' else: order_field, order_type = ordering[0], 'asc' if params.has_key(ORDER_VAR): try: field_name = lookup_opts.admin.list_display[int(params[ORDER_VAR])] try: f = lookup_opts.get_field(field_name) except models.FieldDoesNotExist: # see if field_name is a name of a non-field # that allows sorting try: attr = getattr(lookup_opts.admin.manager.model, field_name) order_field = attr.admin_order_field except IndexError: 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 params.has_key(ORDER_TYPE_VAR) 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.manager.get_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 lookup_params.has_key(i): del lookup_params[i] # 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.lookup_opts.admin.list_select_related: qs = qs.select_related() else: for field_name in self.lookup_opts.admin.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 # Calculate lookup_order_field. # If the order-by field is a field with a relationship, order by the # value in the related table. lookup_order_field = self.order_field try: f = self.lookup_opts.get_field(self.order_field, many_to_many=False) except models.FieldDoesNotExist: pass else: if isinstance(f.rel, models.OneToOneRel): # For OneToOneFields, don't try to order by the related object's ordering criteria. pass elif isinstance(f.rel, models.ManyToOneRel): rel_ordering = f.rel.to._meta.ordering and f.rel.to._meta.ordering[0] or f.rel.to._meta.pk.column lookup_order_field = '%s.%s' % (f.rel.to._meta.db_table, rel_ordering) # Set ordering. qs = qs.order_by((self.order_type == 'desc' and '-' or '') + lookup_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.lookup_opts.admin.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.lookup_opts.admin.search_fields] other_qs = QuerySet(self.model) if qs._select_related: other_qs = other_qs.select_related() other_qs = other_qs.filter(reduce(operator.or_, or_queries)) qs = qs & other_qs 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)) def change_list(request, app_label, model_name): model = models.get_model(app_label, model_name) if model is None: raise Http404("App %r, model %r, not found" % (app_label, model_name)) if not request.user.has_perm(app_label + '.' + model._meta.get_change_permission()): raise PermissionDenied try: cl = ChangeList(request, model) 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') c = template.RequestContext(request, { 'title': cl.title, 'is_popup': cl.is_popup, 'cl': cl, }) c.update({'has_add_permission': c['perms'][app_label][cl.opts.get_add_permission()]}), return render_to_response(['admin/%s/%s/change_list.html' % (app_label, cl.opts.object_name.lower()), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html'], context_instance=c) change_list = staff_member_required(never_cache(change_list))
Python
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.forms import UserCreationForm, AdminPasswordChangeForm from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django import oldforms, template from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect from django.utils.html import escape def user_add_stage(request): if not request.user.has_perm('auth.change_user'): raise PermissionDenied manipulator = UserCreationForm() if request.method == 'POST': new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: new_user = manipulator.save(new_data) msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user} if request.POST.has_key("_addanother"): request.user.message_set.create(message=msg) return HttpResponseRedirect(request.path) else: request.user.message_set.create(message=msg + ' ' + _("You may edit it again below.")) return HttpResponseRedirect('../%s/' % new_user.id) else: errors = new_data = {} form = oldforms.FormWrapper(manipulator, new_data, errors) return render_to_response('admin/auth/user/add_form.html', { 'title': _('Add user'), 'form': form, 'is_popup': request.REQUEST.has_key('_popup'), 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_file_field': False, 'has_absolute_url': False, 'auto_populated_fields': (), 'bound_field_sets': (), 'first_form_field_id': 'id_username', 'opts': User._meta, 'username_help_text': User._meta.get_field('username').help_text, }, context_instance=template.RequestContext(request)) user_add_stage = staff_member_required(user_add_stage) def user_change_password(request, id): if not request.user.has_perm('auth.change_user'): raise PermissionDenied user = get_object_or_404(User, pk=id) manipulator = AdminPasswordChangeForm(user) if request.method == 'POST': new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: new_user = manipulator.save(new_data) msg = _('Password changed successfully.') request.user.message_set.create(message=msg) return HttpResponseRedirect('..') else: errors = new_data = {} form = oldforms.FormWrapper(manipulator, new_data, errors) return render_to_response('admin/auth/user/change_password.html', { 'title': _('Change password: %s') % escape(user.username), 'form': form, 'is_popup': request.REQUEST.has_key('_popup'), 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'first_form_field_id': 'id_password1', 'opts': User._meta, 'original': user, 'show_save': True, }, context_instance=template.RequestContext(request)) user_change_password = staff_member_required(user_change_password)
Python
from django import template, templatetags from django.template import RequestContext from django.conf import settings from django.contrib.admin.views.decorators import staff_member_required from django.db import models from django.shortcuts import render_to_response from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.http import Http404, get_host from django.core import urlresolvers from django.contrib.admin import utils from django.contrib.sites.models import Site import inspect, os, re # Exclude methods starting with these strings from documentation MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_') class GenericSite(object): domain = 'example.com' name = 'my site' def doc_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) return render_to_response('admin_doc/index.html', context_instance=RequestContext(request)) doc_index = staff_member_required(doc_index) def bookmarklets(request): # Hack! This couples this view to the URL it lives at. admin_root = request.path[:-len('doc/bookmarklets/')] return render_to_response('admin_doc/bookmarklets.html', { 'admin_url': "%s://%s%s" % (request.is_secure() and 'https' or 'http', get_host(request), admin_root), }, context_instance=RequestContext(request)) bookmarklets = staff_member_required(bookmarklets) def template_tag_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) load_all_installed_template_libraries() tags = [] for module_name, library in template.libraries.items(): for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring(tag_func.__doc__) if title: title = utils.parse_rst(title, 'tag', _('tag:') + tag_name) if body: body = utils.parse_rst(body, 'tag', _('tag:') + tag_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'tag', _('tag:') + tag_name) if library in template.builtins: tag_library = None else: tag_library = module_name.split('.')[-1] tags.append({ 'name': tag_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return render_to_response('admin_doc/template_tag_index.html', {'tags': tags}, context_instance=RequestContext(request)) template_tag_index = staff_member_required(template_tag_index) def template_filter_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) load_all_installed_template_libraries() filters = [] for module_name, library in template.libraries.items(): for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) if library in template.builtins: tag_library = None else: tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return render_to_response('admin_doc/template_filter_index.html', {'filters': filters}, context_instance=RequestContext(request)) template_filter_index = staff_member_required(template_filter_index) def view_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) if Site._meta.installed: site_obj = Site.objects.get(pk=settings_mod.SITE_ID) else: site_obj = GenericSite() for (func, regex) in view_functions: views.append({ 'name': func.__name__, 'module': func.__module__, 'site_id': settings_mod.SITE_ID, 'site': site_obj, 'url': simplify_regex(regex), }) return render_to_response('admin_doc/view_index.html', {'views': views}, context_instance=RequestContext(request)) view_index = staff_member_required(view_index) def view_detail(request, view): if not utils.docutils_is_available: return missing_docutils_page(request) mod, func = urlresolvers.get_mod_func(view) try: view_func = getattr(__import__(mod, {}, {}, ['']), func) except (ImportError, AttributeError): raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) if title: title = utils.parse_rst(title, 'view', _('view:') + view) if body: body = utils.parse_rst(body, 'view', _('view:') + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view) return render_to_response('admin_doc/view_detail.html', { 'name': view, 'summary': title, 'body': body, 'meta': metadata, }, context_instance=RequestContext(request)) view_detail = staff_member_required(view_detail) def model_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) m_list = [m._meta for m in models.get_models()] return render_to_response('admin_doc/model_index.html', {'models': m_list}, context_instance=RequestContext(request)) model_index = staff_member_required(model_index) def model_detail(request, app_label, model_name): if not utils.docutils_is_available: return missing_docutils_page(request) # Get the model class. try: app_mod = models.get_app(app_label) except ImproperlyConfigured: raise Http404, _("App %r not found") % app_label model = None for m in models.get_models(app_mod): if m._meta.object_name.lower() == model_name: model = m break if model is None: raise Http404, _("Model %(name)r not found in app %(label)r") % {'name': model_name, 'label': app_label} opts = model._meta # Gather fields/field descriptions. fields = [] for field in opts.fields: # ForeignKey is a special case since the field will actually be a # descriptor that returns the other object if isinstance(field, models.ForeignKey): data_type = related_object_name = field.rel.to.__name__ app_label = field.rel.to._meta.app_label verbose = utils.parse_rst((_("the related `%(label)s.%(type)s` object") % {'label': app_label, 'type': data_type}), 'model', _('model:') + data_type) else: data_type = get_readable_field_data_type(field) verbose = field.verbose_name fields.append({ 'name': field.name, 'data_type': data_type, 'verbose': verbose, 'help_text': field.help_text, }) # Gather model methods. for func_name, func in model.__dict__.items(): if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1): try: for exclude in MODEL_METHODS_EXCLUDE: if func_name.startswith(exclude): raise StopIteration except StopIteration: continue verbose = func.__doc__ if verbose: verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name) fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose, }) # Gather related objects for rel in opts.get_all_related_objects(): verbose = _("related `%(label)s.%(name)s` objects") % {'label': rel.opts.app_label, 'name': rel.opts.object_name} accessor = rel.get_accessor_name() fields.append({ 'name' : "%s.all" % accessor, 'data_type' : 'List', 'verbose' : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name), }) fields.append({ 'name' : "%s.count" % accessor, 'data_type' : 'Integer', 'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name), }) return render_to_response('admin_doc/model_detail.html', { 'name': '%s.%s' % (opts.app_label, opts.object_name), 'summary': _("Fields on %s objects") % opts.object_name, 'description': model.__doc__, 'fields': fields, }, context_instance=RequestContext(request)) model_detail = staff_member_required(model_detail) def template_detail(request, template): templates = [] for site_settings_module in settings.ADMIN_FOR: settings_mod = __import__(site_settings_module, {}, {}, ['']) if Site._meta.installed: site_obj = Site.objects.get(pk=settings_mod.SITE_ID) else: site_obj = GenericSite() for dir in settings_mod.TEMPLATE_DIRS: template_file = os.path.join(dir, "%s.html" % template) templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': lambda: os.path.exists(template_file) and open(template_file).read() or '', 'site_id': settings_mod.SITE_ID, 'site': site_obj, 'order': list(settings_mod.TEMPLATE_DIRS).index(dir), }) return render_to_response('admin_doc/template_detail.html', { 'name': template, 'templates': templates, }, context_instance=RequestContext(request)) template_detail = staff_member_required(template_detail) #################### # Helper functions # #################### def missing_docutils_page(request): """Display an error message for people without docutils""" return render_to_response('admin_doc/missing_docutils.html') def load_all_installed_template_libraries(): # Load/register all template tag libraries from installed apps. for e in templatetags.__path__: libraries = [os.path.splitext(p)[0] for p in os.listdir(e) if p.endswith('.py') and p[0].isalpha()] for library_name in libraries: try: lib = template.get_library("django.templatetags.%s" % library_name.split('.')[-1]) except template.InvalidTemplateLibrary: pass def get_return_data_type(func_name): """Return a somewhat-helpful data type given a function name""" if func_name.startswith('get_'): if func_name.endswith('_list'): return 'List' elif func_name.endswith('_count'): return 'Integer' return '' # Maps Field objects to their human-readable data types, as strings. # Column-type strings can contain format strings; they'll be interpolated # against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. DATA_TYPE_MAPPING = { 'AutoField' : _('Integer'), 'BooleanField' : _('Boolean (Either True or False)'), 'CharField' : _('String (up to %(maxlength)s)'), 'CommaSeparatedIntegerField': _('Comma-separated integers'), 'DateField' : _('Date (without time)'), 'DateTimeField' : _('Date (with time)'), 'EmailField' : _('E-mail address'), 'FileField' : _('File path'), 'FilePathField' : _('File path'), 'FloatField' : _('Decimal number'), 'ForeignKey' : _('Integer'), 'ImageField' : _('File path'), 'IntegerField' : _('Integer'), 'IPAddressField' : _('IP address'), 'ManyToManyField' : '', 'NullBooleanField' : _('Boolean (Either True, False or None)'), 'OneToOneField' : _('Relation to parent model'), 'PhoneNumberField' : _('Phone number'), 'PositiveIntegerField' : _('Integer'), 'PositiveSmallIntegerField' : _('Integer'), 'SlugField' : _('String (up to %(maxlength)s)'), 'SmallIntegerField' : _('Integer'), 'TextField' : _('Text'), 'TimeField' : _('Time'), 'URLField' : _('URL'), 'USStateField' : _('U.S. state (two uppercase letters)'), 'XMLField' : _('XML text'), } def get_readable_field_data_type(field): return DATA_TYPE_MAPPING[field.get_internal_type()] % field.__dict__ def extract_views_from_urlpatterns(urlpatterns, base=''): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a two-tuple: (view_func, regex) """ views = [] for p in urlpatterns: if hasattr(p, '_get_callback'): try: views.append((p._get_callback(), base + p.regex.pattern)) except ViewDoesNotExist: continue elif hasattr(p, '_get_url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern)) else: raise TypeError, _("%s does not appear to be a urlpattern object") % p return views named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)') non_named_group_matcher = re.compile(r'\(.*?\)') def simplify_regex(pattern): """ Clean up urlpattern regexes into something somewhat readable by Mere Humans: turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into "<sport_slug>/athletes/<athlete_slug>/" """ # handle named groups first pattern = named_group_matcher.sub(lambda m: m.group(1), pattern) # handle non-named groups pattern = non_named_group_matcher.sub("<var>", pattern) # clean up any outstanding regex-y characters. pattern = pattern.replace('^', '').replace('$', '').replace('?', '').replace('//', '/').replace('\\', '') if not pattern.startswith('/'): pattern = '/' + pattern return pattern
Python
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 gettext_lazy import base64, datetime, md5 import cPickle as pickle ERROR_MESSAGE = gettext_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() if request.POST and request.POST.has_key('post_data'): # User has failed login BUT has previously saved post data. post_data = request.POST['post_data'] elif request.POST: # User's session must have expired; save their post data. post_data = _encode_post_data(request.POST) else: post_data = _encode_post_data({}) return render_to_response('admin/login.html', { 'title': _('Log in'), 'app_path': request.path, 'post_data': post_data, 'error_message': error_message }, context_instance=template.RequestContext(request)) def _encode_post_data(post_data): pickled = pickle.dumps(post_data) pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def _decode_post_data(encoded_data): encoded_data = base64.decodestring(encoded_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation, "User may have tampered with session cookie." return pickle.loads(pickled) 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. if request.POST.has_key('post_data'): # User must have re-authenticated through a different window # or tab. request.POST = _decode_post_data(request.POST['post_data']) 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 not request.POST.has_key(LOGIN_FORM_KEY): if request.POST: message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.") 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) # 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. try: user = User.objects.get(email=username) except User.DoesNotExist: message = _("Usernames cannot contain the '@' character.") else: message = _("Your e-mail address is not your username. Try '%s' instead.") % user.username 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) # TODO: set last_login with an event. user.last_login = datetime.datetime.now() user.save() if request.POST.has_key('post_data'): post_data = _decode_post_data(request.POST['post_data']) if post_data and not post_data.has_key(LOGIN_FORM_KEY): # overwrite request.POST with the saved post_data, and continue request.POST = post_data request.user = user return view_func(request, *args, **kwargs) else: request.session.delete_test_cookie() return http.HttpResponseRedirect(request.path) else: return _display_login_form(request, ERROR_MESSAGE) return _checklogin
Python
from django import template from django.db.models import get_models register = template.Library() class AdminApplistNode(template.Node): def __init__(self, varname): self.varname = varname def render(self, context): from django.db import models from django.utils.text import capfirst app_list = [] user = context['user'] for app in models.get_apps(): # Determine the app_label. app_models = get_models(app) if not app_models: continue app_label = app_models[0]._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: model_list = [] for m in app_models: if m._meta.admin: perms = { 'add': user.has_perm("%s.%s" % (app_label, m._meta.get_add_permission())), 'change': user.has_perm("%s.%s" % (app_label, m._meta.get_change_permission())), 'delete': user.has_perm("%s.%s" % (app_label, m._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_list.append({ 'name': capfirst(m._meta.verbose_name_plural), 'admin_url': '%s/%s/' % (app_label, m.__name__.lower()), 'perms': perms, }) if model_list: # Sort using verbose decorate-sort-undecorate pattern # instead of key argument to sort() for python 2.3 compatibility decorated = [(x['name'], x) for x in model_list] decorated.sort() model_list = [x for key, x in decorated] app_list.append({ 'name': app_label.title(), 'has_module_perms': has_module_perms, 'models': model_list, }) context[self.varname] = app_list return '' def get_admin_app_list(parser, token): """ Returns a list of installed applications and models for which the current user has at least one permission. Syntax:: {% get_admin_app_list as [context_var_containing_app_list] %} Example usage:: {% get_admin_app_list as admin_app_list %} """ tokens = token.contents.split() if len(tokens) < 3: raise template.TemplateSyntaxError, "'%s' tag requires two arguments" % tokens[0] if tokens[1] != 'as': raise template.TemplateSyntaxError, "First argument to '%s' tag must be 'as'" % tokens[0] return AdminApplistNode(tokens[2]) register.tag('get_admin_app_list', get_admin_app_list)
Python
from django import template from django.contrib.admin.views.main import AdminBoundField from django.template import loader from django.utils.text import capfirst from django.db import models from django.db.models.fields import Field from django.db.models.related import BoundRelatedObject from django.conf import settings import re register = template.Library() word_re = re.compile('[A-Z][a-z]+') absolute_url_re = re.compile(r'^(?:http(?:s)?:/)?/', re.IGNORECASE) def class_name_to_underscored(name): return '_'.join([s.lower() for s in word_re.findall(name)[:-1]]) def include_admin_script(script_path): """ Returns an HTML script element for including a script from the admin media url (or other location if an absolute url is given). Example usage:: {% include_admin_script "js/calendar.js" %} could return:: <script type="text/javascript" src="/media/admin/js/calendar.js"> """ if not absolute_url_re.match(script_path): script_path = '%s%s' % (settings.ADMIN_MEDIA_PREFIX, script_path) return '<script type="text/javascript" src="%s"></script>' % script_path include_admin_script = register.simple_tag(include_admin_script) def submit_row(context): opts = context['opts'] change = context['change'] is_popup = context['is_popup'] 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 opts.admin.save_as, 'show_save_and_add_another': not is_popup and (not opts.admin.save_as or context['add']), 'show_save_and_continue': not is_popup and context['has_change_permission'], 'show_save': True } submit_row = register.inclusion_tag('admin/submit_line.html', takes_context=True)(submit_row) def field_label(bound_field): class_names = [] if isinstance(bound_field.field, models.BooleanField): class_names.append("vCheckboxLabel") colon = "" else: if not bound_field.field.blank: class_names.append('required') if not bound_field.first: class_names.append('inline') colon = ":" class_str = class_names and ' class="%s"' % ' '.join(class_names) or '' return '<label for="%s"%s>%s%s</label> ' % (bound_field.element_id, class_str, \ capfirst(bound_field.field.verbose_name), colon) field_label = register.simple_tag(field_label) class FieldWidgetNode(template.Node): nodelists = {} default = None def __init__(self, bound_field_var): self.bound_field_var = bound_field_var def get_nodelist(cls, klass): if not cls.nodelists.has_key(klass): try: field_class_name = klass.__name__ template_name = "widget/%s.html" % class_name_to_underscored(field_class_name) nodelist = loader.get_template(template_name).nodelist except template.TemplateDoesNotExist: super_klass = bool(klass.__bases__) and klass.__bases__[0] or None if super_klass and super_klass != Field: nodelist = cls.get_nodelist(super_klass) else: if not cls.default: cls.default = loader.get_template("widget/default.html").nodelist nodelist = cls.default cls.nodelists[klass] = nodelist return nodelist else: return cls.nodelists[klass] get_nodelist = classmethod(get_nodelist) def render(self, context): bound_field = template.resolve_variable(self.bound_field_var, context) context.push() context['bound_field'] = bound_field output = self.get_nodelist(bound_field.field.__class__).render(context) context.pop() return output class FieldWrapper(object): def __init__(self, field ): self.field = field def needs_header(self): return not isinstance(self.field, models.AutoField) def header_class_attribute(self): return self.field.blank and ' class="optional"' or '' def use_raw_id_admin(self): return isinstance(self.field.rel, (models.ManyToOneRel, models.ManyToManyRel)) \ and self.field.rel.raw_id_admin class FormFieldCollectionWrapper(object): def __init__(self, field_mapping, fields, index): self.field_mapping = field_mapping self.fields = fields self.bound_fields = [AdminBoundField(field, self.field_mapping, field_mapping['original']) for field in self.fields] self.index = index class TabularBoundRelatedObject(BoundRelatedObject): def __init__(self, related_object, field_mapping, original): super(TabularBoundRelatedObject, self).__init__(related_object, field_mapping, original) self.field_wrapper_list = [FieldWrapper(field) for field in self.relation.editable_fields()] fields = self.relation.editable_fields() self.form_field_collection_wrappers = [FormFieldCollectionWrapper(field_mapping, fields, i) for (i,field_mapping) in self.field_mappings.items() ] self.original_row_needed = max([fw.use_raw_id_admin() for fw in self.field_wrapper_list]) self.show_url = original and hasattr(self.relation.opts, 'get_absolute_url') def template_name(self): return "admin/edit_inline_tabular.html" class StackedBoundRelatedObject(BoundRelatedObject): def __init__(self, related_object, field_mapping, original): super(StackedBoundRelatedObject, self).__init__(related_object, field_mapping, original) fields = self.relation.editable_fields() self.field_mappings.fill() self.form_field_collection_wrappers = [FormFieldCollectionWrapper(field_mapping ,fields, i) for (i,field_mapping) in self.field_mappings.items()] self.show_url = original and hasattr(self.relation.opts, 'get_absolute_url') def template_name(self): return "admin/edit_inline_stacked.html" class EditInlineNode(template.Node): def __init__(self, rel_var): self.rel_var = rel_var def render(self, context): relation = template.resolve_variable(self.rel_var, context) context.push() if relation.field.rel.edit_inline == models.TABULAR: bound_related_object_class = TabularBoundRelatedObject elif relation.field.rel.edit_inline == models.STACKED: bound_related_object_class = StackedBoundRelatedObject else: bound_related_object_class = relation.field.rel.edit_inline original = context.get('original', None) bound_related_object = relation.bind(context['form'], original, bound_related_object_class) context['bound_related_object'] = bound_related_object t = loader.get_template(bound_related_object.template_name()) output = t.render(context) context.pop() return output def output_all(form_fields): return ''.join([str(f) for f in form_fields]) output_all = register.simple_tag(output_all) def auto_populated_field_script(auto_pop_fields, change = False): t = [] for field in auto_pop_fields: if change: t.append('document.getElementById("id_%s")._changed = true;' % field.name) else: t.append('document.getElementById("id_%s").onchange = function() { this._changed = true; };' % field.name) add_values = ' + " " + '.join(['document.getElementById("id_%s").value' % g for g in field.prepopulate_from]) for f in field.prepopulate_from: t.append('document.getElementById("id_%s").onkeyup = function() {' \ ' var e = document.getElementById("id_%s");' \ ' if(!e._changed) { e.value = URLify(%s, %s);} }; ' % ( f, field.name, add_values, field.maxlength)) return ''.join(t) auto_populated_field_script = register.simple_tag(auto_populated_field_script) def filter_interface_script_maybe(bound_field): f = bound_field.field if f.rel and isinstance(f.rel, models.ManyToManyRel) and f.rel.filter_interface: return '<script type="text/javascript">addEvent(window, "load", function(e) {' \ ' SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % ( f.name, f.verbose_name.replace('"', '\\"'), f.rel.filter_interface-1, settings.ADMIN_MEDIA_PREFIX) else: return '' filter_interface_script_maybe = register.simple_tag(filter_interface_script_maybe) def field_widget(parser, token): bits = token.contents.split() if len(bits) != 2: raise template.TemplateSyntaxError, "%s takes 1 argument" % bits[0] return FieldWidgetNode(bits[1]) field_widget = register.tag(field_widget) def edit_inline(parser, token): bits = token.contents.split() if len(bits) != 2: raise template.TemplateSyntaxError, "%s takes 1 argument" % bits[0] return EditInlineNode(bits[1]) edit_inline = register.tag(edit_inline) def admin_field_line(context, argument_val): if isinstance(argument_val, AdminBoundField): bound_fields = [argument_val] else: bound_fields = [bf for bf in argument_val] add = context['add'] change = context['change'] class_names = ['form-row'] for bound_field in bound_fields: for f in bound_field.form_fields: if f.errors(): class_names.append('errors') break # Assumes BooleanFields won't be stacked next to each other! if isinstance(bound_fields[0].field, models.BooleanField): class_names.append('checkbox-row') return { 'add': context['add'], 'change': context['change'], 'bound_fields': bound_fields, 'class_names': " ".join(class_names), } admin_field_line = register.inclusion_tag('admin/field_line.html', takes_context=True)(admin_field_line)
Python
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)
Python
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 from django.utils.text import capfirst from django.utils.translation import get_date_formats, get_partial_date_formats from django.template import Library import datetime register = Library() DOT = '.' def paginator_number(cl,i): if i == DOT: return '... ' elif i == cl.page_num: return '<span class="this-page">%d</span> ' % (i+1) else: return '<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.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.pages <= 10: page_range = range(paginator.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.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.pages - ON_ENDS, paginator.pages)) else: page_range.extend(range(page_num + 1, paginator.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(lookup_opts.admin.list_display): try: f = lookup_opts.get_field(field_name) 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__ is a special-case. if field_name == '__str__': header = lookup_opts.verbose_name else: attr = getattr(cl.model, field_name) # Let AttributeErrors propagate. try: header = attr.short_description except AttributeError: header = field_name.replace('_', ' ') # It is a non-field, but perhaps one that is sortable if not getattr(getattr(cl.model, field_name), "admin_order_field", None): 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: 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": (th_classes and ' class="%s"' % ' '.join(th_classes) or '')} def _boolean_icon(field_val): BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} return '<img src="%simg/admin/icon-%s.gif" alt="%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.lookup_opts.admin.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 # or a property. try: attr = getattr(result, field_name) allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if callable(attr): attr = attr() if boolean: allow_tags = True result_repr = _boolean_icon(attr) else: result_repr = str(attr) 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: 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) # FloatFields are special: Zero-pad the decimals. elif isinstance(f, models.FloatField): 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(str(field_val)) if result_repr == '': result_repr = '&nbsp;' # If list_display_links not defined, add the link tag to the first field if (first and not cl.lookup_opts.admin.list_display_links) or field_name in cl.lookup_opts.admin.list_display_links: table_tag = {True:'th', False:'td'}[first] first = False url = cl.url_for_result(result) result_id = str(getattr(result, pk)) # str() is needed in case of 23L (long ints) yield ('<%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %r); return false;"' % result_id or ''), result_repr, table_tag)) else: yield ('<td%s>%s</td>' % (row_class, 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.lookup_opts.admin.date_hierarchy: field_name = cl.lookup_opts.admin.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: 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 and not cl.opts.one_to_one_field, 'search_var': SEARCH_VAR } search_form = register.inclusion_tag('admin/search_form.html')(search_form) def filter(cl, spec): return {'title': spec.title(), 'choices' : list(spec.choices(cl))} filter = register.inclusion_tag('admin/filter.html')(filter) def filters(cl): return {'cl': cl} filters = register.inclusion_tag('admin/filters.html')(filters)
Python
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 "<GetAdminLog Node>" def render(self, context): if self.user is not None and 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'))
Python
from django.utils.translation import ngettext from django.utils.translation import gettext_lazy as _ from django import template import re register = template.Library() def ordinal(value): """ Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except ValueError: return value t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th')) if value % 100 in (11, 12, 13): # special case return "%d%s" % (value, t[0]) return '%d%s' % (value, t[value % 10]) register.filter(ordinal) def intcomma(value): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = str(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value)) if orig == new: return new else: return intcomma(new) register.filter(intcomma) def intword(value): """ Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ value = int(value) if value < 1000000: return value if value < 1000000000: new_value = value / 1000000.0 return ngettext('%(value).1f million', '%(value).1f million', new_value) % {'value': new_value} if value < 1000000000000: new_value = value / 1000000000.0 return ngettext('%(value).1f billion', '%(value).1f billion', new_value) % {'value': new_value} if value < 1000000000000000: new_value = value / 1000000000000.0 return ngettext('%(value).1f trillion', '%(value).1f trillion', new_value) % {'value': new_value} return value register.filter(intword) def apnumber(value): """ For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. """ try: value = int(value) except ValueError: return value if not 0 < value < 10: return value return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'), _('seven'), _('eight'), _('nine'))[value-1] register.filter(apnumber)
Python
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from django.conf import settings import datetime MIN_PHOTO_DIMENSION = 5 MAX_PHOTO_DIMENSION = 1000 # option codes for comment-form hidden fields PHOTOS_REQUIRED = 'pr' PHOTOS_OPTIONAL = 'pa' RATINGS_REQUIRED = 'rr' RATINGS_OPTIONAL = 'ra' IS_PUBLIC = 'ip' # what users get if they don't have any karma DEFAULT_KARMA = 5 KARMA_NEEDED_BEFORE_DISPLAYED = 3 class CommentManager(models.Manager): def get_security_hash(self, options, photo_options, rating_options, target): """ Returns the MD5 hash of the given options (a comma-separated string such as 'pa,ra') and target (something like 'lcom.eventtimes:5157'). Used to validate that submitted form options have not been tampered-with. """ import md5 return md5.new(options + photo_options + rating_options + target + settings.SECRET_KEY).hexdigest() def get_rating_options(self, rating_string): """ Given a rating_string, this returns a tuple of (rating_range, options). >>> s = "scale:1-10|First_category|Second_category" >>> Comment.objects.get_rating_options(s) ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ['First category', 'Second category']) """ rating_range, options = rating_string.split('|', 1) rating_range = range(int(rating_range[6:].split('-')[0]), int(rating_range[6:].split('-')[1])+1) choices = [c.replace('_', ' ') for c in options.split('|')] return rating_range, choices def get_list_with_karma(self, **kwargs): """ Returns a list of Comment objects matching the given lookup terms, with _karma_total_good and _karma_total_bad filled. """ extra_kwargs = {} extra_kwargs.setdefault('select', {}) extra_kwargs['select']['_karma_total_good'] = 'SELECT COUNT(*) FROM comments_karmascore, comments_comment WHERE comments_karmascore.comment_id=comments_comment.id AND score=1' extra_kwargs['select']['_karma_total_bad'] = 'SELECT COUNT(*) FROM comments_karmascore, comments_comment WHERE comments_karmascore.comment_id=comments_comment.id AND score=-1' return self.filter(**kwargs).extra(**extra_kwargs) def user_is_moderator(self, user): if user.is_superuser: return True for g in user.groups.all(): if g.id == settings.COMMENTS_MODERATORS_GROUP: return True return False class Comment(models.Model): user = models.ForeignKey(User, raw_id_admin=True) content_type = models.ForeignKey(ContentType) object_id = models.IntegerField(_('object ID')) headline = models.CharField(_('headline'), maxlength=255, blank=True) comment = models.TextField(_('comment'), maxlength=3000) rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True) rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True) rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True) rating4 = models.PositiveSmallIntegerField(_('rating #4'), blank=True, null=True) rating5 = models.PositiveSmallIntegerField(_('rating #5'), blank=True, null=True) rating6 = models.PositiveSmallIntegerField(_('rating #6'), blank=True, null=True) rating7 = models.PositiveSmallIntegerField(_('rating #7'), blank=True, null=True) rating8 = models.PositiveSmallIntegerField(_('rating #8'), blank=True, null=True) # This field designates whether to use this row's ratings in aggregate # functions (summaries). We need this because people are allowed to post # multiple reviews on the same thing, but the system will only use the # latest one (with valid_rating=True) in tallying the reviews. valid_rating = models.BooleanField(_('is valid rating')) submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True) is_public = models.BooleanField(_('is public')) ip_address = models.IPAddressField(_('IP address'), blank=True, null=True) is_removed = models.BooleanField(_('is removed'), help_text=_('Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.')) site = models.ForeignKey(Site) objects = CommentManager() class Meta: verbose_name = _('comment') verbose_name_plural = _('comments') ordering = ('-submit_date',) class Admin: fields = ( (None, {'fields': ('content_type', 'object_id', 'site')}), ('Content', {'fields': ('user', 'headline', 'comment')}), ('Ratings', {'fields': ('rating1', 'rating2', 'rating3', 'rating4', 'rating5', 'rating6', 'rating7', 'rating8', 'valid_rating')}), ('Meta', {'fields': ('is_public', 'is_removed', 'ip_address')}), ) list_display = ('user', 'submit_date', 'content_type', 'get_content_object') list_filter = ('submit_date',) date_hierarchy = 'submit_date' search_fields = ('comment', 'user__username') def __repr__(self): return "%s: %s..." % (self.user.username, self.comment[:100]) def get_absolute_url(self): return self.get_content_object().get_absolute_url() + "#c" + str(self.id) def get_crossdomain_url(self): return "/r/%d/%d/" % (self.content_type_id, self.object_id) def get_flag_url(self): return "/comments/flag/%s/" % self.id def get_deletion_url(self): return "/comments/delete/%s/" % self.id def get_content_object(self): """ Returns the object that this comment is a comment on. Returns None if the object no longer exists. """ from django.core.exceptions import ObjectDoesNotExist try: return self.content_type.get_object_for_this_type(pk=self.object_id) except ObjectDoesNotExist: return None get_content_object.short_description = _('Content object') def _fill_karma_cache(self): "Helper function that populates good/bad karma caches" good, bad = 0, 0 for k in self.karmascore_set: if k.score == -1: bad +=1 elif k.score == 1: good +=1 self._karma_total_good, self._karma_total_bad = good, bad def get_good_karma_total(self): if not hasattr(self, "_karma_total_good"): self._fill_karma_cache() return self._karma_total_good def get_bad_karma_total(self): if not hasattr(self, "_karma_total_bad"): self._fill_karma_cache() return self._karma_total_bad def get_karma_total(self): if not hasattr(self, "_karma_total_good") or not hasattr(self, "_karma_total_bad"): self._fill_karma_cache() return self._karma_total_good + self._karma_total_bad def get_as_text(self): return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % \ {'user': self.user.username, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url()} class FreeComment(models.Model): # A FreeComment is a comment by a non-registered user. content_type = models.ForeignKey(ContentType) object_id = models.IntegerField(_('object ID')) comment = models.TextField(_('comment'), maxlength=3000) person_name = models.CharField(_("person's name"), maxlength=50) submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True) is_public = models.BooleanField(_('is public')) ip_address = models.IPAddressField(_('ip address')) # TODO: Change this to is_removed, like Comment approved = models.BooleanField(_('approved by staff')) site = models.ForeignKey(Site) class Meta: verbose_name = _('free comment') verbose_name_plural = _('free comments') ordering = ('-submit_date',) class Admin: fields = ( (None, {'fields': ('content_type', 'object_id', 'site')}), ('Content', {'fields': ('person_name', 'comment')}), ('Meta', {'fields': ('submit_date', 'is_public', 'ip_address', 'approved')}), ) list_display = ('person_name', 'submit_date', 'content_type', 'get_content_object') list_filter = ('submit_date',) date_hierarchy = 'submit_date' search_fields = ('comment', 'person_name') def __repr__(self): return "%s: %s..." % (self.person_name, self.comment[:100]) def get_absolute_url(self): return self.get_content_object().get_absolute_url() + "#c" + str(self.id) def get_content_object(self): """ Returns the object that this comment is a comment on. Returns None if the object no longer exists. """ from django.core.exceptions import ObjectDoesNotExist try: return self.content_type.get_object_for_this_type(pk=self.object_id) except ObjectDoesNotExist: return None get_content_object.short_description = _('Content object') class KarmaScoreManager(models.Manager): def vote(self, user_id, comment_id, score): try: karma = self.objects.get(comment__pk=comment_id, user__pk=user_id) except self.model.DoesNotExist: karma = self.model(None, user_id=user_id, comment_id=comment_id, score=score, scored_date=datetime.datetime.now()) karma.save() else: karma.score = score karma.scored_date = datetime.datetime.now() karma.save() def get_pretty_score(self, score): """ Given a score between -1 and 1 (inclusive), returns the same score on a scale between 1 and 10 (inclusive), as an integer. """ if score is None: return DEFAULT_KARMA return int(round((4.5 * score) + 5.5)) class KarmaScore(models.Model): user = models.ForeignKey(User) comment = models.ForeignKey(Comment) score = models.SmallIntegerField(_('score'), db_index=True) scored_date = models.DateTimeField(_('score date'), auto_now=True) objects = KarmaScoreManager() class Meta: verbose_name = _('karma score') verbose_name_plural = _('karma scores') unique_together = (('user', 'comment'),) def __repr__(self): return _("%(score)d rating by %(user)s") % {'score': self.score, 'user': self.user} class UserFlagManager(models.Manager): def flag(self, comment, user): """ Flags the given comment by the given user. If the comment has already been flagged by the user, or it was a comment posted by the user, nothing happens. """ if int(comment.user_id) == int(user.id): return # A user can't flag his own comment. Fail silently. try: f = self.objects.get(user__pk=user.id, comment__pk=comment.id) except self.model.DoesNotExist: from django.core.mail import mail_managers f = self.model(None, user.id, comment.id, None) message = _('This comment was flagged by %(user)s:\n\n%(text)s') % {'user': user.username, 'text': comment.get_as_text()} mail_managers('Comment flagged', message, fail_silently=True) f.save() class UserFlag(models.Model): user = models.ForeignKey(User) comment = models.ForeignKey(Comment) flag_date = models.DateTimeField(_('flag date'), auto_now_add=True) objects = UserFlagManager() class Meta: verbose_name = _('user flag') verbose_name_plural = _('user flags') unique_together = (('user', 'comment'),) def __repr__(self): return _("Flag by %r") % self.user class ModeratorDeletion(models.Model): user = models.ForeignKey(User, verbose_name='moderator') comment = models.ForeignKey(Comment) deletion_date = models.DateTimeField(_('deletion date'), auto_now_add=True) class Meta: verbose_name = _('moderator deletion') verbose_name_plural = _('moderator deletions') unique_together = (('user', 'comment'),) def __repr__(self): return _("Moderator deletion by %r") % self.user
Python
from django.conf import settings from django.contrib.comments.models import Comment, FreeComment from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site class LatestFreeCommentsFeed(Feed): "Feed of latest comments on the current site." comments_class = FreeComment def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "Latest comments on %s" % self._site.name def items(self): return self.comments_class.objects.filter(site__pk=settings.SITE_ID, is_public=True)[:40] class LatestCommentsFeed(LatestFreeCommentsFeed): """Feed of latest free comments on the current site""" comments_class = Comment def items(self): qs = LatestFreeCommentsFeed.items(self) qs = qs.filter(is_removed=False) if settings.COMMENTS_BANNED_USERS_GROUP: where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs
Python
from django.conf.urls.defaults import * urlpatterns = patterns('django.contrib.comments.views', (r'^post/$', 'comments.post_comment'), (r'^postfree/$', 'comments.post_free_comment'), (r'^posted/$', 'comments.comment_was_posted'), (r'^karma/vote/(?P<comment_id>\d+)/(?P<vote>up|down)/$', 'karma.vote'), (r'^flag/(?P<comment_id>\d+)/$', 'userflags.flag'), (r'^flag/(?P<comment_id>\d+)/done/$', 'userflags.flag_done'), (r'^delete/(?P<comment_id>\d+)/$', 'userflags.delete'), (r'^delete/(?P<comment_id>\d+)/done/$', 'userflags.delete_done'), )
Python
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404 from django.contrib.comments.models import Comment, ModeratorDeletion, UserFlag from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.conf import settings def flag(request, comment_id): """ Flags a comment. Confirmation on GET, action on POST. Templates: `comments/flag_verify`, `comments/flag_done` Context: comment the flagged `comments.comments` object """ comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) if request.POST: UserFlag.objects.flag(comment, request.user) return HttpResponseRedirect('%sdone/' % request.path) return render_to_response('comments/flag_verify.html', {'comment': comment}, context_instance=RequestContext(request)) flag = login_required(flag) def flag_done(request, comment_id): comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) return render_to_response('comments/flag_done.html', {'comment': comment}, context_instance=RequestContext(request)) def delete(request, comment_id): """ Deletes a comment. Confirmation on GET, action on POST. Templates: `comments/delete_verify`, `comments/delete_done` Context: comment the flagged `comments.comments` object """ comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) if not Comment.objects.user_is_moderator(request.user): raise Http404 if request.POST: # If the comment has already been removed, silently fail. if not comment.is_removed: comment.is_removed = True comment.save() m = ModeratorDeletion(None, request.user.id, comment.id, None) m.save() return HttpResponseRedirect('%sdone/' % request.path) return render_to_response('comments/delete_verify.html', {'comment': comment}, context_instance=RequestContext(request)) delete = login_required(delete) def delete_done(request, comment_id): comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) return render_to_response('comments/delete_done.html', {'comment': comment}, context_instance=RequestContext(request))
Python
from django.http import Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.comments.models import Comment, KarmaScore def vote(request, comment_id, vote): """ Rate a comment (+1 or -1) Templates: `karma_vote_accepted` Context: comment `comments.comments` object being rated """ rating = {'up': 1, 'down': -1}.get(vote, False) if not rating: raise Http404, "Invalid vote" if not request.user.is_authenticated(): raise Http404, _("Anonymous users cannot vote") try: comment = Comment.objects.get(pk=comment_id) except Comment.DoesNotExist: raise Http404, _("Invalid comment ID") if comment.user.id == request.user.id: raise Http404, _("No voting for yourself") KarmaScore.objects.vote(request.user.id, comment_id, rating) # Reload comment to ensure we have up to date karma count comment = Comment.objects.get(pk=comment_id) return render_to_response('comments/karma_vote_accepted.html', {'comment': comment}, context_instance=RequestContext(request))
Python
from django.core import validators from django import oldforms from django.core.mail import mail_admins, mail_managers from django.http import Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.comments.models import Comment, FreeComment, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC from django.contrib.contenttypes.models import ContentType from django.contrib.auth.forms import AuthenticationForm from django.http import HttpResponseRedirect from django.utils.text import normalize_newlines from django.conf import settings from django.utils.translation import ngettext import base64, datetime COMMENTS_PER_PAGE = 20 class PublicCommentManipulator(AuthenticationForm): "Manipulator that handles public registered comments" def __init__(self, user, ratings_required, ratings_range, num_rating_choices): AuthenticationForm.__init__(self) self.ratings_range, self.num_rating_choices = ratings_range, num_rating_choices choices = [(c, c) for c in ratings_range] def get_validator_list(rating_num): if rating_num <= num_rating_choices: return [validators.RequiredIfOtherFieldsGiven(['rating%d' % i for i in range(1, 9) if i != rating_num], _("This rating is required because you've entered at least one other rating."))] else: return [] self.fields.extend([ oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, validator_list=[self.hasNoProfanities]), oldforms.RadioSelectField(field_name="rating1", choices=choices, is_required=ratings_required and num_rating_choices > 0, validator_list=get_validator_list(1), ), oldforms.RadioSelectField(field_name="rating2", choices=choices, is_required=ratings_required and num_rating_choices > 1, validator_list=get_validator_list(2), ), oldforms.RadioSelectField(field_name="rating3", choices=choices, is_required=ratings_required and num_rating_choices > 2, validator_list=get_validator_list(3), ), oldforms.RadioSelectField(field_name="rating4", choices=choices, is_required=ratings_required and num_rating_choices > 3, validator_list=get_validator_list(4), ), oldforms.RadioSelectField(field_name="rating5", choices=choices, is_required=ratings_required and num_rating_choices > 4, validator_list=get_validator_list(5), ), oldforms.RadioSelectField(field_name="rating6", choices=choices, is_required=ratings_required and num_rating_choices > 5, validator_list=get_validator_list(6), ), oldforms.RadioSelectField(field_name="rating7", choices=choices, is_required=ratings_required and num_rating_choices > 6, validator_list=get_validator_list(7), ), oldforms.RadioSelectField(field_name="rating8", choices=choices, is_required=ratings_required and num_rating_choices > 7, validator_list=get_validator_list(8), ), ]) if user.is_authenticated(): self["username"].is_required = False self["username"].validator_list = [] self["password"].is_required = False self["password"].validator_list = [] self.user_cache = user def hasNoProfanities(self, field_data, all_data): if settings.COMMENTS_ALLOW_PROFANITIES: return return validators.hasNoProfanities(field_data, all_data) def get_comment(self, new_data): "Helper function" return Comment(None, self.get_user_id(), new_data["content_type_id"], new_data["object_id"], new_data.get("headline", "").strip(), new_data["comment"].strip(), new_data.get("rating1", None), new_data.get("rating2", None), new_data.get("rating3", None), new_data.get("rating4", None), new_data.get("rating5", None), new_data.get("rating6", None), new_data.get("rating7", None), new_data.get("rating8", None), new_data.get("rating1", None) is not None, datetime.datetime.now(), new_data["is_public"], new_data["ip_address"], False, settings.SITE_ID) def save(self, new_data): today = datetime.date.today() c = self.get_comment(new_data) for old in Comment.objects.filter(content_type__id__exact=new_data["content_type_id"], object_id__exact=new_data["object_id"], user__id__exact=self.get_user_id()): # Check that this comment isn't duplicate. (Sometimes people post # comments twice by mistake.) If it is, fail silently by pretending # the comment was posted successfully. if old.submit_date.date() == today and old.comment == c.comment \ and old.rating1 == c.rating1 and old.rating2 == c.rating2 \ and old.rating3 == c.rating3 and old.rating4 == c.rating4 \ and old.rating5 == c.rating5 and old.rating6 == c.rating6 \ and old.rating7 == c.rating7 and old.rating8 == c.rating8: return old # If the user is leaving a rating, invalidate all old ratings. if c.rating1 is not None: old.valid_rating = False old.save() c.save() # If the commentor has posted fewer than COMMENTS_FIRST_FEW comments, # send the comment to the managers. if self.user_cache.comment_set.count() <= settings.COMMENTS_FIRST_FEW: message = ngettext('This comment was posted by a user who has posted fewer than %(count)s comment:\n\n%(text)s', 'This comment was posted by a user who has posted fewer than %(count)s comments:\n\n%(text)s', settings.COMMENTS_FIRST_FEW) % \ {'count': settings.COMMENTS_FIRST_FEW, 'text': c.get_as_text()} mail_managers("Comment posted by rookie user", message) if settings.COMMENTS_SKETCHY_USERS_GROUP and settings.COMMENTS_SKETCHY_USERS_GROUP in [g.id for g in self.user_cache.get_group_list()]: message = _('This comment was posted by a sketchy user:\n\n%(text)s') % {'text': c.get_as_text()} mail_managers("Comment posted by sketchy user (%s)" % self.user_cache.username, c.get_as_text()) return c class PublicFreeCommentManipulator(oldforms.Manipulator): "Manipulator that handles public free (unregistered) comments" def __init__(self): self.fields = ( oldforms.TextField(field_name="person_name", maxlength=50, is_required=True, validator_list=[self.hasNoProfanities]), oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, validator_list=[self.hasNoProfanities]), ) def hasNoProfanities(self, field_data, all_data): if settings.COMMENTS_ALLOW_PROFANITIES: return return validators.hasNoProfanities(field_data, all_data) def get_comment(self, new_data): "Helper function" return FreeComment(None, new_data["content_type_id"], new_data["object_id"], new_data["comment"].strip(), new_data["person_name"].strip(), datetime.datetime.now(), new_data["is_public"], new_data["ip_address"], False, settings.SITE_ID) def save(self, new_data): today = datetime.date.today() c = self.get_comment(new_data) # Check that this comment isn't duplicate. (Sometimes people post # comments twice by mistake.) If it is, fail silently by pretending # the comment was posted successfully. for old_comment in FreeComment.objects.filter(content_type__id__exact=new_data["content_type_id"], object_id__exact=new_data["object_id"], person_name__exact=new_data["person_name"], submit_date__year=today.year, submit_date__month=today.month, submit_date__day=today.day): if old_comment.comment == c.comment: return old_comment c.save() return c def post_comment(request): """ Post a comment Redirects to the `comments.comments.comment_was_posted` view upon success. Templates: `comment_preview` Context: comment the comment being posted comment_form the comment form options comment options target comment target hash security hash (must be included in a posted form to succesfully post a comment). rating_options comment ratings options ratings_optional are ratings optional? ratings_required are ratings required? rating_range range of ratings rating_choices choice of ratings """ if not request.POST: raise Http404, _("Only POSTs are allowed") try: options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo'] except KeyError: raise Http404, _("One or more of the required fields wasn't submitted") photo_options = request.POST.get('photo_options', '') rating_options = normalize_newlines(request.POST.get('rating_options', '')) if Comment.objects.get_security_hash(options, photo_options, rating_options, target) != security_hash: raise Http404, _("Somebody tampered with the comment form (security violation)") # Now we can be assured the data is valid. if rating_options: rating_range, rating_choices = Comment.objects.get_rating_options(base64.decodestring(rating_options)) else: rating_range, rating_choices = [], [] content_type_id, object_id = target.split(':') # target is something like '52:5157' try: obj = ContentType.objects.get(pk=content_type_id).get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid") option_list = options.split(',') # options is something like 'pa,ra' new_data = request.POST.copy() new_data['content_type_id'] = content_type_id new_data['object_id'] = object_id new_data['ip_address'] = request.META.get('REMOTE_ADDR') new_data['is_public'] = IS_PUBLIC in option_list manipulator = PublicCommentManipulator(request.user, ratings_required=RATINGS_REQUIRED in option_list, ratings_range=rating_range, num_rating_choices=len(rating_choices)) errors = manipulator.get_validation_errors(new_data) # If user gave correct username/password and wasn't already logged in, log them in # so they don't have to enter a username/password again. if manipulator.get_user() and not manipulator.get_user().is_authenticated() and new_data.has_key('password') and manipulator.get_user().check_password(new_data['password']): from django.contrib.auth import login login(request, manipulator.get_user()) if errors or request.POST.has_key('preview'): class CommentFormWrapper(oldforms.FormWrapper): def __init__(self, manipulator, new_data, errors, rating_choices): oldforms.FormWrapper.__init__(self, manipulator, new_data, errors) self.rating_choices = rating_choices def ratings(self): field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))] for i, f in enumerate(field_list): f.choice = rating_choices[i] return field_list comment = errors and '' or manipulator.get_comment(new_data) comment_form = CommentFormWrapper(manipulator, new_data, errors, rating_choices) return render_to_response('comments/preview.html', { 'comment': comment, 'comment_form': comment_form, 'options': options, 'target': target, 'hash': security_hash, 'rating_options': rating_options, 'ratings_optional': RATINGS_OPTIONAL in option_list, 'ratings_required': RATINGS_REQUIRED in option_list, 'rating_range': rating_range, 'rating_choices': rating_choices, }, context_instance=RequestContext(request)) elif request.POST.has_key('post'): # If the IP is banned, mail the admins, do NOT save the comment, and # serve up the "Thanks for posting" page as if the comment WAS posted. if request.META['REMOTE_ADDR'] in settings.BANNED_IPS: mail_admins("Banned IP attempted to post comment", str(request.POST) + "\n\n" + str(request.META)) else: manipulator.do_html2python(new_data) comment = manipulator.save(new_data) return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id)) else: raise Http404, _("The comment form didn't provide either 'preview' or 'post'") def post_free_comment(request): """ Post a free comment (not requiring a log in) Redirects to `comments.comments.comment_was_posted` view on success. Templates: `comment_free_preview` Context: comment comment being posted comment_form comment form object options comment options target comment target hash security hash (must be included in a posted form to succesfully post a comment). """ if not request.POST: raise Http404, _("Only POSTs are allowed") try: options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo'] except KeyError: raise Http404, _("One or more of the required fields wasn't submitted") if Comment.objects.get_security_hash(options, '', '', target) != security_hash: raise Http404, _("Somebody tampered with the comment form (security violation)") content_type_id, object_id = target.split(':') # target is something like '52:5157' content_type = ContentType.objects.get(pk=content_type_id) try: obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid") option_list = options.split(',') new_data = request.POST.copy() new_data['content_type_id'] = content_type_id new_data['object_id'] = object_id new_data['ip_address'] = request.META['REMOTE_ADDR'] new_data['is_public'] = IS_PUBLIC in option_list manipulator = PublicFreeCommentManipulator() errors = manipulator.get_validation_errors(new_data) if errors or request.POST.has_key('preview'): comment = errors and '' or manipulator.get_comment(new_data) return render_to_response('comments/free_preview.html', { 'comment': comment, 'comment_form': oldforms.FormWrapper(manipulator, new_data, errors), 'options': options, 'target': target, 'hash': security_hash, }, context_instance=RequestContext(request)) elif request.POST.has_key('post'): # If the IP is banned, mail the admins, do NOT save the comment, and # serve up the "Thanks for posting" page as if the comment WAS posted. if request.META['REMOTE_ADDR'] in settings.BANNED_IPS: from django.core.mail import mail_admins mail_admins("Practical joker", str(request.POST) + "\n\n" + str(request.META)) else: manipulator.do_html2python(new_data) comment = manipulator.save(new_data) return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id)) else: raise Http404, _("The comment form didn't provide either 'preview' or 'post'") def comment_was_posted(request): """ Display "comment was posted" success page Templates: `comment_posted` Context: object The object the comment was posted on """ obj = None if request.GET.has_key('c'): content_type_id, object_id = request.GET['c'].split(':') try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: pass return render_to_response('comments/posted.html', {'object': obj}, context_instance=RequestContext(request))
Python
from django.contrib.comments.models import Comment, FreeComment from django.contrib.comments.models import PHOTOS_REQUIRED, PHOTOS_OPTIONAL, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC from django.contrib.comments.models import MIN_PHOTO_DIMENSION, MAX_PHOTO_DIMENSION from django import template from django.template import loader from django.core.exceptions import ObjectDoesNotExist from django.contrib.contenttypes.models import ContentType import re register = template.Library() COMMENT_FORM = 'comments/form.html' FREE_COMMENT_FORM = 'comments/freeform.html' class CommentFormNode(template.Node): def __init__(self, content_type, obj_id_lookup_var, obj_id, free, photos_optional=False, photos_required=False, photo_options='', ratings_optional=False, ratings_required=False, rating_options='', is_public=True): self.content_type = content_type self.obj_id_lookup_var, self.obj_id, self.free = obj_id_lookup_var, obj_id, free self.photos_optional, self.photos_required = photos_optional, photos_required self.ratings_optional, self.ratings_required = ratings_optional, ratings_required self.photo_options, self.rating_options = photo_options, rating_options self.is_public = is_public def render(self, context): from django.utils.text import normalize_newlines import base64 context.push() if self.obj_id_lookup_var is not None: try: self.obj_id = template.resolve_variable(self.obj_id_lookup_var, context) except template.VariableDoesNotExist: return '' # Validate that this object ID is valid for this content-type. # We only have to do this validation if obj_id_lookup_var is provided, # because do_comment_form() validates hard-coded object IDs. try: self.content_type.get_object_for_this_type(pk=self.obj_id) except ObjectDoesNotExist: context['display_form'] = False else: context['display_form'] = True else: context['display_form'] = True context['target'] = '%s:%s' % (self.content_type.id, self.obj_id) options = [] for var, abbr in (('photos_required', PHOTOS_REQUIRED), ('photos_optional', PHOTOS_OPTIONAL), ('ratings_required', RATINGS_REQUIRED), ('ratings_optional', RATINGS_OPTIONAL), ('is_public', IS_PUBLIC)): context[var] = getattr(self, var) if getattr(self, var): options.append(abbr) context['options'] = ','.join(options) if self.free: context['hash'] = Comment.objects.get_security_hash(context['options'], '', '', context['target']) default_form = loader.get_template(FREE_COMMENT_FORM) else: context['photo_options'] = self.photo_options context['rating_options'] = normalize_newlines(base64.encodestring(self.rating_options).strip()) if self.rating_options: context['rating_range'], context['rating_choices'] = Comment.objects.get_rating_options(self.rating_options) context['hash'] = Comment.objects.get_security_hash(context['options'], context['photo_options'], context['rating_options'], context['target']) default_form = loader.get_template(COMMENT_FORM) output = default_form.render(context) context.pop() return output class CommentCountNode(template.Node): def __init__(self, package, module, context_var_name, obj_id, var_name, free): self.package, self.module = package, module self.context_var_name, self.obj_id = context_var_name, obj_id self.var_name, self.free = var_name, free def render(self, context): from django.conf import settings manager = self.free and FreeComment.objects or Comment.objects if self.context_var_name is not None: self.obj_id = template.resolve_variable(self.context_var_name, context) comment_count = manager.filter(object_id__exact=self.obj_id, content_type__app_label__exact=self.package, content_type__model__exact=self.module, site__id__exact=settings.SITE_ID).count() context[self.var_name] = comment_count return '' class CommentListNode(template.Node): def __init__(self, package, module, context_var_name, obj_id, var_name, free, ordering, extra_kwargs=None): self.package, self.module = package, module self.context_var_name, self.obj_id = context_var_name, obj_id self.var_name, self.free = var_name, free self.ordering = ordering self.extra_kwargs = extra_kwargs or {} def render(self, context): from django.conf import settings get_list_function = self.free and FreeComment.objects.filter or Comment.objects.get_list_with_karma if self.context_var_name is not None: try: self.obj_id = template.resolve_variable(self.context_var_name, context) except template.VariableDoesNotExist: return '' kwargs = { 'object_id__exact': self.obj_id, 'content_type__app_label__exact': self.package, 'content_type__model__exact': self.module, 'site__id__exact': settings.SITE_ID, } kwargs.update(self.extra_kwargs) if not self.free and settings.COMMENTS_BANNED_USERS_GROUP: kwargs['select'] = {'is_hidden': 'user_id IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)' % settings.COMMENTS_BANNED_USERS_GROUP} comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related() if not self.free: if context.has_key('user') and context['user'].is_authenticated(): user_id = context['user'].id context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user']) else: user_id = None context['user_can_moderate_comments'] = False # Only display comments by banned users to those users themselves. if settings.COMMENTS_BANNED_USERS_GROUP: comment_list = [c for c in comment_list if not c.is_hidden or (user_id == c.user_id)] context[self.var_name] = comment_list return '' class DoCommentForm: """ Displays a comment form for the given params. Syntax:: {% comment_form for [pkg].[py_module_name] [context_var_containing_obj_id] with [list of options] %} Example usage:: {% comment_form for lcom.eventtimes event.id with is_public yes photos_optional thumbs,200,400 ratings_optional scale:1-5|first_option|second_option %} ``[context_var_containing_obj_id]`` can be a hard-coded integer or a variable containing the ID. """ def __init__(self, free): self.free = free def __call__(self, parser, token): tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError, "%r tag requires at least 3 arguments" % tokens[0] if tokens[1] != 'for': raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0] try: package, module = tokens[2].split('.') except ValueError: # unpack list of wrong size raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0] try: content_type = ContentType.objects.get(app_label__exact=package, model__exact=module) except ContentType.DoesNotExist: raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module) obj_id_lookup_var, obj_id = None, None if tokens[3].isdigit(): obj_id = tokens[3] try: # ensure the object ID is valid content_type.get_object_for_this_type(pk=obj_id) except ObjectDoesNotExist: raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id) else: obj_id_lookup_var = tokens[3] kwargs = {} if len(tokens) > 4: if tokens[4] != 'with': raise template.TemplateSyntaxError, "Fourth argument in %r tag must be 'with'" % tokens[0] for option, args in zip(tokens[5::2], tokens[6::2]): if option in ('photos_optional', 'photos_required') and not self.free: # VALIDATION ############################################## option_list = args.split(',') if len(option_list) % 3 != 0: raise template.TemplateSyntaxError, "Incorrect number of comma-separated arguments to %r tag" % tokens[0] for opt in option_list[::3]: if not opt.isalnum(): raise template.TemplateSyntaxError, "Invalid photo directory name in %r tag: '%s'" % (tokens[0], opt) for opt in option_list[1::3] + option_list[2::3]: if not opt.isdigit() or not (MIN_PHOTO_DIMENSION <= int(opt) <= MAX_PHOTO_DIMENSION): raise template.TemplateSyntaxError, "Invalid photo dimension in %r tag: '%s'. Only values between %s and %s are allowed." % (tokens[0], opt, MIN_PHOTO_DIMENSION, MAX_PHOTO_DIMENSION) # VALIDATION ENDS ######################################### kwargs[option] = True kwargs['photo_options'] = args elif option in ('ratings_optional', 'ratings_required') and not self.free: # VALIDATION ############################################## if 2 < len(args.split('|')) > 9: raise template.TemplateSyntaxError, "Incorrect number of '%s' options in %r tag. Use between 2 and 8." % (option, tokens[0]) if re.match('^scale:\d+\-\d+\:$', args.split('|')[0]): raise template.TemplateSyntaxError, "Invalid 'scale' in %r tag's '%s' options" % (tokens[0], option) # VALIDATION ENDS ######################################### kwargs[option] = True kwargs['rating_options'] = args elif option in ('is_public'): kwargs[option] = (args == 'true') else: raise template.TemplateSyntaxError, "%r tag got invalid parameter '%s'" % (tokens[0], option) return CommentFormNode(content_type, obj_id_lookup_var, obj_id, self.free, **kwargs) class DoCommentCount: """ Gets comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [pkg].[py_module_name] [context_var_containing_obj_id] as [varname] %} Example usage:: {% get_comment_count for lcom.eventtimes event.id as comment_count %} Note: ``[context_var_containing_obj_id]`` can also be a hard-coded integer, like this:: {% get_comment_count for lcom.eventtimes 23 as comment_count %} """ def __init__(self, free): self.free = free def __call__(self, parser, token): tokens = token.contents.split() # Now tokens is a list like this: # ['get_comment_list', 'for', 'lcom.eventtimes', 'event.id', 'as', 'comment_list'] if len(tokens) != 6: raise template.TemplateSyntaxError, "%r tag requires 5 arguments" % tokens[0] if tokens[1] != 'for': raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0] try: package, module = tokens[2].split('.') except ValueError: # unpack list of wrong size raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0] try: content_type = ContentType.objects.get(app_label__exact=package, model__exact=module) except ContentType.DoesNotExist: raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module) var_name, obj_id = None, None if tokens[3].isdigit(): obj_id = tokens[3] try: # ensure the object ID is valid content_type.get_object_for_this_type(pk=obj_id) except ObjectDoesNotExist: raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id) else: var_name = tokens[3] if tokens[4] != 'as': raise template.TemplateSyntaxError, "Fourth argument in %r must be 'as'" % tokens[0] return CommentCountNode(package, module, var_name, obj_id, tokens[5], self.free) class DoGetCommentList: """ Gets comments for the given params and populates the template context with a special comment_package variable, whose name is defined by the ``as`` clause. Syntax:: {% get_comment_list for [pkg].[py_module_name] [context_var_containing_obj_id] as [varname] (reversed) %} Example usage:: {% get_comment_list for lcom.eventtimes event.id as comment_list %} Note: ``[context_var_containing_obj_id]`` can also be a hard-coded integer, like this:: {% get_comment_list for lcom.eventtimes 23 as comment_list %} To get a list of comments in reverse order -- that is, most recent first -- pass ``reversed`` as the last param:: {% get_comment_list for lcom.eventtimes event.id as comment_list reversed %} """ def __init__(self, free): self.free = free def __call__(self, parser, token): tokens = token.contents.split() # Now tokens is a list like this: # ['get_comment_list', 'for', 'lcom.eventtimes', 'event.id', 'as', 'comment_list'] if not len(tokens) in (6, 7): raise template.TemplateSyntaxError, "%r tag requires 5 or 6 arguments" % tokens[0] if tokens[1] != 'for': raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0] try: package, module = tokens[2].split('.') except ValueError: # unpack list of wrong size raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0] try: content_type = ContentType.objects.get(app_label__exact=package,model__exact=module) except ContentType.DoesNotExist: raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module) var_name, obj_id = None, None if tokens[3].isdigit(): obj_id = tokens[3] try: # ensure the object ID is valid content_type.get_object_for_this_type(pk=obj_id) except ObjectDoesNotExist: raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id) else: var_name = tokens[3] if tokens[4] != 'as': raise template.TemplateSyntaxError, "Fourth argument in %r must be 'as'" % tokens[0] if len(tokens) == 7: if tokens[6] != 'reversed': raise template.TemplateSyntaxError, "Final argument in %r must be 'reversed' if given" % tokens[0] ordering = "-" else: ordering = "" return CommentListNode(package, module, var_name, obj_id, tokens[5], self.free, ordering) # registration comments register.tag('get_comment_list', DoGetCommentList(False)) register.tag('comment_form', DoCommentForm(False)) register.tag('get_comment_count', DoCommentCount(False)) # free comments register.tag('get_free_comment_list', DoGetCommentList(True)) register.tag('free_comment_form', DoCommentForm(True)) register.tag('get_free_comment_count', DoCommentCount(True))
Python
from django.core import urlresolvers import urllib PING_URL = "http://www.google.com/webmasters/sitemaps/ping" class SitemapNotFound(Exception): pass def ping_google(sitemap_url=None, ping_url=PING_URL): """ Alerts Google that the sitemap for the current site has been updated. If sitemap_url is provided, it should be an absolute path to the sitemap for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this function will attempt to deduce it by using urlresolvers.reverse(). """ if sitemap_url is None: try: # First, try to get the "index" sitemap URL. sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index') except urlresolvers.NoReverseMatch: try: # Next, try for the "global" sitemap URL. sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap') except urlresolvers.NoReverseMatch: pass if sitemap_url is None: raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.") from django.contrib.sites.models import Site current_site = Site.objects.get_current() url = "%s%s" % (current_site.domain, sitemap_url) params = urllib.urlencode({'sitemap':url}) urllib.urlopen("%s?%s" % (ping_url, params)) class Sitemap: def __get(self, name, obj, default=None): try: attr = getattr(self, name) except AttributeError: return default if callable(attr): return attr(obj) return attr def items(self): return [] def location(self, obj): return obj.get_absolute_url() def get_urls(self): from django.contrib.sites.models import Site current_site = Site.objects.get_current() urls = [] for item in self.items(): loc = "http://%s%s" % (current_site.domain, self.__get('location', item)) url_info = { 'location': loc, 'lastmod': self.__get('lastmod', item, None), 'changefreq': self.__get('changefreq', item, None), 'priority': self.__get('priority', item, None) } urls.append(url_info) return urls class FlatPageSitemap(Sitemap): def items(self): from django.contrib.sites.models import Site current_site = Site.objects.get_current() return current_site.flatpage_set.all() class GenericSitemap(Sitemap): priority = None changefreq = None def __init__(self, info_dict, priority=None, changefreq=None): self.queryset = info_dict['queryset'] self.date_field = info_dict.get('date_field', None) self.priority = priority self.changefreq = changefreq def items(self): # Make sure to return a clone; we don't want premature evaluation. return self.queryset.filter() def lastmod(self, item): if self.date_field is not None: return getattr(item, self.date_field) return None
Python
from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.models import Site from django.core import urlresolvers def index(request, sitemaps): current_site = Site.objects.get_current() sites = [] protocol = request.is_secure() and 'https' or 'http' for section in sitemaps.keys(): sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap', kwargs={'section': section}) sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url)) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) return HttpResponse(xml, mimetype='application/xml') def sitemap(request, sitemaps, section=None): maps, urls = [], [] if section is not None: if not sitemaps.has_key(section): raise Http404("No sitemap available for section: %r" % section) maps.append(sitemaps[section]) else: maps = sitemaps.values() for site in maps: if callable(site): urls.extend(site().get_urls()) else: urls.extend(site.get_urls()) xml = loader.render_to_string('sitemap.xml', {'urlset': urls}) return HttpResponse(xml, mimetype='application/xml')
Python
import base64, md5, random, sys, datetime import cPickle as pickle from django.db import models from django.utils.translation import gettext_lazy as _ from django.conf import settings class SessionManager(models.Manager): def encode(self, session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict) pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def get_new_session_key(self): "Returns session key that isn't being used." # The random module is seeded when this Apache child is created. # Use person_id and SECRET_KEY as added salt. while 1: session_key = md5.new(str(random.randint(0, sys.maxint - 1)) + str(random.randint(0, sys.maxint - 1)) + settings.SECRET_KEY).hexdigest() try: self.get(session_key=session_key) except self.model.DoesNotExist: break return session_key def get_new_session_object(self): """ Returns a new session object. """ # FIXME: There is a *small* chance of collision here, meaning we will # return an existing object. That can be fixed when we add a way to # validate (and guarantee) that non-auto primary keys are unique. For # now, we save immediately in order to reduce the "window of # misfortune" as much as possible. created = False while not created: obj, created = self.get_or_create(session_key=self.get_new_session_key(), expire_date = datetime.datetime.now()) # Collision in key generation, so re-seed the generator random.seed() return obj def save(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django website). """ session_key = models.CharField(_('session key'), maxlength=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date')) objects = SessionManager() class Meta: db_table = 'django_session' verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): encoded_data = base64.decodestring(self.session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation, "User tampered with session cookie." try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {}
Python
from django.conf import settings from django.contrib.sessions.models import Session from django.core.exceptions import SuspiciousOperation from django.utils.cache import patch_vary_headers import datetime TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' class SessionWrapper(object): def __init__(self, session_key): self.session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def set_test_cookie(self): self[TEST_COOKIE_NAME] = TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(TEST_COOKIE_NAME) == TEST_COOKIE_VALUE def delete_test_cookie(self): del self[TEST_COOKIE_NAME] def _get_session(self): # Lazily loads session from storage. self.accessed = True try: return self._session_cache except AttributeError: if self.session_key is None: self._session_cache = {} else: try: s = Session.objects.get(session_key=self.session_key, expire_date__gt=datetime.datetime.now()) self._session_cache = s.get_decoded() except (Session.DoesNotExist, SuspiciousOperation): self._session_cache = {} # Set the session_key to None to force creation of a new # key, for extra security. self.session_key = None return self._session_cache _session = property(_get_session) class SessionMiddleware(object): def process_request(self, request): request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) def process_response(self, request, response): # If request.session was modified, or if response.session was set, save # those changes and set a session cookie. try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.session_key: session_key = request.session.session_key else: obj = Session.objects.get_new_session_object() session_key = obj.session_key if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: max_age = None expires = None else: max_age = settings.SESSION_COOKIE_AGE expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT") new_session = Session.objects.save(session_key, request.session._session, datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)) response.set_cookie(settings.SESSION_COOKIE_NAME, session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None) return response
Python
from django.conf.urls.defaults import * urlpatterns = patterns('django.contrib.flatpages.views', (r'^(?P<url>.*)$', 'flatpage'), )
Python
from django.core import validators from django.db import models from django.contrib.sites.models import Site from django.utils.translation import gettext_lazy as _ class FlatPage(models.Model): url = models.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL], help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes.")) title = models.CharField(_('title'), maxlength=200) content = models.TextField(_('content')) enable_comments = models.BooleanField(_('enable comments')) template_name = models.CharField(_('template name'), maxlength=70, blank=True, help_text=_("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.")) registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) sites = models.ManyToManyField(Site) class Meta: db_table = 'django_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url',) class Admin: fields = ( (None, {'fields': ('url', 'title', 'content', 'sites')}), ('Advanced options', {'classes': 'collapse', 'fields': ('enable_comments', 'registration_required', 'template_name')}), ) list_filter = ('sites',) search_fields = ('url', 'title') def __str__(self): return "%s -- %s" % (self.url, self.title) def get_absolute_url(self): return self.url
Python
from django.contrib.flatpages.views import flatpage from django.http import Http404 from django.conf import settings class FlatpageFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a flatpage for non-404 responses. try: return flatpage(request, request.path) # Return the original response if any errors happened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except: if settings.DEBUG: raise return response
Python
from django.contrib.flatpages.models import FlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse from django.conf import settings from django.core.xheaders import populate_xheaders DEFAULT_TEMPLATE = 'flatpages/default.html' def flatpage(request, url): """ Flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = "/" + url f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
Python
from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.template import Context, loader from django.core import validators from django import oldforms from django.utils.translation import gettext as _ class UserCreationForm(oldforms.Manipulator): "A form that creates a user, with no privileges, from the given username and password." def __init__(self): self.fields = ( oldforms.TextField(field_name='username', length=30, maxlength=30, is_required=True, validator_list=[validators.isAlphaNumeric, self.isValidUsername]), oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), ) def isValidUsername(self, field_data, all_data): try: User.objects.get(username=field_data) except User.DoesNotExist: return raise validators.ValidationError, _('A user with that username already exists.') def save(self, new_data): "Creates the user." return User.objects.create_user(new_data['username'], '', new_data['password1']) class AuthenticationForm(oldforms.Manipulator): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ def __init__(self, request=None): """ If request is passed in, the manipulator will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validator. """ self.request = request self.fields = [ oldforms.TextField(field_name="username", length=15, maxlength=30, is_required=True, validator_list=[self.isValidUser, self.hasCookiesEnabled]), oldforms.PasswordField(field_name="password", length=15, maxlength=30, is_required=True), ] self.user_cache = None def hasCookiesEnabled(self, field_data, all_data): if self.request and not self.request.session.test_cookie_worked(): raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.") def isValidUser(self, field_data, all_data): username = field_data password = all_data.get('password', None) self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.") elif not self.user_cache.is_active: raise validators.ValidationError, _("This account is inactive.") def get_user_id(self): if self.user_cache: return self.user_cache.id return None def get_user(self): return self.user_cache class PasswordResetForm(oldforms.Manipulator): "A form that lets a user request a password reset" def __init__(self): self.fields = ( oldforms.EmailField(field_name="email", length=40, is_required=True, validator_list=[self.isValidUserEmail]), ) def isValidUserEmail(self, new_data, all_data): "Validates that a user exists with the given e-mail address" try: self.user_cache = User.objects.get(email__iexact=new_data) except User.DoesNotExist: raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?") def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'): "Calculates a new password randomly and sends it to the user" from django.core.mail import send_mail new_pass = User.objects.make_random_password() self.user_cache.set_password(new_pass) self.user_cache.save() if not domain_override: current_site = Site.objects.get_current() site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override t = loader.get_template(email_template_name) c = { 'new_password': new_pass, 'email': self.user_cache.email, 'domain': domain, 'site_name': site_name, 'user': self.user_cache, } send_mail('Password reset on %s' % site_name, t.render(Context(c)), None, [self.user_cache.email]) class PasswordChangeForm(oldforms.Manipulator): "A form that lets a user change his password." def __init__(self, user): self.user = user self.fields = ( oldforms.PasswordField(field_name="old_password", length=30, maxlength=30, is_required=True, validator_list=[self.isValidOldPassword]), oldforms.PasswordField(field_name="new_password1", length=30, maxlength=30, is_required=True, validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]), oldforms.PasswordField(field_name="new_password2", length=30, maxlength=30, is_required=True), ) def isValidOldPassword(self, new_data, all_data): "Validates that the old_password field is correct." if not self.user.check_password(new_data): raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.") def save(self, new_data): "Saves the new password." self.user.set_password(new_data['new_password1']) self.user.save() class AdminPasswordChangeForm(oldforms.Manipulator): "A form used to change the password of a user in the admin interface." def __init__(self, user): self.user = user self.fields = ( oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), ) def save(self, new_data): "Saves the new password." self.user.set_password(new_data['password1']) self.user.save()
Python
from django.core import validators from django.core.exceptions import ImproperlyConfigured from django.db import backend, connection, models from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext_lazy as _ import datetime def check_password(raw_password, enc_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ algo, salt, hsh = enc_password.split('$') if algo == 'md5': import md5 return hsh == md5.new(salt+raw_password).hexdigest() elif algo == 'sha1': import sha return hsh == sha.new(salt+raw_password).hexdigest() raise ValueError, "Got unknown password algorithm type in password." class SiteProfileNotAvailable(Exception): pass class Permission(models.Model): """The permissions system provides a way to assign permissions to specific users and groups of users. The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form and add an object. - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object. - The "delete" permission limits the ability to delete an object. Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date." Three basic permissions -- add, change and delete -- are automatically created for each Django model. """ name = models.CharField(_('name'), maxlength=50) content_type = models.ForeignKey(ContentType) codename = models.CharField(_('codename'), maxlength=100) class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = (('content_type', 'codename'),) ordering = ('content_type', 'codename') def __str__(self): return "%s | %s" % (self.content_type, self.name) class Group(models.Model): """Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission. Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages. """ name = models.CharField(_('name'), maxlength=80, unique=True) permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL) class Meta: verbose_name = _('group') verbose_name_plural = _('groups') ordering = ('name',) class Admin: search_fields = ('name',) def __str__(self): return self.name class UserManager(models.Manager): def create_user(self, username, email, password): "Creates and saves a User with the given username, e-mail and password." now = datetime.datetime.now() user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now) user.set_password(password) user.save() return user def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'): "Generates a random password with the given length and given allowed_chars" # Note that default value of allowed_chars does not have "I" or letters # that look like it -- just to avoid confusion. from random import choice return ''.join([choice(allowed_chars) for i in range(length)]) class User(models.Model): """Users within the Django authentication system are represented by this model. Username and password are required. Other fields are optional. """ username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric], help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores).")) first_name = models.CharField(_('first name'), maxlength=30, blank=True) last_name = models.CharField(_('last name'), maxlength=30, blank=True) email = models.EmailField(_('e-mail address'), blank=True) password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>.")) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site.")) is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user can log into the Django admin. Unselect this instead of deleting accounts.")) is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them.")) last_login = models.DateTimeField(_('last login'), default=models.LazyDate()) date_joined = models.DateTimeField(_('date joined'), default=models.LazyDate()) groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")) user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, filter_interface=models.HORIZONTAL) objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('username',) class Admin: fields = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), (_('Groups'), {'fields': ('groups',)}), ) list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff', 'is_superuser') search_fields = ('username', 'first_name', 'last_name', 'email') def __str__(self): return self.username def get_absolute_url(self): return "/users/%s/" % self.username def is_anonymous(self): "Always returns False. This is a way of comparing User objects to anonymous users." return False def is_authenticated(self): """Always return True. This is a way to tell if the user has been authenticated in templates. """ return True def get_full_name(self): "Returns the first_name plus the last_name, with a space in between." full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def set_password(self, raw_password): import sha, random algo = 'sha1' salt = sha.new(str(random.random())).hexdigest()[:5] hsh = sha.new(salt+raw_password).hexdigest() self.password = '%s$%s$%s' % (algo, salt, hsh) def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ # Backwards-compatibility check. Older passwords won't include the # algorithm or salt. if '$' not in self.password: import md5 is_correct = (self.password == md5.new(raw_password).hexdigest()) if is_correct: # Convert the password to the new, more secure format. self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password) def get_group_permissions(self): "Returns a list of permission strings that this user has through his/her groups." if not hasattr(self, '_group_perm_cache'): import sets cursor = connection.cursor() # The SQL below works out to the following, after DB quoting: # cursor.execute(""" # SELECT ct."app_label", p."codename" # FROM "auth_permission" p, "auth_group_permissions" gp, "auth_user_groups" ug, "django_content_type" ct # WHERE p."id" = gp."permission_id" # AND gp."group_id" = ug."group_id" # AND ct."id" = p."content_type_id" # AND ug."user_id" = %s, [self.id]) sql = """ SELECT ct.%s, p.%s FROM %s p, %s gp, %s ug, %s ct WHERE p.%s = gp.%s AND gp.%s = ug.%s AND ct.%s = p.%s AND ug.%s = %%s""" % ( backend.quote_name('app_label'), backend.quote_name('codename'), backend.quote_name('auth_permission'), backend.quote_name('auth_group_permissions'), backend.quote_name('auth_user_groups'), backend.quote_name('django_content_type'), backend.quote_name('id'), backend.quote_name('permission_id'), backend.quote_name('group_id'), backend.quote_name('group_id'), backend.quote_name('id'), backend.quote_name('content_type_id'), backend.quote_name('user_id'),) cursor.execute(sql, [self.id]) self._group_perm_cache = sets.Set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()]) return self._group_perm_cache def get_all_permissions(self): if not hasattr(self, '_perm_cache'): import sets self._perm_cache = sets.Set(["%s.%s" % (p.content_type.app_label, p.codename) for p in self.user_permissions.select_related()]) self._perm_cache.update(self.get_group_permissions()) return self._perm_cache def has_perm(self, perm): "Returns True if the user has the specified permission." if not self.is_active: return False if self.is_superuser: return True return perm in self.get_all_permissions() def has_perms(self, perm_list): "Returns True if the user has each of the specified permissions." for perm in perm_list: if not self.has_perm(perm): return False return True def has_module_perms(self, app_label): "Returns True if the user has any permissions in the given app label." if not self.is_active: return False if self.is_superuser: return True return bool(len([p for p in self.get_all_permissions() if p[:p.index('.')] == app_label])) def get_and_delete_messages(self): messages = [] for m in self.message_set.all(): messages.append(m.message) m.delete() return messages def email_user(self, subject, message, from_email=None): "Sends an e-mail to this User." from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email]) def get_profile(self): """ Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles. """ if not hasattr(self, '_profile_cache'): from django.conf import settings if not settings.AUTH_PROFILE_MODULE: raise SiteProfileNotAvailable try: app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.') model = models.get_model(app_label, model_name) self._profile_cache = model._default_manager.get(user__id__exact=self.id) except (ImportError, ImproperlyConfigured): raise SiteProfileNotAvailable return self._profile_cache class Message(models.Model): """The message system is a lightweight way to queue messages for given users. A message is associated with a User instance (so it is only applicable for registered users). There's no concept of expiration or timestamps. Messages are created by the Django admin after successful actions. For example, "The poll Foo was created successfully." is a message. """ user = models.ForeignKey(User) message = models.TextField(_('message')) def __str__(self): return self.message class AnonymousUser(object): id = None username = '' def __init__(self): pass def __str__(self): return 'AnonymousUser' def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return 1 # instances always return the same hash value def save(self): raise NotImplementedError def delete(self): raise NotImplementedError def set_password(self, raw_password): raise NotImplementedError def check_password(self, raw_password): raise NotImplementedError def _get_groups(self): raise NotImplementedError groups = property(_get_groups) def _get_user_permissions(self): raise NotImplementedError user_permissions = property(_get_user_permissions) def has_perm(self, perm): return False def has_module_perms(self, module): return False def get_and_delete_messages(self): return [] def is_anonymous(self): return True def is_authenticated(self): return False
Python
from django.contrib.auth import LOGIN_URL, REDIRECT_FIELD_NAME from django.http import HttpResponseRedirect from urllib import quote def user_passes_test(test_func, login_url=LOGIN_URL): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def _dec(view_func): def _checklogin(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))) _checklogin.__doc__ = view_func.__doc__ _checklogin.__dict__ = view_func.__dict__ return _checklogin return _dec login_required = user_passes_test(lambda u: u.is_authenticated()) login_required.__doc__ = ( """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ ) def permission_required(perm, login_url=LOGIN_URL): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. """ return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)
Python
""" Helper function for creating superusers in the authentication system. If run from the command line, this module lets you create a superuser interactively. """ from django.core import validators from django.contrib.auth.models import User import getpass import os import sys def createsuperuser(username=None, email=None, password=None): """ Helper function for creating a superuser from the command line. All arguments are optional and will be prompted-for if invalid or not given. """ try: import pwd except ImportError: default_username = '' else: # Determine the current system user's username, to use as a default. default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower() # Determine whether the default username is taken, so we don't display # it as an option. if default_username: try: User.objects.get(username=default_username) except User.DoesNotExist: pass else: default_username = '' try: while 1: if not username: input_msg = 'Username' if default_username: input_msg += ' (Leave blank to use %r)' % default_username username = raw_input(input_msg + ': ') if default_username and username == '': username = default_username if not username.isalnum(): sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n") username = None continue try: User.objects.get(username=username) except User.DoesNotExist: break else: sys.stderr.write("Error: That username is already taken.\n") username = None while 1: if not email: email = raw_input('E-mail address: ') try: validators.isValidEmail(email, None) except validators.ValidationError: sys.stderr.write("Error: That e-mail address is invalid.\n") email = None else: break while 1: if not password: password = getpass.getpass() password2 = getpass.getpass('Password (again): ') if password != password2: sys.stderr.write("Error: Your passwords didn't match.\n") password = None continue if password.strip() == '': sys.stderr.write("Error: Blank passwords aren't allowed.\n") password = None continue break except KeyboardInterrupt: sys.stderr.write("\nOperation cancelled.\n") sys.exit(1) u = User.objects.create_user(username, email, password) u.is_staff = True u.is_active = True u.is_superuser = True u.save() print "Superuser created successfully." if __name__ == "__main__": createsuperuser()
Python
""" Creates permissions for all installed apps that need permissions. """ from django.dispatch import dispatcher from django.db.models import get_models, signals from django.contrib.auth import models as auth_app def _get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in ('add', 'change', 'delete'): perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name))) return perms + list(opts.permissions) def create_permissions(app, created_models, verbosity): from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models: ctype = ContentType.objects.get_for_model(klass) for codename, name in _get_all_permissions(klass._meta): p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id, defaults={'name': name, 'content_type': ctype}) if created and verbosity >= 2: print "Adding permission '%s'" % p def create_superuser(app, created_models, verbosity, **kwargs): from django.contrib.auth.models import User from django.contrib.auth.create_superuser import createsuperuser as do_create if User in created_models and kwargs.get('interactive', True): msg = "\nYou just installed Django's auth system, which means you don't have " \ "any superusers defined.\nWould you like to create one now? (yes/no): " confirm = raw_input(msg) while 1: if confirm not in ('yes', 'no'): confirm = raw_input('Please enter either "yes" or "no": ') continue if confirm == 'yes': do_create() break dispatcher.connect(create_permissions, signal=signals.post_syncdb) dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
Python
class LazyUser(object): def __get__(self, request, obj_type=None): if not hasattr(request, '_cached_user'): from django.contrib.auth import get_user request._cached_user = get_user(request) return request._cached_user class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." request.__class__.user = LazyUser() return None
Python
from django.core.exceptions import ImproperlyConfigured SESSION_KEY = '_auth_user_id' BACKEND_SESSION_KEY = '_auth_user_backend' LOGIN_URL = '/accounts/login/' REDIRECT_FIELD_NAME = 'next' def load_backend(path): i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = __import__(module, {}, {}, [attr]) except ImportError, e: raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e) try: cls = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr) return cls() def get_backends(): from django.conf import settings backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backends.append(load_backend(backend_path)) return backends def authenticate(**credentials): """ If the given credentials are valid, return a User object. """ for backend in get_backends(): try: user = backend.authenticate(**credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue if user is None: continue # Annotate the user object with the path of the backend. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return user def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. """ if user is None: user = request.user # TODO: It would be nice to support different login methods, like signed cookies. request.session[SESSION_KEY] = user.id request.session[BACKEND_SESSION_KEY] = user.backend def logout(request): """ Remove the authenticated user's ID from the request. """ try: del request.session[SESSION_KEY] except KeyError: pass try: del request.session[BACKEND_SESSION_KEY] except KeyError: pass def get_user(request): from django.contrib.auth.models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) or AnonymousUser() except KeyError: user = AnonymousUser() return user
Python
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm from django import oldforms from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.sites.models import Site from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth import LOGIN_URL, REDIRECT_FIELD_NAME def login(request, template_name='registration/login.html'): "Displays the login form and handles the login action." manipulator = AuthenticationForm(request) redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '') if request.POST: errors = manipulator.get_validation_errors(request.POST) if not errors: # Light security check -- make sure redirect_to isn't garbage. if not redirect_to or '://' in redirect_to or ' ' in redirect_to: redirect_to = '/accounts/profile/' from django.contrib.auth import login login(request, manipulator.get_user()) request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: errors = {} request.session.set_test_cookie() return render_to_response(template_name, { 'form': oldforms.FormWrapper(manipulator, request.POST, errors), REDIRECT_FIELD_NAME: redirect_to, 'site_name': Site.objects.get_current().name, }, context_instance=RequestContext(request)) def logout(request, next_page=None, template_name='registration/logged_out.html'): "Logs out the user and displays 'You are logged out' message." from django.contrib.auth import logout logout(request) if next_page is None: return render_to_response(template_name, {'title': _('Logged out')}, context_instance=RequestContext(request)) else: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page or request.path) def logout_then_login(request, login_url=LOGIN_URL): "Logs out the user if he is logged in. Then redirects to the log-in page." return logout(request, login_url) def redirect_to_login(next, login_url=LOGIN_URL): "Redirects the user to the login page, passing the given 'next' page" return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, next)) def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html'): new_data, errors = {}, {} form = PasswordResetForm() if request.POST: new_data = request.POST.copy() errors = form.get_validation_errors(new_data) if not errors: if is_admin_site: form.save(domain_override=request.META['HTTP_HOST']) else: form.save(email_template_name=email_template_name) return HttpResponseRedirect('%sdone/' % request.path) return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, context_instance=RequestContext(request)) def password_reset_done(request, template_name='registration/password_reset_done.html'): return render_to_response(template_name, context_instance=RequestContext(request)) def password_change(request, template_name='registration/password_change_form.html'): new_data, errors = {}, {} form = PasswordChangeForm(request.user) if request.POST: new_data = request.POST.copy() errors = form.get_validation_errors(new_data) if not errors: form.save(new_data) return HttpResponseRedirect('%sdone/' % request.path) return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, context_instance=RequestContext(request)) password_change = login_required(password_change) def password_change_done(request, template_name='registration/password_change_done.html'): return render_to_response(template_name, context_instance=RequestContext(request))
Python
from django.contrib.auth.models import User class ModelBackend: """ Authenticate against django.contrib.auth.models.User """ # TODO: Model, login attribute name and password attribute name should be # configurable. def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
Python
from mod_python import apache import os def authenhandler(req, **kwargs): """ Authentication handler that checks against Django's auth database. """ # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_name = options.get('DjangoPermissionName', None) staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off")) settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from django.contrib.auth.models import User from django import db db.reset_queries() # check that the username is valid kwargs = {'username': req.user, 'is_active': True} if staff_only: kwargs['is_staff'] = True if superuser_only: kwargs['is_superuser'] = True try: try: user = User.objects.get(**kwargs) except User.DoesNotExist: return apache.HTTP_UNAUTHORIZED # check the password and any permission given if user.check_password(req.get_basic_auth_pw()): if permission_name: if user.has_perm(permission_name): return apache.OK else: return apache.HTTP_UNAUTHORIZED else: return apache.OK else: return apache.HTTP_UNAUTHORIZED finally: db.connection.close()
Python
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.template import Context, loader, Template, TemplateDoesNotExist from django.contrib.sites.models import Site from django.utils import feedgenerator from django.conf import settings def add_domain(domain, url): if not url.startswith('http://'): url = u'http://%s%s' % (domain, url) return url class FeedDoesNotExist(ObjectDoesNotExist): pass class Feed(object): item_pubdate = None item_enclosure_url = None feed_type = feedgenerator.DefaultFeed title_template = None description_template = None def __init__(self, slug, feed_url): self.slug = slug self.feed_url = feed_url self.title_template_name = self.title_template or ('feeds/%s_title.html' % slug) self.description_template_name = self.description_template or ('feeds/%s_description.html' % slug) def item_link(self, item): try: return item.get_absolute_url() except AttributeError: raise ImproperlyConfigured, "Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__ def __get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check func_code.co_argcount rather than try/excepting the # function and catching the TypeError, because something inside # the function may raise the TypeError. This technique is more # accurate. if hasattr(attr, 'func_code'): argcount = attr.func_code.co_argcount else: argcount = attr.__call__.func_code.co_argcount if argcount == 2: # one argument is 'self' return attr(obj) else: return attr() return attr def get_feed(self, url=None): """ Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters. """ if url: try: obj = self.get_object(url.split('/')) except (AttributeError, ObjectDoesNotExist): raise FeedDoesNotExist else: obj = None current_site = Site.objects.get_current() link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link) feed = self.feed_type( title = self.__get_dynamic_attr('title', obj), link = link, description = self.__get_dynamic_attr('description', obj), language = settings.LANGUAGE_CODE.decode(), feed_url = add_domain(current_site, self.__get_dynamic_attr('feed_url', obj)), author_name = self.__get_dynamic_attr('author_name', obj), author_link = self.__get_dynamic_attr('author_link', obj), author_email = self.__get_dynamic_attr('author_email', obj), categories = self.__get_dynamic_attr('categories', obj), feed_copyright = self.__get_dynamic_attr('feed_copyright', obj), ) try: title_tmp = loader.get_template(self.title_template_name) except TemplateDoesNotExist: title_tmp = Template('{{ obj }}') try: description_tmp = loader.get_template(self.description_template_name) except TemplateDoesNotExist: description_tmp = Template('{{ obj }}') for item in self.__get_dynamic_attr('items', obj): link = add_domain(current_site.domain, self.__get_dynamic_attr('item_link', item)) enc = None enc_url = self.__get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url = enc_url.decode('utf-8'), length = str(self.__get_dynamic_attr('item_enclosure_length', item)).decode('utf-8'), mime_type = self.__get_dynamic_attr('item_enclosure_mime_type', item).decode('utf-8'), ) author_name = self.__get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self.__get_dynamic_attr('item_author_email', item) author_link = self.__get_dynamic_attr('item_author_link', item) else: author_email = author_link = None feed.add_item( title = title_tmp.render(Context({'obj': item, 'site': current_site})).decode('utf-8'), link = link, description = description_tmp.render(Context({'obj': item, 'site': current_site})).decode('utf-8'), unique_id = link, enclosure = enc, pubdate = self.__get_dynamic_attr('item_pubdate', item), author_name = author_name, author_email = author_email, author_link = author_link, categories = self.__get_dynamic_attr('item_categories', item), item_copyright = self.__get_dynamic_attr('item_copyright', item), ) return feed
Python
from django.contrib.syndication import feeds from django.http import HttpResponse, Http404 def feed(request, url, feed_dict=None): if not feed_dict: raise Http404, "No feeds are registered." try: slug, param = url.split('/', 1) except ValueError: slug, param = url, '' try: f = feed_dict[slug] except KeyError: raise Http404, "Slug %r isn't registered." % slug try: feedgen = f(slug, request.path).get_feed(param) except feeds.FeedDoesNotExist: raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug response = HttpResponse(mimetype=feedgen.mime_type) feedgen.write(response, 'utf-8') return response
Python
""" Cross Site Request Forgery Middleware. This module provides a middleware that implements protection against request forgeries from other sites. """ from django.conf import settings from django.http import HttpResponseForbidden import md5 import re import itertools _ERROR_MSG = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><body><h1>403 Forbidden</h1><p>Cross Site Request Forgery detected. Request aborted.</p></body></html>' _POST_FORM_RE = \ re.compile(r'(<form\W[^>]*\bmethod=(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) _HTML_TYPES = ('text/html', 'application/xhtml+xml') def _make_token(session_id): return md5.new(settings.SECRET_KEY + session_id).hexdigest() class CsrfMiddleware(object): """Django middleware that adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value. In the list of middlewares, SessionMiddleware is required, and must come after this middleware. CsrfMiddleWare must come after compression middleware. If a session ID cookie is present, it is hashed with the SECRET_KEY setting to create an authentication token. This token is added to all outgoing POST forms and is expected on all incoming POST requests that have a session ID cookie. If you are setting cookies directly, instead of using Django's session framework, this middleware will not work. """ def process_request(self, request): if request.POST: try: session_id = request.COOKIES[settings.SESSION_COOKIE_NAME] except KeyError: # No session, no check required return None csrf_token = _make_token(session_id) # check incoming token try: request_csrf_token = request.POST['csrfmiddlewaretoken'] except KeyError: return HttpResponseForbidden(_ERROR_MSG) if request_csrf_token != csrf_token: return HttpResponseForbidden(_ERROR_MSG) return None def process_response(self, request, response): csrf_token = None try: cookie = response.cookies[settings.SESSION_COOKIE_NAME] csrf_token = _make_token(cookie.value) except KeyError: # No outgoing cookie to set session, but # a session might already exist. try: session_id = request.COOKIES[settings.SESSION_COOKIE_NAME] csrf_token = _make_token(session_id) except KeyError: # no incoming or outgoing cookie pass if csrf_token is not None and \ response['Content-Type'].split(';')[0] in _HTML_TYPES: # ensure we don't add the 'id' attribute twice (HTML validity) idattributes = itertools.chain(("id='csrfmiddlewaretoken'",), itertools.repeat('')) def add_csrf_field(match): """Returns the matched <form> tag plus the added <input> element""" return match.group() + "<div style='display:none;'>" + \ "<input type='hidden' " + idattributes.next() + \ " name='csrfmiddlewaretoken' value='" + csrf_token + \ "' /></div>" # Modify any POST forms response.content = _POST_FORM_RE.sub(add_csrf_field, response.content) return response
Python
""" Field classes """ from django.utils.translation import gettext from util import ErrorList, ValidationError, smart_unicode from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple import datetime import re import time __all__ = ( 'Field', 'CharField', 'IntegerField', 'DEFAULT_DATE_INPUT_FORMATS', 'DateField', 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField', 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'RegexField', 'EmailField', 'URLField', 'BooleanField', 'ChoiceField', 'NullBooleanField', 'MultipleChoiceField', 'ComboField', 'MultiValueField', 'SplitDateTimeField', ) # These values, if given to to_python(), will trigger the self.required check. EMPTY_VALUES = (None, '') try: set # Only available in Python 2.4+ except NameError: from sets import Set as set # Python 2.3 fallback class Field(object): widget = TextInput # Default widget to use when rendering this type of Field. hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden". # Tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None): # required -- Boolean that specifies whether the field is required. # True by default. # widget -- A Widget class, or instance of a Widget class, that should be # used for this Field when displaying it. Each Field has a default # Widget that it'll use if you don't specify this. In most cases, # the default widget is TextInput. # label -- A verbose name for this field, for use in displaying this field in # a form. By default, Django will use a "pretty" version of the form # field name, if the Field is part of a Form. # initial -- A value to use in this Field's initial display. This value is # *not* used as a fallback if data isn't given. # help_text -- An optional string to use as "help text" for this Field. if label is not None: label = smart_unicode(label) self.required, self.label, self.initial = required, label, initial self.help_text = smart_unicode(help_text or '') widget = widget or self.widget if isinstance(widget, type): widget = widget() # Hook into self.widget_attrs() for any Field-specific HTML attributes. extra_attrs = self.widget_attrs(widget) if extra_attrs: widget.attrs.update(extra_attrs) self.widget = widget # Increase the creation counter, and save our local copy. self.creation_counter = Field.creation_counter Field.creation_counter += 1 def clean(self, value): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ if self.required and value in EMPTY_VALUES: raise ValidationError(gettext(u'This field is required.')) return value def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), returns a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {} class CharField(Field): def __init__(self, max_length=None, min_length=None, *args, **kwargs): self.max_length, self.min_length = max_length, min_length super(CharField, self).__init__(*args, **kwargs) def clean(self, value): "Validates max_length and min_length. Returns a Unicode object." super(CharField, self).clean(value) if value in EMPTY_VALUES: return u'' value = smart_unicode(value) if self.max_length is not None and len(value) > self.max_length: raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length) if self.min_length is not None and len(value) < self.min_length: raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length) return value def widget_attrs(self, widget): if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)): return {'maxlength': str(self.max_length)} class IntegerField(Field): def __init__(self, max_value=None, min_value=None, *args, **kwargs): self.max_value, self.min_value = max_value, min_value super(IntegerField, self).__init__(*args, **kwargs) def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(value) except (ValueError, TypeError): raise ValidationError(gettext(u'Enter a whole number.')) if self.max_value is not None and value > self.max_value: raise ValidationError(gettext(u'Ensure this value is less than or equal to %s.') % self.max_value) if self.min_value is not None and value < self.min_value: raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value) return value DEFAULT_DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) class DateField(Field): def __init__(self, input_formats=None, *args, **kwargs): super(DateField, self).__init__(*args, **kwargs) self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS def clean(self, value): """ Validates that the input can be converted to a date. Returns a Python datetime.date object. """ super(DateField, self).clean(value) if value in EMPTY_VALUES: return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value for format in self.input_formats: try: return datetime.date(*time.strptime(value, format)[:3]) except ValueError: continue raise ValidationError(gettext(u'Enter a valid date.')) DEFAULT_TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) class TimeField(Field): def __init__(self, input_formats=None, *args, **kwargs): super(TimeField, self).__init__(*args, **kwargs) self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS def clean(self, value): """ Validates that the input can be converted to a time. Returns a Python datetime.time object. """ super(TimeField, self).clean(value) if value in EMPTY_VALUES: return None if isinstance(value, datetime.time): return value for format in self.input_formats: try: return datetime.time(*time.strptime(value, format)[3:6]) except ValueError: continue raise ValidationError(gettext(u'Enter a valid time.')) DEFAULT_DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) class DateTimeField(Field): def __init__(self, input_formats=None, *args, **kwargs): super(DateTimeField, self).__init__(*args, **kwargs) self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS def clean(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ super(DateTimeField, self).clean(value) if value in EMPTY_VALUES: return None if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): return datetime.datetime(value.year, value.month, value.day) for format in self.input_formats: try: return datetime.datetime(*time.strptime(value, format)[:6]) except ValueError: continue raise ValidationError(gettext(u'Enter a valid date/time.')) class RegexField(Field): def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs): """ regex can be either a string or a compiled regular expression object. error_message is an optional error message to use, if 'Enter a valid value' is too generic for you. """ super(RegexField, self).__init__(*args, **kwargs) if isinstance(regex, basestring): regex = re.compile(regex) self.regex = regex self.max_length, self.min_length = max_length, min_length self.error_message = error_message or gettext(u'Enter a valid value.') def clean(self, value): """ Validates that the input matches the regular expression. Returns a Unicode object. """ super(RegexField, self).clean(value) if value in EMPTY_VALUES: value = u'' value = smart_unicode(value) if value == u'': return value if self.max_length is not None and len(value) > self.max_length: raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length) if self.min_length is not None and len(value) < self.min_length: raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length) if not self.regex.search(value): raise ValidationError(self.error_message) return value email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE) # domain class EmailField(RegexField): def __init__(self, max_length=None, min_length=None, *args, **kwargs): RegexField.__init__(self, email_re, max_length, min_length, gettext(u'Enter a valid e-mail address.'), *args, **kwargs) url_re = re.compile( r'^https?://' # http:// or https:// r'(?:[A-Z0-9-]+\.)+[A-Z]{2,6}' # domain r'(?::\d+)?' # optional port r'(?:/?|/\S+)$', re.IGNORECASE) try: from django.conf import settings URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT except ImportError: # It's OK if Django settings aren't configured. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)' class URLField(RegexField): def __init__(self, max_length=None, min_length=None, verify_exists=False, validator_user_agent=URL_VALIDATOR_USER_AGENT, *args, **kwargs): super(URLField, self).__init__(url_re, max_length, min_length, gettext(u'Enter a valid URL.'), *args, **kwargs) self.verify_exists = verify_exists self.user_agent = validator_user_agent def clean(self, value): value = super(URLField, self).clean(value) if value == u'': return value if self.verify_exists: import urllib2 from django.conf import settings headers = { "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "Accept-Language": "en-us,en;q=0.5", "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "Connection": "close", "User-Agent": self.user_agent, } try: req = urllib2.Request(value, None, headers) u = urllib2.urlopen(req) except ValueError: raise ValidationError(gettext(u'Enter a valid URL.')) except: # urllib2.URLError, httplib.InvalidURL, etc. raise ValidationError(gettext(u'This URL appears to be a broken link.')) return value class BooleanField(Field): widget = CheckboxInput def clean(self, value): "Returns a Python boolean object." super(BooleanField, self).clean(value) return bool(value) class NullBooleanField(BooleanField): """ A field whose valid values are None, True and False. Invalid values are cleaned to None. """ widget = NullBooleanSelect def clean(self, value): return {True: True, False: False}.get(value, None) class ChoiceField(Field): def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None, help_text=None): super(ChoiceField, self).__init__(required, widget, label, initial, help_text) self.choices = choices def _get_choices(self): return self._choices def _set_choices(self, value): # Setting choices also sets the choices on the widget. # choices can be any iterable, but we call list() on it because # it will be consumed more than once. self._choices = self.widget.choices = list(value) choices = property(_get_choices, _set_choices) def clean(self, value): """ Validates that the input is in self.choices. """ value = super(ChoiceField, self).clean(value) if value in EMPTY_VALUES: value = u'' value = smart_unicode(value) if value == u'': return value valid_values = set([str(k) for k, v in self.choices]) if value not in valid_values: raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.')) return value class MultipleChoiceField(ChoiceField): hidden_widget = MultipleHiddenInput def __init__(self, choices=(), required=True, widget=SelectMultiple, label=None, initial=None, help_text=None): super(MultipleChoiceField, self).__init__(choices, required, widget, label, initial, help_text) def clean(self, value): """ Validates that the input is a list or tuple. """ if self.required and not value: raise ValidationError(gettext(u'This field is required.')) elif not self.required and not value: return [] if not isinstance(value, (list, tuple)): raise ValidationError(gettext(u'Enter a list of values.')) new_value = [] for val in value: val = smart_unicode(val) new_value.append(val) # Validate that each value in the value list is in self.choices. valid_values = set([smart_unicode(k) for k, v in self.choices]) for val in new_value: if val not in valid_values: raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val) return new_value class ComboField(Field): """ A Field whose clean() method calls multiple Field clean() methods. """ def __init__(self, fields=(), *args, **kwargs): super(ComboField, self).__init__(*args, **kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by ComboField, not by those # individual fields. for f in fields: f.required = False self.fields = fields def clean(self, value): """ Validates the given value against all of self.fields, which is a list of Field instances. """ super(ComboField, self).clean(value) for field in self.fields: value = field.clean(value) return value class MultiValueField(Field): """ A Field that is composed of multiple Fields. Its clean() method takes a "decompressed" list of values. Each value in this list is cleaned by the corresponding field -- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is "compressed" into a single value. Subclasses should implement compress(), which specifies how a list of valid values should be converted to a single value. Subclasses should not have to implement clean(). You'll probably want to use this with MultiWidget. """ def __init__(self, fields=(), *args, **kwargs): super(MultiValueField, self).__init__(*args, **kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by MultiValueField, not by those # individual fields. for f in fields: f.required = False self.fields = fields def clean(self, value): """ Validates every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(value[0]) and TimeField.clean(value[1]). """ clean_data = [] errors = ErrorList() if self.required and not value: raise ValidationError(gettext(u'This field is required.')) elif not self.required and not value: return self.compress([]) if not isinstance(value, (list, tuple)): raise ValidationError(gettext(u'Enter a list of values.')) for i, field in enumerate(self.fields): try: field_value = value[i] except KeyError: field_value = None if self.required and field_value in EMPTY_VALUES: raise ValidationError(gettext(u'This field is required.')) try: clean_data.append(field.clean(field_value)) except ValidationError, e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. errors.extend(e.messages) if errors: raise ValidationError(errors) return self.compress(clean_data) def compress(self, data_list): """ Returns a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by combining the date and time in data_list. """ raise NotImplementedError('Subclasses must implement this method.') class SplitDateTimeField(MultiValueField): def __init__(self, *args, **kwargs): fields = (DateField(), TimeField()) super(SplitDateTimeField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return datetime.datetime.combine(*data_list) return None
Python
""" Form classes """ from django.utils.datastructures import SortedDict, MultiValueDict from django.utils.html import escape from fields import Field from widgets import TextInput, Textarea, HiddenInput, MultipleHiddenInput from util import flatatt, StrAndUnicode, ErrorDict, ErrorList, ValidationError import copy __all__ = ('BaseForm', 'Form') NON_FIELD_ERRORS = '__all__' def pretty_name(name): "Converts 'first_name' to 'First name'" name = name[0].upper() + name[1:] return name.replace('_', ' ') class SortedDictFromList(SortedDict): "A dictionary that keeps its keys in the order in which they're inserted." # This is different than django.utils.datastructures.SortedDict, because # this takes a list/tuple as the argument to __init__(). def __init__(self, data=None): if data is None: data = [] self.keyOrder = [d[0] for d in data] dict.__init__(self, dict(data)) def copy(self): return SortedDictFromList([(k, copy.copy(v)) for k, v in self.items()]) class DeclarativeFieldsMetaclass(type): """ Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'base_fields' as well. """ def __new__(cls, name, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if isinstance(obj, Field)] fields.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) # If this class is subclassing another Form, add that Form's fields. # Note that we loop over the bases in *reverse*. This is necessary in # order to preserve the correct order of fields. for base in bases[::-1]: if hasattr(base, 'base_fields'): fields = base.base_fields.items() + fields attrs['base_fields'] = SortedDictFromList(fields) return type.__new__(cls, name, bases, attrs) class BaseForm(StrAndUnicode): # This is the main implementation of all the Form logic. Note that this # class is different than Form. See the comments by the Form class for more # information. Any improvements to the form API should be made to *this* # class, not to the Form class. def __init__(self, data=None, auto_id='id_%s', prefix=None, initial=None): self.is_bound = data is not None self.data = data or {} self.auto_id = auto_id self.prefix = prefix self.initial = initial or {} self.__errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = self.base_fields.copy() def __unicode__(self): return self.as_table() def __iter__(self): for name, field in self.fields.items(): yield BoundField(self, field, name) def __getitem__(self, name): "Returns a BoundField with the given name." try: field = self.fields[name] except KeyError: raise KeyError('Key %r not found in Form' % name) return BoundField(self, field, name) def _errors(self): "Returns an ErrorDict for self.data" if self.__errors is None: self.full_clean() return self.__errors errors = property(_errors) def is_valid(self): """ Returns True if the form has no errors. Otherwise, False. If errors are being ignored, returns False. """ return self.is_bound and not bool(self.errors) def add_prefix(self, field_name): """ Returns the field name with a prefix appended, if this Form has a prefix set. Subclasses may wish to override. """ return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()." top_errors = self.non_field_errors() # Errors that should be displayed above all fields. output, hidden_fields = [], [] for name, field in self.fields.items(): bf = BoundField(self, field, name) bf_errors = ErrorList([escape(error) for error in bf.errors]) # Escape and cache in local variable. if bf.is_hidden: if bf_errors: top_errors.extend(['(Hidden field %s) %s' % (name, e) for e in bf_errors]) hidden_fields.append(unicode(bf)) else: if errors_on_separate_row and bf_errors: output.append(error_row % bf_errors) label = bf.label and bf.label_tag(escape(bf.label + ':')) or '' if field.help_text: help_text = help_text_html % field.help_text else: help_text = u'' output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text}) if top_errors: output.insert(0, error_row % top_errors) if hidden_fields: # Insert any hidden fields in the last row. str_hidden = u''.join(hidden_fields) if output: last_row = output[-1] # Chop off the trailing row_ender (e.g. '</td></tr>') and insert the hidden fields. output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender else: # If there aren't any rows in the output, just append the hidden fields. output.append(str_hidden) return u'\n'.join(output) def as_table(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." return self._html_output(u'<tr><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False) def as_ul(self): "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>." return self._html_output(u'<li>%(errors)s%(label)s %(field)s%(help_text)s</li>', u'<li>%s</li>', '</li>', u' %s', False) def as_p(self): "Returns this form rendered as HTML <p>s." return self._html_output(u'<p>%(label)s %(field)s%(help_text)s</p>', u'<p>%s</p>', '</p>', u' %s', True) def non_field_errors(self): """ Returns an ErrorList of errors that aren't associated with a particular field -- i.e., from Form.clean(). Returns an empty ErrorList if there are none. """ return self.errors.get(NON_FIELD_ERRORS, ErrorList()) def full_clean(self): """ Cleans all of self.data and populates self.__errors and self.clean_data. """ errors = ErrorDict() if not self.is_bound: # Stop further processing. self.__errors = errors return self.clean_data = {} for name, field in self.fields.items(): # value_from_datadict() gets the data from the dictionary. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. value = field.widget.value_from_datadict(self.data, self.add_prefix(name)) try: value = field.clean(value) self.clean_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.clean_data[name] = value except ValidationError, e: errors[name] = e.messages try: self.clean_data = self.clean() except ValidationError, e: errors[NON_FIELD_ERRORS] = e.messages if errors: delattr(self, 'clean_data') self.__errors = errors def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'. """ return self.clean_data class Form(BaseForm): "A collection of Fields, plus their associated data." # This is a separate class from BaseForm in order to abstract the way # self.fields is specified. This class (Form) is the one that does the # fancy metaclass stuff purely for the semantic sugar -- it allows one # to define a form using declarative syntax. # BaseForm itself has no way of designating self.fields. __metaclass__ = DeclarativeFieldsMetaclass class BoundField(StrAndUnicode): "A Field plus data" def __init__(self, form, field, name): self.form = form self.field = field self.name = name self.html_name = form.add_prefix(name) if self.field.label is None: self.label = pretty_name(name) else: self.label = self.field.label self.help_text = field.help_text or '' def __unicode__(self): "Renders this field as an HTML widget." # Use the 'widget' attribute on the field to determine which type # of HTML widget to use. value = self.as_widget(self.field.widget) if not isinstance(value, basestring): # Some Widget render() methods -- notably RadioSelect -- return a # "special" object rather than a string. Call the __str__() on that # object to get its rendered value. value = value.__str__() return value def _errors(self): """ Returns an ErrorList for this field. Returns an empty ErrorList if there are none. """ return self.form.errors.get(self.name, ErrorList()) errors = property(_errors) def as_widget(self, widget, attrs=None): attrs = attrs or {} auto_id = self.auto_id if auto_id and not attrs.has_key('id') and not widget.attrs.has_key('id'): attrs['id'] = auto_id if not self.form.is_bound: data = self.form.initial.get(self.name, self.field.initial) else: data = self.data return widget.render(self.html_name, data, attrs=attrs) def as_text(self, attrs=None): """ Returns a string of HTML for representing this as an <input type="text">. """ return self.as_widget(TextInput(), attrs) def as_textarea(self, attrs=None): "Returns a string of HTML for representing this as a <textarea>." return self.as_widget(Textarea(), attrs) def as_hidden(self, attrs=None): """ Returns a string of HTML for representing this as an <input type="hidden">. """ return self.as_widget(self.field.hidden_widget(), attrs) def _data(self): """ Returns the data for this BoundField, or None if it wasn't given. """ return self.field.widget.value_from_datadict(self.form.data, self.html_name) data = property(_data) def label_tag(self, contents=None, attrs=None): """ Wraps the given contents in a <label>, if the field has an ID attribute. Does not HTML-escape the contents. If contents aren't given, uses the field's HTML-escaped label. If attrs are given, they're used as HTML attributes on the <label> tag. """ contents = contents or escape(self.label) widget = self.field.widget id_ = widget.attrs.get('id') or self.auto_id if id_: attrs = attrs and flatatt(attrs) or '' contents = '<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, contents) return contents def _is_hidden(self): "Returns True if this BoundField's widget is hidden." return self.field.widget.is_hidden is_hidden = property(_is_hidden) def _auto_id(self): """ Calculates and returns the ID attribute for this BoundField, if the associated Form has specified auto_id. Returns an empty string otherwise. """ auto_id = self.form.auto_id if auto_id and '%s' in str(auto_id): return str(auto_id) % self.html_name elif auto_id: return self.html_name return '' auto_id = property(_auto_id)
Python
""" Helper functions for creating Form classes from Django models and database field objects. """ from django.utils.translation import gettext from util import ValidationError from forms import BaseForm, DeclarativeFieldsMetaclass, SortedDictFromList from fields import Field, ChoiceField from widgets import Select, SelectMultiple, MultipleHiddenInput __all__ = ('save_instance', 'form_for_model', 'form_for_instance', 'form_for_fields', 'ModelChoiceField', 'ModelMultipleChoiceField') def model_save(self, commit=True): """ Creates and returns model instance according to self.clean_data. This method is created for any form_for_model Form. """ if self.errors: raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name) return save_instance(self, self._model(), commit) def save_instance(form, instance, commit=True): """ Saves bound Form ``form``'s clean_data into model instance ``instance``. Assumes ``form`` has a field for every non-AutoField database field in ``instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``instance``. """ from django.db import models opts = instance.__class__._meta if form.errors: raise ValueError("The %s could not be changed because the data didn't validate." % opts.object_name) clean_data = form.clean_data for f in opts.fields: if not f.editable or isinstance(f, models.AutoField): continue setattr(instance, f.name, clean_data[f.name]) if commit: instance.save() for f in opts.many_to_many: setattr(instance, f.attname, clean_data[f.name]) # GOTCHA: If many-to-many data is given and commit=False, the many-to-many # data will be lost. This happens because a many-to-many options cannot be # set on an object until after it's saved. Maybe we should raise an # exception in that case. return instance def make_instance_save(instance): "Returns the save() method for a form_for_instance Form." def save(self, commit=True): return save_instance(self, instance, commit) return save def form_for_model(model, form=BaseForm, formfield_callback=lambda f: f.formfield()): """ Returns a Form class for the given Django model class. Provide ``form`` if you want to use a custom BaseForm subclass. Provide ``formfield_callback`` if you want to define different logic for determining the formfield for a given database field. It's a callable that takes a database Field instance and returns a form Field instance. """ opts = model._meta field_list = [] for f in opts.fields + opts.many_to_many: if not f.editable: continue formfield = formfield_callback(f) if formfield: field_list.append((f.name, formfield)) fields = SortedDictFromList(field_list) return type(opts.object_name + 'Form', (form,), {'base_fields': fields, '_model': model, 'save': model_save}) def form_for_instance(instance, form=BaseForm, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): """ Returns a Form class for the given Django model instance. Provide ``form`` if you want to use a custom BaseForm subclass. Provide ``formfield_callback`` if you want to define different logic for determining the formfield for a given database field. It's a callable that takes a database Field instance, plus **kwargs, and returns a form Field instance with the given kwargs (i.e. 'initial'). """ model = instance.__class__ opts = model._meta field_list = [] for f in opts.fields + opts.many_to_many: if not f.editable: continue current_value = f.value_from_object(instance) formfield = formfield_callback(f, initial=current_value) if formfield: field_list.append((f.name, formfield)) fields = SortedDictFromList(field_list) return type(opts.object_name + 'InstanceForm', (form,), {'base_fields': fields, '_model': model, 'save': make_instance_save(instance)}) def form_for_fields(field_list): "Returns a Form class for the given list of Django database field instances." fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list if f.editable]) return type('FormForFields', (BaseForm,), {'base_fields': fields}) class QuerySetIterator(object): def __init__(self, queryset, empty_label, cache_choices): self.queryset, self.empty_label, self.cache_choices = queryset, empty_label, cache_choices def __iter__(self): if self.empty_label is not None: yield (u"", self.empty_label) for obj in self.queryset: yield (obj._get_pk_val(), str(obj)) # Clear the QuerySet cache if required. if not self.cache_choices: self.queryset._result_cache = None class ModelChoiceField(ChoiceField): "A ChoiceField whose choices are a model QuerySet." # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. def __init__(self, queryset, empty_label=u"---------", cache_choices=False, required=True, widget=Select, label=None, initial=None, help_text=None): self.queryset = queryset self.empty_label = empty_label self.cache_choices = cache_choices # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__(self, required, widget, label, initial, help_text) self.widget.choices = self.choices def _get_choices(self): # If self._choices is set, then somebody must have manually set # the property self.choices. In this case, just return self._choices. if hasattr(self, '_choices'): return self._choices # Otherwise, execute the QuerySet in self.queryset to determine the # choices dynamically. Return a fresh QuerySetIterator that has not # been consumed. Note that we're instantiating a new QuerySetIterator # *each* time _get_choices() is called (and, thus, each time # self.choices is accessed) so that we can ensure the QuerySet has not # been consumed. return QuerySetIterator(self.queryset, self.empty_label, self.cache_choices) def _set_choices(self, value): # This method is copied from ChoiceField._set_choices(). It's necessary # because property() doesn't allow a subclass to overwrite only # _get_choices without implementing _set_choices. self._choices = self.widget.choices = list(value) choices = property(_get_choices, _set_choices) def clean(self, value): Field.clean(self, value) if value in ('', None): return None try: value = self.queryset.model._default_manager.get(pk=value) except self.queryset.model.DoesNotExist: raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.')) return value class ModelMultipleChoiceField(ModelChoiceField): "A MultipleChoiceField whose choices are a model QuerySet." hidden_widget = MultipleHiddenInput def __init__(self, queryset, cache_choices=False, required=True, widget=SelectMultiple, label=None, initial=None, help_text=None): super(ModelMultipleChoiceField, self).__init__(queryset, None, cache_choices, required, widget, label, initial, help_text) def clean(self, value): if self.required and not value: raise ValidationError(gettext(u'This field is required.')) elif not self.required and not value: return [] if not isinstance(value, (list, tuple)): raise ValidationError(gettext(u'Enter a list of values.')) final_values = [] for val in value: try: obj = self.queryset.model._default_manager.get(pk=val) except self.queryset.model.DoesNotExist: raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val) else: final_values.append(obj) return final_values
Python
""" HTML Widget classes """ __all__ = ( 'Widget', 'TextInput', 'PasswordInput', 'HiddenInput', 'MultipleHiddenInput', 'FileInput', 'Textarea', 'CheckboxInput', 'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect', 'CheckboxSelectMultiple', 'MultiWidget', 'SplitDateTimeWidget', ) from util import flatatt, StrAndUnicode, smart_unicode from django.utils.datastructures import MultiValueDict from django.utils.html import escape from django.utils.translation import gettext from itertools import chain try: set # Only available in Python 2.4+ except NameError: from sets import Set as set # Python 2.3 fallback class Widget(object): is_hidden = False # Determines whether this corresponds to an <input type="hidden">. def __init__(self, attrs=None): self.attrs = attrs or {} def render(self, name, value, attrs=None): """ Returns this Widget rendered as HTML, as a Unicode string. The 'value' given is not guaranteed to be valid input, so subclass implementations should program defensively. """ raise NotImplementedError def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." attrs = dict(self.attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs def value_from_datadict(self, data, name): """ Given a dictionary of data and this widget's name, returns the value of this widget. Returns None if it's not provided. """ return data.get(name, None) def id_for_label(self, id_): """ Returns the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Returns None if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ id_for_label = classmethod(id_for_label) class Input(Widget): """ Base class for all <input> widgets (except type='checkbox' and type='radio', which are special). """ input_type = None # Subclasses must define this. def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': final_attrs['value'] = smart_unicode(value) # Only add the 'value' attribute if a value is non-empty. return u'<input%s />' % flatatt(final_attrs) class TextInput(Input): input_type = 'text' class PasswordInput(Input): input_type = 'password' def __init__(self, attrs=None, render_value=True): self.attrs = attrs or {} self.render_value = render_value def render(self, name, value, attrs=None): if not self.render_value: value=None return super(PasswordInput, self).render(name, value, attrs) class HiddenInput(Input): input_type = 'hidden' is_hidden = True class MultipleHiddenInput(HiddenInput): """ A widget that handles <input type="hidden"> for fields that have a list of values. """ def __init__(self, attrs=None, choices=()): # choices can be any iterable self.attrs = attrs or {} self.choices = choices def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) return u'\n'.join([(u'<input%s />' % flatatt(dict(value=smart_unicode(v), **final_attrs))) for v in value]) def value_from_datadict(self, data, name): if isinstance(data, MultiValueDict): return data.getlist(name) return data.get(name, None) class FileInput(Input): input_type = 'file' class Textarea(Widget): def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) return u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value)) class CheckboxInput(Widget): def __init__(self, attrs=None, check_test=bool): # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.attrs = attrs or {} self.check_test = check_test def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, type='checkbox', name=name) try: result = self.check_test(value) except: # Silently catch exceptions result = False if result: final_attrs['checked'] = 'checked' if value not in ('', True, False, None): final_attrs['value'] = smart_unicode(value) # Only add the 'value' attribute if a value is non-empty. return u'<input%s />' % flatatt(final_attrs) class Select(Widget): def __init__(self, attrs=None, choices=()): self.attrs = attrs or {} # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def render(self, name, value, attrs=None, choices=()): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) output = [u'<select%s>' % flatatt(final_attrs)] str_value = smart_unicode(value) # Normalize to string. for option_value, option_label in chain(self.choices, choices): option_value = smart_unicode(option_value) selected_html = (option_value == str_value) and u' selected="selected"' or '' output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(smart_unicode(option_label)))) output.append(u'</select>') return u'\n'.join(output) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ((u'1', gettext('Unknown')), (u'2', gettext('Yes')), (u'3', gettext('No'))) super(NullBooleanSelect, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): try: value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value] except KeyError: value = u'1' return super(NullBooleanSelect, self).render(name, value, attrs, choices) def value_from_datadict(self, data, name): value = data.get(name, None) return {u'2': True, u'3': False, True: True, False: False}.get(value, None) class SelectMultiple(Widget): def __init__(self, attrs=None, choices=()): # choices can be any iterable self.attrs = attrs or {} self.choices = choices def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] str_values = set([smart_unicode(v) for v in value]) # Normalize to strings. for option_value, option_label in chain(self.choices, choices): option_value = smart_unicode(option_value) selected_html = (option_value in str_values) and ' selected="selected"' or '' output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(smart_unicode(option_label)))) output.append(u'</select>') return u'\n'.join(output) def value_from_datadict(self, data, name): if isinstance(data, MultiValueDict): return data.getlist(name) return data.get(name, None) class RadioInput(StrAndUnicode): "An object used by RadioFieldRenderer that represents a single <input type='radio'>." def __init__(self, name, value, attrs, choice, index): self.name, self.value = name, value self.attrs = attrs self.choice_value = smart_unicode(choice[0]) self.choice_label = smart_unicode(choice[1]) self.index = index def __unicode__(self): return u'<label>%s %s</label>' % (self.tag(), self.choice_label) def is_checked(self): return self.value == self.choice_value def tag(self): if self.attrs.has_key('id'): self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index) final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' return u'<input%s />' % flatatt(final_attrs) class RadioFieldRenderer(StrAndUnicode): "An object used by RadioSelect to enable customization of radio widgets." def __init__(self, name, value, attrs, choices): self.name, self.value, self.attrs = name, value, attrs self.choices = choices def __iter__(self): for i, choice in enumerate(self.choices): yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i) def __getitem__(self, idx): choice = self.choices[idx] # Let the IndexError propogate return RadioInput(self.name, self.value, self.attrs.copy(), choice, idx) def __unicode__(self): "Outputs a <ul> for this set of radio fields." return u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % w for w in self]) class RadioSelect(Select): def render(self, name, value, attrs=None, choices=()): "Returns a RadioFieldRenderer instance rather than a Unicode string." if value is None: value = '' str_value = smart_unicode(value) # Normalize to string. attrs = attrs or {} return RadioFieldRenderer(name, str_value, attrs, list(chain(self.choices, choices))) def id_for_label(self, id_): # RadioSelect is represented by multiple <input type="radio"> fields, # each of which has a distinct ID. The IDs are made distinct by a "_X" # suffix, where X is the zero-based index of the radio field. Thus, # the label for a RadioSelect should reference the first one ('_0'). if id_: id_ += '_0' return id_ id_for_label = classmethod(id_for_label) class CheckboxSelectMultiple(SelectMultiple): def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and attrs.has_key('id') final_attrs = self.build_attrs(attrs, name=name) output = [u'<ul>'] str_values = set([smart_unicode(v) for v in value]) # Normalize to strings. for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = smart_unicode(option_value) rendered_cb = cb.render(name, option_value) output.append(u'<li><label>%s %s</label></li>' % (rendered_cb, escape(smart_unicode(option_label)))) output.append(u'</ul>') return u'\n'.join(output) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += '_0' return id_ id_for_label = classmethod(id_for_label) class MultiWidget(Widget): """ A widget that is composed of multiple widgets. Its render() method takes a "decompressed" list of values, not a single value. Each value in this list is rendered in the corresponding widget -- the first value is rendered in the first widget, the second value is rendered in the second widget, etc. Subclasses should implement decompress(), which specifies how a single value should be converted to a list of values. Subclasses should not have to implement clean(). Subclasses may implement format_output(), which takes the list of rendered widgets and returns HTML that formats them any way you'd like. You'll probably want to use this with MultiValueField. """ def __init__(self, widgets, attrs=None): self.widgets = [isinstance(w, type) and w() or w for w in widgets] super(MultiWidget, self).__init__(attrs) def render(self, name, value, attrs=None): # value is a list of values, each corresponding to a widget # in self.widgets. if not isinstance(value, list): value = self.decompress(value) output = [] for i, widget in enumerate(self.widgets): try: widget_value = value[i] except KeyError: widget_value = None output.append(widget.render(name + '_%s' % i, widget_value, attrs)) return self.format_output(output) def value_from_datadict(self, data, name): return [data.get(name + '_%s' % i) for i in range(len(self.widgets))] def format_output(self, rendered_widgets): return u''.join(rendered_widgets) def decompress(self, value): """ Returns a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError('Subclasses must implement this method.') class SplitDateTimeWidget(MultiWidget): """ A Widget that splits datetime input into two <input type="text"> boxes. """ def __init__(self, attrs=None): widgets = (TextInput(attrs=attrs), TextInput(attrs=attrs)) super(SplitDateTimeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return [value.date(), value.time()] return [None, None]
Python
""" Extra HTML Widget classes """ from django.newforms.widgets import Widget, Select from django.utils.dates import MONTHS import datetime __all__ = ('SelectDateWidget',) class SelectDateWidget(Widget): """ A Widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ month_field = '%s_month' day_field = '%s_day' year_field = '%s_year' def __init__(self, attrs=None, years=None): # years is an optional list/tuple of years to use in the "year" select box. self.attrs = attrs or {} if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year+10) def render(self, name, value, attrs=None): try: value = datetime.date(*map(int, value.split('-'))) year_val, month_val, day_val = value.year, value.month, value.day except (AttributeError, TypeError, ValueError): year_val = month_val = day_val = None output = [] month_choices = MONTHS.items() month_choices.sort() select_html = Select(choices=month_choices).render(self.month_field % name, month_val) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] select_html = Select(choices=day_choices).render(self.day_field % name, day_val) output.append(select_html) year_choices = [(i, i) for i in self.years] select_html = Select(choices=year_choices).render(self.year_field % name, year_val) output.append(select_html) return u'\n'.join(output) def value_from_datadict(self, data, name): y, m, d = data.get(self.year_field % name), data.get(self.month_field % name), data.get(self.day_field % name) if y and m and d: return '%s-%s-%s' % (y, m, d) return None
Python
from widgets import *
Python
from django.conf import settings from django.utils.html import escape # Converts a dictionary to a single string with key="value", XML-style with # a leading space. Assumes keys do not need to be XML-escaped. flatatt = lambda attrs: u''.join([u' %s="%s"' % (k, escape(v)) for k, v in attrs.items()]) def smart_unicode(s): if not isinstance(s, basestring): if hasattr(s, '__unicode__'): s = unicode(s) else: s = unicode(str(s), settings.DEFAULT_CHARSET) elif not isinstance(s, unicode): s = unicode(s, settings.DEFAULT_CHARSET) return s class StrAndUnicode(object): """ A class whose __str__ returns its __unicode__ as a bytestring according to settings.DEFAULT_CHARSET. Useful as a mix-in. """ def __str__(self): return self.__unicode__().encode(settings.DEFAULT_CHARSET) class ErrorDict(dict): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ def __str__(self): return self.as_ul() def as_ul(self): if not self: return u'' return u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s%s</li>' % (k, v) for k, v in self.items()]) def as_text(self): return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % i for i in v])) for k, v in self.items()]) class ErrorList(list): """ A collection of errors that knows how to display itself in various formats. """ def __str__(self): return self.as_ul() def as_ul(self): if not self: return u'' return u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s</li>' % e for e in self]) def as_text(self): if not self: return u'' return u'\n'.join([u'* %s' % e for e in self]) class ValidationError(Exception): def __init__(self, message): "ValidationError can be passed a string or a list." if isinstance(message, list): self.messages = ErrorList([smart_unicode(msg) for msg in message]) else: assert isinstance(message, basestring), ("%s should be a basestring" % repr(message)) message = smart_unicode(message) self.messages = ErrorList([message]) def __str__(self): # This is needed because, without a __str__(), printing an exception # instance would result in this: # AttributeError: ValidationError instance has no attribute 'args' # See http://www.python.org/doc/current/tut/node10.html#handling return repr(self.messages)
Python
""" Django validation and HTML form handling. TODO: Default value for field Field labels Nestable Forms FatalValidationError -- short-circuits all other validators on a form ValidationWarning "This form field requires foo.js" and form.js_includes() """ from util import ValidationError from widgets import * from fields import * from forms import * from models import *
Python
"Default tags used by the template system, available to all templates." from django.template import Node, NodeList, Template, Context, resolve_variable from django.template import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END from django.template import get_library, Library, InvalidTemplateLibrary from django.conf import settings import sys register = Library() class CommentNode(Node): def render(self, context): return '' class CycleNode(Node): def __init__(self, cyclevars, variable_name=None): self.cyclevars = cyclevars self.cyclevars_len = len(cyclevars) self.counter = -1 self.variable_name = variable_name def render(self, context): self.counter += 1 value = self.cyclevars[self.counter % self.cyclevars_len] if self.variable_name: context[self.variable_name] = value return value class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output) class FilterNode(Node): def __init__(self, filter_expr, nodelist): self.filter_expr, self.nodelist = filter_expr, nodelist def render(self, context): output = self.nodelist.render(context) # apply filters return self.filter_expr.resolve(Context({'var': output})) class FirstOfNode(Node): def __init__(self, vars): self.vars = vars def render(self, context): for var in self.vars: try: value = resolve_variable(var, context) except VariableDoesNotExist: continue if value: return str(value) return '' class ForNode(Node): def __init__(self, loopvar, sequence, reversed, nodelist_loop): self.loopvar, self.sequence = loopvar, sequence self.reversed = reversed self.nodelist_loop = nodelist_loop def __repr__(self): if self.reversed: reversed = ' reversed' else: reversed = '' return "<For Node: for %s in %s, tail_len: %d%s>" % \ (self.loopvar, self.sequence, len(self.nodelist_loop), reversed) def __iter__(self): for node in self.nodelist_loop: yield node def get_nodes_by_type(self, nodetype): nodes = [] if isinstance(self, nodetype): nodes.append(self) nodes.extend(self.nodelist_loop.get_nodes_by_type(nodetype)) return nodes def render(self, context): nodelist = NodeList() if context.has_key('forloop'): parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if self.reversed: # From http://www.python.org/doc/current/tut/node11.html def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] values = reverse(values) for i, item in enumerate(values): context['forloop'] = { # shortcuts for current loop iteration number 'counter0': i, 'counter': i+1, # reverse counter iteration numbers 'revcounter': len_values - i, 'revcounter0': len_values - i - 1, # boolean values designating first and last times through loop 'first': (i == 0), 'last': (i == len_values - 1), 'parentloop': parentloop, } context[self.loopvar] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() return nodelist.render(context) class IfChangedNode(Node): def __init__(self, nodelist, *varlist): self.nodelist = nodelist self._last_seen = None self._varlist = varlist def render(self, context): if context.has_key('forloop') and context['forloop']['first']: self._last_seen = None try: if self._varlist: # Consider multiple parameters. # This automatically behaves like a OR evaluation of the multiple variables. compare_to = [resolve_variable(var, context) for var in self._varlist] else: compare_to = self.nodelist.render(context) except VariableDoesNotExist: compare_to = None if compare_to != self._last_seen: firstloop = (self._last_seen == None) self._last_seen = compare_to context.push() context['ifchanged'] = {'firstloop': firstloop} content = self.nodelist.render(context) context.pop() return content else: return '' class IfEqualNode(Node): def __init__(self, var1, var2, nodelist_true, nodelist_false, negate): self.var1, self.var2 = var1, var2 self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.negate = negate def __repr__(self): return "<IfEqualNode>" def render(self, context): try: val1 = resolve_variable(self.var1, context) except VariableDoesNotExist: val1 = None try: val2 = resolve_variable(self.var2, context) except VariableDoesNotExist: val2 = None if (self.negate and val1 != val2) or (not self.negate and val1 == val2): return self.nodelist_true.render(context) return self.nodelist_false.render(context) class IfNode(Node): def __init__(self, bool_exprs, nodelist_true, nodelist_false, link_type): self.bool_exprs = bool_exprs self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.link_type = link_type def __repr__(self): return "<If node>" def __iter__(self): for node in self.nodelist_true: yield node for node in self.nodelist_false: yield node def get_nodes_by_type(self, nodetype): nodes = [] if isinstance(self, nodetype): nodes.append(self) nodes.extend(self.nodelist_true.get_nodes_by_type(nodetype)) nodes.extend(self.nodelist_false.get_nodes_by_type(nodetype)) return nodes def render(self, context): if self.link_type == IfNode.LinkTypes.or_: for ifnot, bool_expr in self.bool_exprs: try: value = bool_expr.resolve(context, True) except VariableDoesNotExist: value = None if (value and not ifnot) or (ifnot and not value): return self.nodelist_true.render(context) return self.nodelist_false.render(context) else: for ifnot, bool_expr in self.bool_exprs: try: value = bool_expr.resolve(context, True) except VariableDoesNotExist: value = None if not ((value and not ifnot) or (ifnot and not value)): return self.nodelist_false.render(context) return self.nodelist_true.render(context) class LinkTypes: and_ = 0, or_ = 1 class RegroupNode(Node): def __init__(self, target, expression, var_name): self.target, self.expression = target, expression self.var_name = var_name def render(self, context): obj_list = self.target.resolve(context, True) if obj_list == None: # target_var wasn't found in context; fail silently context[self.var_name] = [] return '' output = [] # list of dictionaries in the format {'grouper': 'key', 'list': [list of contents]} for obj in obj_list: grouper = self.expression.resolve(Context({'var': obj}), True) # TODO: Is this a sensible way to determine equality? if output and repr(output[-1]['grouper']) == repr(grouper): output[-1]['list'].append(obj) else: output.append({'grouper': grouper, 'list': [obj]}) context[self.var_name] = output return '' def include_is_allowed(filepath): for root in settings.ALLOWED_INCLUDE_ROOTS: if filepath.startswith(root): return True return False class SsiNode(Node): def __init__(self, filepath, parsed): self.filepath, self.parsed = filepath, parsed def render(self, context): if not include_is_allowed(self.filepath): if settings.DEBUG: return "[Didn't have permission to include file]" else: return '' # Fail silently for invalid includes. try: fp = open(self.filepath, 'r') output = fp.read() fp.close() except IOError: output = '' if self.parsed: try: t = Template(output, name=self.filepath) return t.render(context) except TemplateSyntaxError, e: if settings.DEBUG: return "[Included template had syntax error: %s]" % e else: return '' # Fail silently for invalid included templates. return output class LoadNode(Node): def render(self, context): return '' class NowNode(Node): def __init__(self, format_string): self.format_string = format_string def render(self, context): from datetime import datetime from django.utils.dateformat import DateFormat df = DateFormat(datetime.now()) return df.format(self.format_string) class SpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): from django.utils.html import strip_spaces_between_tags return strip_spaces_between_tags(self.nodelist.render(context).strip()) class TemplateTagNode(Node): mapping = {'openblock': BLOCK_TAG_START, 'closeblock': BLOCK_TAG_END, 'openvariable': VARIABLE_TAG_START, 'closevariable': VARIABLE_TAG_END, 'openbrace': SINGLE_BRACE_START, 'closebrace': SINGLE_BRACE_END, 'opencomment': COMMENT_TAG_START, 'closecomment': COMMENT_TAG_END, } def __init__(self, tagtype): self.tagtype = tagtype def render(self, context): return self.mapping.get(self.tagtype, '') class URLNode(Node): def __init__(self, view_name, args, kwargs): self.view_name = view_name self.args = args self.kwargs = kwargs def render(self, context): from django.core.urlresolvers import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] kwargs = dict([(k, v.resolve(context)) for k, v in self.kwargs.items()]) try: return reverse(self.view_name, args=args, kwargs=kwargs) except NoReverseMatch: try: project_name = settings.SETTINGS_MODULE.split('.')[0] return reverse(project_name + '.' + self.view_name, args=args, kwargs=kwargs) except NoReverseMatch: return '' class WidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width def render(self, context): try: value = self.val_expr.resolve(context) maxvalue = self.max_expr.resolve(context) except VariableDoesNotExist: return '' try: value = float(value) maxvalue = float(maxvalue) ratio = (value / maxvalue) * int(self.max_width) except (ValueError, ZeroDivisionError): return '' return str(int(round(ratio))) #@register.tag def comment(parser, token): """ Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` """ parser.skip_past('endcomment') return CommentNode() comment = register.tag(comment) #@register.tag def cycle(parser, token): """ Cycle among the given strings each time this tag is encountered Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle row1,row2 %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each sucessive time through:: <tr class="{% cycle row1,row2,row3 as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, seperated by commas. Make sure not to put spaces between the values -- only commas. """ # Note: This returns the exact same node on each {% cycle name %} call; that # is, the node object returned from {% cycle a,b,c as name %} and the one # returned from {% cycle name %} are the exact same object. This shouldn't # cause problems (heh), but if it does, now you know. # # Ugly hack warning: this stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. args = token.contents.split() if len(args) < 2: raise TemplateSyntaxError("'Cycle' statement requires at least two arguments") elif len(args) == 2 and "," in args[1]: # {% cycle a,b,c %} cyclevars = [v for v in args[1].split(",") if v] # split and kill blanks return CycleNode(cyclevars) # {% cycle name %} elif len(args) == 2: name = args[1] if not hasattr(parser, '_namedCycleNodes'): raise TemplateSyntaxError("No named cycles in template: '%s' is not defined" % name) if not parser._namedCycleNodes.has_key(name): raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._namedCycleNodes[name] elif len(args) == 4: # {% cycle a,b,c as name %} if args[2] != 'as': raise TemplateSyntaxError("Second 'cycle' argument must be 'as'") cyclevars = [v for v in args[1].split(",") if v] # split and kill blanks name = args[3] node = CycleNode(cyclevars, name) if not hasattr(parser, '_namedCycleNodes'): parser._namedCycleNodes = {} parser._namedCycleNodes[name] = node return node else: raise TemplateSyntaxError("Invalid arguments to 'cycle': %s" % args) cycle = register.tag(cycle) def debug(parser, token): """ Output a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ return DebugNode() debug = register.tag(debug) #@register.tag(name="filter") def do_filter(parser, token): """ Filter the contents of the blog through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %} """ _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) nodelist = parser.parse(('endfilter',)) parser.delete_first_token() return FilterNode(filter_expr, nodelist) filter = register.tag("filter", do_filter) #@register.tag def firstof(parser, token): """ Outputs the first variable passed that is not False. Outputs nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 %} This is equivalent to:: {% if var1 %} {{ var1 }} {% else %}{% if var2 %} {{ var2 }} {% else %}{% if var3 %} {{ var3 }} {% endif %}{% endif %}{% endif %} but obviously much cleaner! """ bits = token.contents.split()[1:] if len(bits) < 1: raise TemplateSyntaxError, "'firstof' statement requires at least one argument" return FirstOfNode(bits) firstof = register.tag(firstof) #@register.tag(name="for") def do_for(parser, token): """ Loop over each item in an array. For example, to display a list of athletes given ``athlete_list``:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> You can also loop over a list in reverse by using ``{% for obj in list reversed %}``. The for loop sets a number of variables available within the loop: ========================== ================================================ Variable Description ========================== ================================================ ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop "above" the current one ========================== ================================================ """ bits = token.contents.split() if len(bits) == 5 and bits[4] != 'reversed': raise TemplateSyntaxError, "'for' statements with five words should end in 'reversed': %s" % token.contents if len(bits) not in (4, 5): raise TemplateSyntaxError, "'for' statements should have either four or five words: %s" % token.contents if bits[2] != 'in': raise TemplateSyntaxError, "'for' statement must contain 'in' as the second word: %s" % token.contents loopvar = bits[1] sequence = parser.compile_filter(bits[3]) reversed = (len(bits) == 5) nodelist_loop = parser.parse(('endfor',)) parser.delete_first_token() return ForNode(loopvar, sequence, reversed, nodelist_loop) do_for = register.tag("for", do_for) def do_ifequal(parser, token, negate): bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError, "%r takes two arguments" % bits[0] end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = NodeList() return IfEqualNode(bits[1], bits[2], nodelist_true, nodelist_false, negate) #@register.tag def ifequal(parser, token): """ Output the contents of the block if the two arguments equal each other. Examples:: {% ifequal user.id comment.user_id %} ... {% endifequal %} {% ifnotequal user.id comment.user_id %} ... {% else %} ... {% endifnotequal %} """ return do_ifequal(parser, token, False) ifequal = register.tag(ifequal) #@register.tag def ifnotequal(parser, token): """Output the contents of the block if the two arguments are not equal. See ifequal.""" return do_ifequal(parser, token, True) ifnotequal = register.tag(ifnotequal) #@register.tag(name="if") def do_if(parser, token): """ The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output: :: {% if althlete_list %} Number of athletes: {{ althete_list|count }} {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. As you can see, the ``if`` tag can take an option ``{% else %}`` clause that will be displayed if the test fails. ``if`` tags may use ``or`` or ``not`` to test a number of variables or to negate a given variable:: {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} For simplicity, ``if`` tags do not allow ``and`` clauses. Use nested ``if`` tags instead:: {% if athlete_list %} {% if coach_list %} Number of athletes: {{ athlete_list|count }}. Number of coaches: {{ coach_list|count }}. {% endif %} {% endif %} """ bits = token.contents.split() del bits[0] if not bits: raise TemplateSyntaxError, "'if' statement requires at least one argument" # bits now looks something like this: ['a', 'or', 'not', 'b', 'or', 'c.d'] bitstr = ' '.join(bits) boolpairs = bitstr.split(' and ') boolvars = [] if len(boolpairs) == 1: link_type = IfNode.LinkTypes.or_ boolpairs = bitstr.split(' or ') else: link_type = IfNode.LinkTypes.and_ if ' or ' in bitstr: raise TemplateSyntaxError, "'if' tags can't mix 'and' and 'or'" for boolpair in boolpairs: if ' ' in boolpair: try: not_, boolvar = boolpair.split() except ValueError: raise TemplateSyntaxError, "'if' statement improperly formatted" if not_ != 'not': raise TemplateSyntaxError, "Expected 'not' in if statement" boolvars.append((True, parser.compile_filter(boolvar))) else: boolvars.append((False, parser.compile_filter(boolpair))) nodelist_true = parser.parse(('else', 'endif')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endif',)) parser.delete_first_token() else: nodelist_false = NodeList() return IfNode(boolvars, nodelist_true, nodelist_false, link_type) do_if = register.tag("if", do_if) #@register.tag def ifchanged(parser, token): """ Check if a value has changed from the last iteration of a loop. The 'ifchanged' block tag is used within a loop. It has two possible uses. 1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:: <h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %} 2. If given a variable, check whether that variable has changed. For example, the following shows the date every time it changes, but only shows the hour if both the hour and the date have changed:: {% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %} """ bits = token.contents.split() nodelist = parser.parse(('endifchanged',)) parser.delete_first_token() return IfChangedNode(nodelist, *bits[1:]) ifchanged = register.tag(ifchanged) #@register.tag def ssi(parser, token): """ Output the contents of a given file into the page. Like a simple "include" tag, the ``ssi`` tag includes the contents of another file -- which must be specified using an absolute page -- in the current page:: {% ssi /home/html/ljworld.com/includes/right_generic.html %} If the optional "parsed" parameter is given, the contents of the included file are evaluated as template code, with the current context:: {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} """ bits = token.contents.split() parsed = False if len(bits) not in (2, 3): raise TemplateSyntaxError, "'ssi' tag takes one argument: the path to the file to be included" if len(bits) == 3: if bits[2] == 'parsed': parsed = True else: raise TemplateSyntaxError, "Second (optional) argument to %s tag must be 'parsed'" % bits[0] return SsiNode(bits[1], parsed) ssi = register.tag(ssi) #@register.tag def load(parser, token): """ Load a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} """ bits = token.contents.split() for taglib in bits[1:]: # add the library to the parser try: lib = get_library("django.templatetags.%s" % taglib.split('.')[-1]) parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError, "'%s' is not a valid tag library: %s" % (taglib, e) return LoadNode() load = register.tag(load) #@register.tag def now(parser, token): """ Display the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ bits = token.contents.split('"') if len(bits) != 3: raise TemplateSyntaxError, "'now' statement takes one argument" format_string = bits[1] return NowNode(format_string) now = register.tag(now) #@register.tag def regroup(parser, token): """ Regroup a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``people`` is a list of ``Person`` objects that have ``first_name``, ``last_name``, and ``gender`` attributes, and you'd like to display a list that looks like: * Male: * George Bush * Bill Clinton * Female: * Margaret Thatcher * Colendeeza Rice * Unknown: * Pat Smith The following snippet of template code would accomplish this dubious task:: {% regroup people by gender as grouped %} <ul> {% for group in grouped %} <li>{{ group.grouper }} <ul> {% for item in group.list %} <li>{{ item }}</li> {% endfor %} </ul> {% endfor %} </ul> As you can see, ``{% regroup %}`` populates a variable with a list of objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the item that was grouped by; ``list`` contains the list of objects that share that ``grouper``. In this case, ``grouper`` would be ``Male``, ``Female`` and ``Unknown``, and ``list`` is the list of people with those genders. Note that `{% regroup %}`` does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of people was not sorted by gender, you'd need to make sure it is sorted before using it, i.e.:: {% regroup people|dictsort:"gender" by gender as grouped %} """ firstbits = token.contents.split(None, 3) if len(firstbits) != 4: raise TemplateSyntaxError, "'regroup' tag takes five arguments" target = parser.compile_filter(firstbits[1]) if firstbits[2] != 'by': raise TemplateSyntaxError, "second argument to 'regroup' tag must be 'by'" lastbits_reversed = firstbits[3][::-1].split(None, 2) if lastbits_reversed[1][::-1] != 'as': raise TemplateSyntaxError, "next-to-last argument to 'regroup' tag must be 'as'" expression = parser.compile_filter('var.%s' % lastbits_reversed[2][::-1]) var_name = lastbits_reversed[0][::-1] return RegroupNode(target, expression, var_name) regroup = register.tag(regroup) def spaceless(parser, token): """ Normalize whitespace between HTML tags to a single space. This includes tab characters and newlines. Example usage:: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example would return this HTML:: <p> <a href="foo/">Foo</a> </p> Only space between *tags* is normalized -- not space between tags and text. In this example, the space around ``Hello`` won't be stripped:: {% spaceless %} <strong> Hello </strong> {% endspaceless %} """ nodelist = parser.parse(('endspaceless',)) parser.delete_first_token() return SpacelessNode(nodelist) spaceless = register.tag(spaceless) #@register.tag def templatetag(parser, token): """ Output one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== ======= """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "'templatetag' statement takes one argument" tag = bits[1] if not TemplateTagNode.mapping.has_key(tag): raise TemplateSyntaxError, "Invalid templatetag argument: '%s'. Must be one of: %s" % \ (tag, TemplateTagNode.mapping.keys()) return TemplateTagNode(tag) templatetag = register.tag(templatetag) def url(parser, token): """ Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url path.to.some_view arg1,arg2,name1=value1 %} The first argument is a path to a view. It can be an absolute python path or just ``app_name.view_name`` without the project name if the view is located inside the project. Other arguments are comma-separated values that will be filled in place of positional and keyword arguments in the URL. All arguments for the URL should be present. For example if you have a view ``app_name.client`` taking client's id and the corresponding line in a URLconf looks like this:: ('^client/(\d+)/$', 'app_name.client') and this app's URLconf is included into the project's URLconf under some path:: ('^clients/', include('project_name.app_name.urls')) then in a template you can create a link for a certain client like this:: {% url app_name.client client.id %} The URL will look like ``/clients/client/123/``. """ bits = token.contents.split(' ', 2) if len(bits) < 2: raise TemplateSyntaxError, "'%s' takes at least one argument (path to a view)" % bits[0] args = [] kwargs = {} if len(bits) > 2: for arg in bits[2].split(','): if '=' in arg: k, v = arg.split('=', 1) kwargs[k] = parser.compile_filter(v) else: args.append(parser.compile_filter(arg)) return URLNode(bits[1], args, kwargs) url = register.tag(url) #@register.tag def widthratio(parser, token): """ For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:: <img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' /> Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). """ bits = token.contents.split() if len(bits) != 4: raise TemplateSyntaxError("widthratio takes three arguments") tag, this_value_expr, max_value_expr, max_width = bits try: max_width = int(max_width) except ValueError: raise TemplateSyntaxError("widthratio final argument must be an integer") return WidthRatioNode(parser.compile_filter(this_value_expr), parser.compile_filter(max_value_expr), max_width) widthratio = register.tag(widthratio)
Python
from django.conf import settings from django.core.exceptions import ImproperlyConfigured _standard_context_processors = None class ContextPopException(Exception): "pop() has been called more times than push()" pass class Context(object): "A stack container for variable context" def __init__(self, dict_=None): dict_ = dict_ or {} self.dicts = [dict_] def __repr__(self): return repr(self.dicts) def __iter__(self): for d in self.dicts: yield d def push(self): self.dicts = [{}] + self.dicts def pop(self): if len(self.dicts) == 1: raise ContextPopException del self.dicts[0] def __setitem__(self, key, value): "Set a variable in the current context" self.dicts[0][key] = value def __getitem__(self, key): "Get a variable's value, starting at the current context and going upward" for d in self.dicts: if d.has_key(key): return d[key] raise KeyError(key) def __delitem__(self, key): "Delete a variable from the current context" del self.dicts[0][key] def has_key(self, key): for d in self.dicts: if d.has_key(key): return True return False def __contains__(self, key): return self.has_key(key) def get(self, key, otherwise=None): for d in self.dicts: if d.has_key(key): return d[key] return otherwise def update(self, other_dict): "Like dict.update(). Pushes an entire dictionary's keys and values onto the context." self.dicts = [other_dict] + self.dicts # This is a function rather than module-level procedural code because we only # want it to execute if somebody uses RequestContext. def get_standard_processors(): global _standard_context_processors if _standard_context_processors is None: processors = [] for path in settings.TEMPLATE_CONTEXT_PROCESSORS: i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = __import__(module, {}, {}, [attr]) except ImportError, e: raise ImproperlyConfigured, 'Error importing request processor module %s: "%s"' % (module, e) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable request processor' % (module, attr) processors.append(func) _standard_context_processors = tuple(processors) return _standard_context_processors class RequestContext(Context): """ This subclass of template.Context automatically populates itself using the processors defined in TEMPLATE_CONTEXT_PROCESSORS. Additional processors can be specified as a list of callables using the "processors" keyword argument. """ def __init__(self, request, dict=None, processors=None): Context.__init__(self, dict) if processors is None: processors = () else: processors = tuple(processors) for processor in get_standard_processors() + processors: self.update(processor(request))
Python
"Default variable filters" from django.template import resolve_variable, Library from django.conf import settings from django.utils.translation import gettext import re import random as random_module register = Library() ####################### # STRING DECORATOR # ####################### def smart_string(obj): # FUTURE: Unicode strings should probably be normalized to a specific # encoding and non-unicode strings should be converted to unicode too. # if isinstance(obj, unicode): # obj = obj.encode(settings.DEFAULT_CHARSET) # else: # obj = unicode(obj, settings.DEFAULT_CHARSET) # FUTURE: Replace dumb string logic below with cool unicode logic above. if not isinstance(obj, basestring): obj = str(obj) return obj def stringfilter(func): """ Decorator for filters which should only receive strings. The object passed as the first positional argument will be converted to a string. """ def _dec(*args, **kwargs): if args: args = list(args) args[0] = smart_string(args[0]) return func(*args, **kwargs) # Include a reference to the real function (used to check original # arguments by the template parser). _dec._decorated_function = getattr(func, '_decorated_function', func) return _dec ################### # STRINGS # ################### def addslashes(value): "Adds slashes - useful for passing strings to JavaScript, for example." return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") addslashes = stringfilter(addslashes) def capfirst(value): "Capitalizes the first character of the value" return value and value[0].upper() + value[1:] capfirst = stringfilter(capfirst) def fix_ampersands(value): "Replaces ampersands with ``&amp;`` entities" from django.utils.html import fix_ampersands return fix_ampersands(value) fix_ampersands = stringfilter(fix_ampersands) def floatformat(text, arg=-1): """ If called without an argument, displays a floating point number as 34.2 -- but only if there's a point to be displayed. With a positive numeric argument, it displays that many decimal places always. With a negative numeric argument, it will display that many decimal places -- but only if there's places to be displayed. Examples: * num1 = 34.23234 * num2 = 34.00000 * num1|floatformat results in 34.2 * num2|floatformat is 34 * num1|floatformat:3 is 34.232 * num2|floatformat:3 is 34.000 * num1|floatformat:-3 is 34.232 * num2|floatformat:-3 is 34 """ try: f = float(text) except ValueError: return '' try: d = int(arg) except ValueError: return smart_string(f) m = f - int(f) if not m and d < 0: return '%d' % int(f) else: formatstr = '%%.%df' % abs(d) return formatstr % f def linenumbers(value): "Displays text with line numbers" from django.utils.html import escape lines = value.split('\n') # Find the maximum width of the line count, for use with zero padding string format command width = str(len(str(len(lines)))) for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return '\n'.join(lines) linenumbers = stringfilter(linenumbers) def lower(value): "Converts a string into all lowercase" return value.lower() lower = stringfilter(lower) def make_list(value): """ Returns the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) make_list = stringfilter(make_list) def slugify(value): "Converts to lowercase, removes non-alpha chars and converts spaces to hyphens" value = re.sub('[^\w\s-]', '', value).strip().lower() return re.sub('[-\s]+', '-', value) slugify = stringfilter(slugify) def stringformat(value, arg): """ Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formating syntax, with the exception that the leading "%" is dropped. See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting """ try: return ("%" + str(arg)) % value except (ValueError, TypeError): return "" def title(value): "Converts a string into titlecase" return re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) title = stringfilter(title) def truncatewords(value, arg): """ Truncates a string after a certain number of words Argument: Number of words to truncate after """ from django.utils.text import truncate_words try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. if not isinstance(value, basestring): value = str(value) return truncate_words(value, length) truncatewords = stringfilter(truncatewords) def truncatewords_html(value, arg): """ Truncates HTML after a certain number of words Argument: Number of words to truncate after """ from django.utils.text import truncate_html_words try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. if not isinstance(value, basestring): value = str(value) return truncate_html_words(value, length) truncatewords_html = stringfilter(truncatewords_html) def upper(value): "Converts a string into all uppercase" return value.upper() upper = stringfilter(upper) def urlencode(value): "Escapes a value for use in a URL" import urllib if not isinstance(value, basestring): value = str(value) return urllib.quote(value) urlencode = stringfilter(urlencode) def urlize(value): "Converts URLs in plain text into clickable links" from django.utils.html import urlize return urlize(value, nofollow=True) urlize = stringfilter(urlize) def urlizetrunc(value, limit): """ Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ from django.utils.html import urlize return urlize(value, trim_url_limit=int(limit), nofollow=True) urlizetrunc = stringfilter(urlizetrunc) def wordcount(value): "Returns the number of words" return len(value.split()) wordcount = stringfilter(wordcount) def wordwrap(value, arg): """ Wraps words at specified line length Argument: number of characters to wrap the text at. """ from django.utils.text import wrap return wrap(value, int(arg)) wordwrap = stringfilter(wordwrap) def ljust(value, arg): """ Left-aligns the value in a field of a given width Argument: field size """ return value.ljust(int(arg)) ljust = stringfilter(ljust) def rjust(value, arg): """ Right-aligns the value in a field of a given width Argument: field size """ return value.rjust(int(arg)) rjust = stringfilter(rjust) def center(value, arg): "Centers the value in a field of a given width" return value.center(int(arg)) center = stringfilter(center) def cut(value, arg): "Removes all values of arg from the given string" return value.replace(arg, '') cut = stringfilter(cut) ################### # HTML STRINGS # ################### def escape(value): "Escapes a string's HTML" from django.utils.html import escape return escape(value) escape = stringfilter(escape) def linebreaks(value): "Converts newlines into <p> and <br />s" from django.utils.html import linebreaks return linebreaks(value) linebreaks = stringfilter(linebreaks) def linebreaksbr(value): "Converts newlines into <br />s" return value.replace('\n', '<br />') linebreaksbr = stringfilter(linebreaksbr) def removetags(value, tags): "Removes a space separated list of [X]HTML tags from the output" tags = [re.escape(tag) for tag in tags.split()] tags_re = '(%s)' % '|'.join(tags) starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re) endtag_re = re.compile('</%s>' % tags_re) value = starttag_re.sub('', value) value = endtag_re.sub('', value) return value removetags = stringfilter(removetags) def striptags(value): "Strips all [X]HTML tags" from django.utils.html import strip_tags return strip_tags(value) striptags = stringfilter(striptags) ################### # LISTS # ################### def dictsort(value, arg): """ Takes a list of dicts, returns that list sorted by the property given in the argument. """ decorated = [(resolve_variable('var.' + arg, {'var' : item}), item) for item in value] decorated.sort() return [item[1] for item in decorated] def dictsortreversed(value, arg): """ Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. """ decorated = [(resolve_variable('var.' + arg, {'var' : item}), item) for item in value] decorated.sort() decorated.reverse() return [item[1] for item in decorated] def first(value): "Returns the first item in a list" try: return value[0] except IndexError: return '' def join(value, arg): "Joins a list with a string, like Python's ``str.join(list)``" try: return arg.join(map(smart_string, value)) except AttributeError: # fail silently but nicely return value def length(value): "Returns the length of the value - useful for lists" return len(value) def length_is(value, arg): "Returns a boolean of whether the value's length is the argument" return len(value) == int(arg) def random(value): "Returns a random item from the list" return random_module.choice(value) def slice_(value, arg): """ Returns a slice of the list. Uses the same syntax as Python's list slicing; see http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice for an introduction. """ try: bits = [] for x in arg.split(':'): if len(x) == 0: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. def unordered_list(value): """ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. The list is assumed to be in the proper format. For example, if ``var`` contains ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``, then ``{{ var|unordered_list }}`` would return:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ def _helper(value, tabs): indent = '\t' * tabs if value[1]: return '%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent, '\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent) else: return '%s<li>%s</li>' % (indent, value[0]) return _helper(value, 1) ################### # INTEGERS # ################### def add(value, arg): "Adds the arg to the value" return int(value) + int(arg) def get_digit(value, arg): """ Given a whole number, returns the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 ################### # DATES # ################### def date(value, arg=None): "Formats a date according to the given format" from django.utils.dateformat import format if not value: return '' if arg is None: arg = settings.DATE_FORMAT return format(value, arg) def time(value, arg=None): "Formats a time according to the given format" from django.utils.dateformat import time_format if value in (None, ''): return '' if arg is None: arg = settings.TIME_FORMAT return time_format(value, arg) def timesince(value, arg=None): 'Formats a date as the time since that date (i.e. "4 days, 6 hours")' from django.utils.timesince import timesince if not value: return '' if arg: return timesince(arg, value) return timesince(value) def timeuntil(value, arg=None): 'Formats a date as the time until that date (i.e. "4 days, 6 hours")' from django.utils.timesince import timesince from datetime import datetime if not value: return '' if arg: return timesince(arg, value) return timesince(datetime.now(), value) ################### # LOGIC # ################### def default(value, arg): "If value is unavailable, use given default" return value or arg def default_if_none(value, arg): "If value is None, use given default" if value is None: return arg return value def divisibleby(value, arg): "Returns true if the value is devisible by the argument" return int(value) % int(arg) == 0 def yesno(value, arg=None): """ Given a string mapping values for true, false and (optionally) None, returns one of those strings accoding to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: arg = gettext('yes,no,maybe') bits = arg.split(',') if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # unpack list of wrong size (no "maybe" value provided) yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ################### def filesizeformat(bytes): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except TypeError: return "0 bytes" if bytes < 1024: return "%d byte%s" % (bytes, bytes != 1 and 's' or '') if bytes < 1024 * 1024: return "%.1f KB" % (bytes / 1024) if bytes < 1024 * 1024 * 1024: return "%.1f MB" % (bytes / (1024 * 1024)) return "%.1f GB" % (bytes / (1024 * 1024 * 1024)) def pluralize(value, arg='s'): """ Returns a plural suffix if the value is not 1, for '1 vote' vs. '2 votes' By default, 's' is used as a suffix; if an argument is provided, that string is used instead. If the provided argument contains a comma, the text before the comma is used for the singular case. """ if not ',' in arg: arg = ',' + arg bits = arg.split(',') if len(bits) > 2: return '' singular_suffix, plural_suffix = bits[:2] try: if int(value) != 1: return plural_suffix except ValueError: # invalid string that's not a number pass except TypeError: # value isn't a string or a number; maybe it's a list? try: if len(value) != 1: return plural_suffix except TypeError: # len() of unsized object pass return singular_suffix def phone2numeric(value): "Takes a phone number and converts it in to its numerical equivalent" from django.utils.text import phone2numeric return phone2numeric(value) def pprint(value): "A wrapper around pprint.pprint -- for debugging, really" from pprint import pformat try: return pformat(value) except Exception, e: return "Error in formatting:%s" % e # Syntax: register.filter(name of filter, callback) register.filter(add) register.filter(addslashes) register.filter(capfirst) register.filter(center) register.filter(cut) register.filter(date) register.filter(default) register.filter(default_if_none) register.filter(dictsort) register.filter(dictsortreversed) register.filter(divisibleby) register.filter(escape) register.filter(filesizeformat) register.filter(first) register.filter(fix_ampersands) register.filter(floatformat) register.filter(get_digit) register.filter(join) register.filter(length) register.filter(length_is) register.filter(linebreaks) register.filter(linebreaksbr) register.filter(linenumbers) register.filter(ljust) register.filter(lower) register.filter(make_list) register.filter(phone2numeric) register.filter(pluralize) register.filter(pprint) register.filter(removetags) register.filter(random) register.filter(rjust) register.filter('slice', slice_) register.filter(slugify) register.filter(stringformat) register.filter(striptags) register.filter(time) register.filter(timesince) register.filter(timeuntil) register.filter(title) register.filter(truncatewords) register.filter(truncatewords_html) register.filter(unordered_list) register.filter(upper) register.filter(urlencode) register.filter(urlize) register.filter(urlizetrunc) register.filter(wordcount) register.filter(wordwrap) register.filter(yesno)
Python
# Wrapper for loading templates from storage of some sort (e.g. filesystem, database). # # This uses the TEMPLATE_LOADERS setting, which is a list of loaders to use. # Each loader is expected to have this interface: # # callable(name, dirs=[]) # # name is the template name. # dirs is an optional list of directories to search instead of TEMPLATE_DIRS. # # The loader should return a tuple of (template_source, path). The path returned # might be shown to the user for debugging purposes, so it should identify where # the template was loaded from. # # Each loader should have an "is_usable" attribute set. This is a boolean that # specifies whether the loader can be used in this Python installation. Each # loader is responsible for setting this when it's initialized. # # For example, the eggs loader (which is capable of loading templates from # Python eggs) sets is_usable to False if the "pkg_resources" module isn't # installed, because pkg_resources is necessary to read eggs. from django.core.exceptions import ImproperlyConfigured from django.template import Origin, Template, Context, TemplateDoesNotExist, add_to_builtins from django.conf import settings template_source_loaders = None class LoaderOrigin(Origin): def __init__(self, display_name, loader, name, dirs): super(LoaderOrigin, self).__init__(display_name) self.loader, self.loadname, self.dirs = loader, name, dirs def reload(self): return self.loader(self.loadname, self.dirs)[0] def make_origin(display_name, loader, name, dirs): if settings.TEMPLATE_DEBUG: return LoaderOrigin(display_name, loader, name, dirs) else: return None def find_template_source(name, dirs=None): # Calculate template_source_loaders the first time the function is executed # because putting this logic in the module-level namespace may cause # circular import errors. See Django ticket #1292. global template_source_loaders if template_source_loaders is None: template_source_loaders = [] for path in settings.TEMPLATE_LOADERS: i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr) if not func.is_usable: import warnings warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % path) else: template_source_loaders.append(func) for loader in template_source_loaders: try: source, display_name = loader(name, dirs) return (source, make_origin(display_name, loader, name, dirs)) except TemplateDoesNotExist: pass raise TemplateDoesNotExist, name def get_template(template_name): """ Returns a compiled Template object for the given template name, handling template inheritance recursively. """ source, origin = find_template_source(template_name) template = get_template_from_string(source, origin, template_name) return template def get_template_from_string(source, origin=None, name=None): """ Returns a compiled Template object for the given template code, handling template inheritance recursively. """ return Template(source, origin, name) def render_to_string(template_name, dictionary=None, context_instance=None): """ Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string. """ dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): t = select_template(template_name) else: t = get_template(template_name) if context_instance: context_instance.update(dictionary) else: context_instance = Context(dictionary) return t.render(context_instance) def select_template(template_name_list): "Given a list of template names, returns the first that can be loaded." for template_name in template_name_list: try: return get_template(template_name) except TemplateDoesNotExist: continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist, ', '.join(template_name_list) add_to_builtins('django.template.loader_tags')
Python
# Wrapper for loading templates from "template" directories in installed app packages. from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist import os # At compile time, cache the directories to search. app_template_dirs = [] for app in settings.INSTALLED_APPS: i = app.rfind('.') if i == -1: m, a = app, None else: m, a = app[:i], app[i+1:] try: if a is None: mod = __import__(m, {}, {}, []) else: mod = getattr(__import__(m, {}, {}, [a]), a) except ImportError, e: raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0]) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): app_template_dirs.append(template_dir) # It won't change, so convert it to a tuple to save memory. app_template_dirs = tuple(app_template_dirs) def get_template_sources(template_name, template_dirs=None): for template_dir in app_template_dirs: yield os.path.join(template_dir, template_name) def load_template_source(template_name, template_dirs=None): for filepath in get_template_sources(template_name, template_dirs): try: return (open(filepath).read(), filepath) except IOError: pass raise TemplateDoesNotExist, template_name load_template_source.is_usable = True
Python
# Wrapper for loading templates from eggs via pkg_resources.resource_string. try: from pkg_resources import resource_string except ImportError: resource_string = None from django.template import TemplateDoesNotExist from django.conf import settings def load_template_source(template_name, template_dirs=None): """ Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name). """ if resource_string is not None: pkg_name = 'templates/' + template_name for app in settings.INSTALLED_APPS: try: return (resource_string(app, pkg_name), 'egg:%s:%s ' % (app, pkg_name)) except: pass raise TemplateDoesNotExist, template_name load_template_source.is_usable = resource_string is not None
Python
# Wrapper for loading templates from the filesystem. from django.conf import settings from django.template import TemplateDoesNotExist import os def get_template_sources(template_name, template_dirs=None): if not template_dirs: template_dirs = settings.TEMPLATE_DIRS for template_dir in template_dirs: yield os.path.join(template_dir, template_name) def load_template_source(template_name, template_dirs=None): tried = [] for filepath in get_template_sources(template_name, template_dirs): try: return (open(filepath).read(), filepath) except IOError: tried.append(filepath) if tried: error_msg = "Tried %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist, error_msg load_template_source.is_usable = True
Python
""" This is the Django template system. How it works: The Lexer.tokenize() function converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of an IfNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> import template >>> s = ''' ... <html> ... {% if test %} ... <h1>{{ varvalue }}</h1> ... {% endif %} ... </html> ... ''' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) '\n<html>\n\n <h1>Hello</h1>\n\n</html>\n' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '\n<html>\n\n</html>\n' """ import re from inspect import getargspec from django.conf import settings from django.template.context import Context, RequestContext, ContextPopException from django.utils.functional import curry from django.utils.text import smart_split __all__ = ('Template', 'Context', 'RequestContext', 'compile_string') TOKEN_TEXT = 0 TOKEN_VAR = 1 TOKEN_BLOCK = 2 TOKEN_COMMENT = 3 # template syntax constants FILTER_SEPARATOR = '|' FILTER_ARGUMENT_SEPARATOR = ':' VARIABLE_ATTRIBUTE_SEPARATOR = '.' BLOCK_TAG_START = '{%' BLOCK_TAG_END = '%}' VARIABLE_TAG_START = '{{' VARIABLE_TAG_END = '}}' COMMENT_TAG_START = '{#' COMMENT_TAG_END = '#}' SINGLE_BRACE_START = '{' SINGLE_BRACE_END = '}' ALLOWED_VARIABLE_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.' # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE="&lt;unknown source&gt;" # match a variable or block tag and capture the entire tag, including start/end delimiters tag_re = re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' % (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END))) # matches if the string is valid number number_re = re.compile(r'[-+]?(\d+|\d*\.\d+)$') # global dictionary of libraries that have been loaded using get_library libraries = {} # global list of libraries to load by default for a new parser builtins = [] class TemplateSyntaxError(Exception): def __str__(self): try: import cStringIO as StringIO except ImportError: import StringIO output = StringIO.StringIO() output.write(Exception.__str__(self)) # Check if we wrapped an exception and print that too. if hasattr(self, 'exc_info'): import traceback output.write('\n\nOriginal ') e = self.exc_info traceback.print_exception(e[0], e[1], e[2], 500, output) return output.getvalue() class TemplateDoesNotExist(Exception): pass class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class InvalidTemplateLibrary(Exception): pass class Origin(object): def __init__(self, name): self.name = name def reload(self): raise NotImplementedError def __str__(self): return self.name class StringOrigin(Origin): def __init__(self, source): super(StringOrigin, self).__init__(UNKNOWN_SOURCE) self.source = source def reload(self): return self.source class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): "Compilation stage" if settings.TEMPLATE_DEBUG and origin == None: origin = StringOrigin(template_string) # Could do some crazy stack-frame stuff to record where this string # came from... self.nodelist = compile_string(template_string, origin) self.name = name def __iter__(self): for node in self.nodelist: for subnode in node: yield subnode def render(self, context): "Display stage -- can be called many times" return self.nodelist.render(context) def compile_string(template_string, origin): "Compiles template_string into NodeList ready for rendering" lexer = lexer_factory(template_string, origin) parser = parser_factory(lexer.tokenize()) return parser.parse() class Token(object): def __init__(self, token_type, contents): "The token_type must be TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK or TOKEN_COMMENT" self.token_type, self.contents = token_type, contents def __str__(self): return '<%s token: "%s...">' % \ ({TOKEN_TEXT: 'Text', TOKEN_VAR: 'Var', TOKEN_BLOCK: 'Block', TOKEN_COMMENT: 'Comment'}[self.token_type], self.contents[:20].replace('\n', '')) def split_contents(self): return list(smart_split(self.contents)) class Lexer(object): def __init__(self, template_string, origin): self.template_string = template_string self.origin = origin def tokenize(self): "Return a list of tokens from a given template_string" # remove all empty strings, because the regex has a tendency to add them bits = filter(None, tag_re.split(self.template_string)) return map(self.create_token, bits) def create_token(self,token_string): "Convert the given token string into a new Token object and return it" if token_string.startswith(VARIABLE_TAG_START): token = Token(TOKEN_VAR, token_string[len(VARIABLE_TAG_START):-len(VARIABLE_TAG_END)].strip()) elif token_string.startswith(BLOCK_TAG_START): token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):-len(BLOCK_TAG_END)].strip()) elif token_string.startswith(COMMENT_TAG_START): token = Token(TOKEN_COMMENT, '') else: token = Token(TOKEN_TEXT, token_string) return token class DebugLexer(Lexer): def __init__(self, template_string, origin): super(DebugLexer, self).__init__(template_string, origin) def tokenize(self): "Return a list of tokens from a given template_string" token_tups, upto = [], 0 for match in tag_re.finditer(self.template_string): start, end = match.span() if start > upto: token_tups.append( (self.template_string[upto:start], (upto, start)) ) upto = start token_tups.append( (self.template_string[start:end], (start,end)) ) upto = end last_bit = self.template_string[upto:] if last_bit: token_tups.append( (last_bit, (upto, upto + len(last_bit))) ) return [self.create_token(tok, (self.origin, loc)) for tok, loc in token_tups] def create_token(self, token_string, source): token = super(DebugLexer, self).create_token(token_string) token.source = source return token class Parser(object): def __init__(self, tokens): self.tokens = tokens self.tags = {} self.filters = {} for lib in builtins: self.add_library(lib) def parse(self, parse_until=None): if parse_until is None: parse_until = [] nodelist = self.create_nodelist() while self.tokens: token = self.next_token() if token.token_type == TOKEN_TEXT: self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token.token_type == TOKEN_VAR: if not token.contents: self.empty_variable(token) filter_expression = self.compile_filter(token.contents) var_node = self.create_variable_node(filter_expression) self.extend_nodelist(nodelist, var_node,token) elif token.token_type == TOKEN_BLOCK: if token.contents in parse_until: # put token back on token list so calling code knows why it terminated self.prepend_token(token) return nodelist try: command = token.contents.split()[0] except IndexError: self.empty_block_tag(token) # execute callback function for this tag and append resulting node self.enter_command(command, token) try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command) try: compiled_result = compile_func(self, token) except TemplateSyntaxError, e: if not self.compile_function_error(token, e): raise self.extend_nodelist(nodelist, compiled_result, token) self.exit_command() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TOKEN_BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def create_variable_node(self, filter_expression): return VariableNode(filter_expression) def create_nodelist(self): return NodeList() def extend_nodelist(self, nodelist, node, token): nodelist.append(node) def enter_command(self, command, token): pass def exit_command(self): pass def error(self, token, msg ): return TemplateSyntaxError(msg) def empty_variable(self, token): raise self.error( token, "Empty variable tag") def empty_block_tag(self, token): raise self.error( token, "Empty block tag") def invalid_block_tag(self, token, command): raise self.error( token, "Invalid block tag: '%s'" % command) def unclosed_block_tag(self, parse_until): raise self.error(None, "Unclosed tags: %s " % ', '.join(parse_until)) def compile_function_error(self, token, e): pass def next_token(self): return self.tokens.pop(0) def prepend_token(self, token): self.tokens.insert(0, token) def delete_first_token(self): del self.tokens[0] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): "Convenient wrapper for FilterExpression" return FilterExpression(token, self) def find_filter(self, filter_name): if self.filters.has_key(filter_name): return self.filters[filter_name] else: raise TemplateSyntaxError, "Invalid filter: '%s'" % filter_name class DebugParser(Parser): def __init__(self, lexer): super(DebugParser, self).__init__(lexer) self.command_stack = [] def enter_command(self, command, token): self.command_stack.append( (command, token.source) ) def exit_command(self): self.command_stack.pop() def error(self, token, msg): return self.source_error(token.source, msg) def source_error(self, source,msg): e = TemplateSyntaxError(msg) e.source = source return e def create_nodelist(self): return DebugNodeList() def create_variable_node(self, contents): return DebugVariableNode(contents) def extend_nodelist(self, nodelist, node, token): node.source = token.source super(DebugParser, self).extend_nodelist(nodelist, node, token) def unclosed_block_tag(self, parse_until): command, source = self.command_stack.pop() msg = "Unclosed tag '%s'. Looking for one of: %s " % (command, ', '.join(parse_until)) raise self.source_error( source, msg) def compile_function_error(self, token, e): if not hasattr(e, 'source'): e.source = token.source def lexer_factory(*args, **kwargs): if settings.TEMPLATE_DEBUG: return DebugLexer(*args, **kwargs) else: return Lexer(*args, **kwargs) def parser_factory(*args, **kwargs): if settings.TEMPLATE_DEBUG: return DebugParser(*args, **kwargs) else: return Parser(*args, **kwargs) class TokenParser(object): """ Subclass this and implement the top() method to parse a template line. When instantiating the parser, pass in the line from the Django template parser. The parser's "tagname" instance-variable stores the name of the tag that the filter was called with. """ def __init__(self, subject): self.subject = subject self.pointer = 0 self.backout = [] self.tagname = self.tag() def top(self): "Overload this method to do the actual parsing and return the result." raise NotImplemented def more(self): "Returns True if there is more stuff in the tag." return self.pointer < len(self.subject) def back(self): "Undoes the last microparser. Use this for lookahead and backtracking." if not len(self.backout): raise TemplateSyntaxError, "back called without some previous parsing" self.pointer = self.backout.pop() def tag(self): "A microparser that just returns the next tag from the line." subject = self.subject i = self.pointer if i >= len(subject): raise TemplateSyntaxError, "expected another tag, found end of string: %s" % subject p = i while i < len(subject) and subject[i] not in (' ', '\t'): i += 1 s = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return s def value(self): "A microparser that parses for a value: some string constant or variable name." subject = self.subject i = self.pointer if i >= len(subject): raise TemplateSyntaxError, "Searching for value. Expected another value but found end of string: %s" % subject if subject[i] in ('"', "'"): p = i i += 1 while i < len(subject) and subject[i] != subject[p]: i += 1 if i >= len(subject): raise TemplateSyntaxError, "Searching for value. Unexpected end of string in column %d: %s" % (i, subject) i += 1 res = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return res else: p = i while i < len(subject) and subject[i] not in (' ', '\t'): if subject[i] in ('"', "'"): c = subject[i] i += 1 while i < len(subject) and subject[i] != c: i += 1 if i >= len(subject): raise TemplateSyntaxError, "Searching for value. Unexpected end of string in column %d: %s" % subject i += 1 s = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return s filter_raw_string = r""" ^%(i18n_open)s"(?P<i18n_constant>%(str)s)"%(i18n_close)s| ^"(?P<constant>%(str)s)"| ^(?P<var>[%(var_chars)s]+)| (?:%(filter_sep)s (?P<filter_name>\w+) (?:%(arg_sep)s (?: %(i18n_open)s"(?P<i18n_arg>%(str)s)"%(i18n_close)s| "(?P<constant_arg>%(str)s)"| (?P<var_arg>[%(var_chars)s]+) ) )? )""" % { 'str': r"""[^"\\]*(?:\\.[^"\\]*)*""", 'var_chars': "A-Za-z0-9\_\." , 'filter_sep': re.escape(FILTER_SEPARATOR), 'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR), 'i18n_open' : re.escape("_("), 'i18n_close' : re.escape(")"), } filter_raw_string = filter_raw_string.replace("\n", "").replace(" ", "") filter_re = re.compile(filter_raw_string) class FilterExpression(object): """ Parses a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = FilterParser(token) >>> p.filters [('default', 'Default value'), ('date', 'Y-m-d')] >>> p.var 'variable' This class should never be instantiated outside of the get_filters_from_token helper function. """ def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError, "Could not parse some characters: %s|%s|%s" % \ (token[:upto], token[upto:start], token[start:]) if var == None: var, constant, i18n_constant = match.group("var", "constant", "i18n_constant") if i18n_constant: var = '"%s"' % _(i18n_constant) elif constant: var = '"%s"' % constant upto = match.end() if var == None: raise TemplateSyntaxError, "Could not find variable at start of %s" % token elif var.find(VARIABLE_ATTRIBUTE_SEPARATOR + '_') > -1 or var[0] == '_': raise TemplateSyntaxError, "Variables and attributes may not begin with underscores: '%s'" % var else: filter_name = match.group("filter_name") args = [] constant_arg, i18n_arg, var_arg = match.group("constant_arg", "i18n_arg", "var_arg") if i18n_arg: args.append((False, _(i18n_arg.replace(r'\"', '"')))) elif constant_arg is not None: args.append((False, constant_arg.replace(r'\"', '"'))) elif var_arg: args.append((True, var_arg)) filter_func = parser.find_filter(filter_name) self.args_check(filter_name,filter_func, args) filters.append( (filter_func,args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] self.var, self.filters = var, filters def resolve(self, context, ignore_failures=False): try: obj = resolve_variable(self.var, context) except VariableDoesNotExist: if ignore_failures: obj = None else: if settings.TEMPLATE_STRING_IF_INVALID: return settings.TEMPLATE_STRING_IF_INVALID else: obj = settings.TEMPLATE_STRING_IF_INVALID for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(arg) else: arg_vals.append(resolve_variable(arg, context)) obj = func(obj, *arg_vals) return obj def args_check(name, func, provided): provided = list(provided) plen = len(provided) # Check to see if a decorator is providing the real function. func = getattr(func, '_decorated_function', func) args, varargs, varkw, defaults = getargspec(func) # First argument is filter input. args.pop(0) if defaults: nondefs = args[:-len(defaults)] else: nondefs = args # Args without defaults must be provided. try: for arg in nondefs: provided.pop(0) except IndexError: # Not enough raise TemplateSyntaxError, "%s requires %d arguments, %d provided" % (name, len(nondefs), plen) # Defaults can be overridden. defaults = defaults and list(defaults) or [] try: for parg in provided: defaults.pop(0) except IndexError: # Too many. raise TemplateSyntaxError, "%s requires %d arguments, %d provided" % (name, len(nondefs), plen) return True args_check = staticmethod(args_check) def __str__(self): return self.token def resolve_variable(path, context): """ Returns the resolved variable, which may contain attribute syntax, within the given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks). >>> c = {'article': {'section':'News'}} >>> resolve_variable('article.section', c) 'News' >>> resolve_variable('article', c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' >>> resolve_variable('article.section', c) 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ if number_re.match(path): number_type = '.' in path and float or int current = number_type(path) elif path[0] in ('"', "'") and path[0] == path[-1]: current = path[1:-1] else: current = context bits = path.split(VARIABLE_ATTRIBUTE_SEPARATOR) while bits: try: # dictionary lookup current = current[bits[0]] except (TypeError, AttributeError, KeyError): try: # attribute lookup current = getattr(current, bits[0]) if callable(current): if getattr(current, 'alters_data', False): current = settings.TEMPLATE_STRING_IF_INVALID else: try: # method call (assuming no args required) current = current() except TypeError: # arguments *were* required # GOTCHA: This will also catch any TypeError # raised in the function itself. current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call except Exception, e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: raise except (TypeError, AttributeError): try: # list-index lookup current = current[int(bits[0])] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bits[0])` key TypeError, # unsubscriptable object ): raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bits[0], current)) # missing attribute except Exception, e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: raise del bits[0] return current class Node(object): def render(self, context): "Return the node rendered as a string" pass def __iter__(self): yield self def get_nodes_by_type(self, nodetype): "Return a list of all nodes (within this node and its nodelist) of the given type" nodes = [] if isinstance(self, nodetype): nodes.append(self) if hasattr(self, 'nodelist'): nodes.extend(self.nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): def render(self, context): bits = [] for node in self: if isinstance(node, Node): bits.append(self.render_node(node, context)) else: bits.append(node) return ''.join(bits) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes def render_node(self, node, context): return(node.render(context)) class DebugNodeList(NodeList): def render_node(self, node, context): try: result = node.render(context) except TemplateSyntaxError, e: if not hasattr(e, 'source'): e.source = node.source raise except Exception, e: from sys import exc_info wrapped = TemplateSyntaxError('Caught an exception while rendering: %s' % e) wrapped.source = node.source wrapped.exc_info = exc_info() raise wrapped return result class TextNode(Node): def __init__(self, s): self.s = s def __repr__(self): return "<Text Node: '%s'>" % self.s[:25] def render(self, context): return self.s class VariableNode(Node): def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def encode_output(self, output): # Check type so that we don't run str() on a Unicode object if not isinstance(output, basestring): try: return str(output) except UnicodeEncodeError: # If __str__() returns a Unicode object, convert it to bytestring. return unicode(output).encode(settings.DEFAULT_CHARSET) elif isinstance(output, unicode): return output.encode(settings.DEFAULT_CHARSET) else: return output def render(self, context): output = self.filter_expression.resolve(context) return self.encode_output(output) class DebugVariableNode(VariableNode): def render(self, context): try: output = self.filter_expression.resolve(context) except TemplateSyntaxError, e: if not hasattr(e, 'source'): e.source = self.source raise return self.encode_output(output) def generic_tag_compiler(params, defaults, name, node_class, parser, token): "Returns a template.Node subclass." bits = token.split_contents()[1:] bmax = len(params) def_len = defaults and len(defaults) or 0 bmin = bmax - def_len if(len(bits) < bmin or len(bits) > bmax): if bmin == bmax: message = "%s takes %s arguments" % (name, bmin) else: message = "%s takes between %s and %s arguments" % (name, bmin, bmax) raise TemplateSyntaxError, message return node_class(bits) class Library(object): def __init__(self): self.filters = {} self.tags = {} def tag(self, name=None, compile_function=None): if name == None and compile_function == None: # @register.tag() return self.tag_function elif name != None and compile_function == None: if(callable(name)): # @register.tag return self.tag_function(name) else: # @register.tag('somename') or @register.tag(name='somename') def dec(func): return self.tag(name, func) return dec elif name != None and compile_function != None: # register.tag('somename', somefunc) self.tags[name] = compile_function return compile_function else: raise InvalidTemplateLibrary, "Unsupported arguments to Library.tag: (%r, %r)", (name, compile_function) def tag_function(self,func): self.tags[getattr(func, "_decorated_function", func).__name__] = func return func def filter(self, name=None, filter_func=None): if name == None and filter_func == None: # @register.filter() return self.filter_function elif filter_func == None: if(callable(name)): # @register.filter return self.filter_function(name) else: # @register.filter('somename') or @register.filter(name='somename') def dec(func): return self.filter(name, func) return dec elif name != None and filter_func != None: # register.filter('somename', somefunc) self.filters[name] = filter_func return filter_func else: raise InvalidTemplateLibrary, "Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func) def filter_function(self, func): self.filters[getattr(func, "_decorated_function", func).__name__] = func return func def simple_tag(self,func): params, xx, xxx, defaults = getargspec(func) class SimpleNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = vars_to_resolve def render(self, context): resolved_vars = [resolve_variable(var, context) for var in self.vars_to_resolve] return func(*resolved_vars) compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, SimpleNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func def inclusion_tag(self, file_name, context_class=Context, takes_context=False): def dec(func): params, xx, xxx, defaults = getargspec(func) if takes_context: if params[0] == 'context': params = params[1:] else: raise TemplateSyntaxError, "Any tag function decorated with takes_context=True must have a first argument of 'context'" class InclusionNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = vars_to_resolve def render(self, context): resolved_vars = [resolve_variable(var, context) for var in self.vars_to_resolve] if takes_context: args = [context] + resolved_vars else: args = resolved_vars dict = func(*args) if not getattr(self, 'nodelist', False): from django.template.loader import get_template, select_template if hasattr(file_name, '__iter__'): t = select_template(file_name) else: t = get_template(file_name) self.nodelist = t.nodelist return self.nodelist.render(context_class(dict)) compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, InclusionNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func return dec def get_library(module_name): lib = libraries.get(module_name, None) if not lib: try: mod = __import__(module_name, {}, {}, ['']) except ImportError, e: raise InvalidTemplateLibrary, "Could not load template library from %s, %s" % (module_name, e) try: lib = mod.register libraries[module_name] = lib except AttributeError: raise InvalidTemplateLibrary, "Template library %s does not have a variable named 'register'" % module_name return lib def add_to_builtins(module_name): builtins.append(get_library(module_name)) add_to_builtins('django.template.defaulttags') add_to_builtins('django.template.defaultfilters')
Python
from django.template import TemplateSyntaxError, TemplateDoesNotExist, resolve_variable from django.template import Library, Node from django.template.loader import get_template, get_template_from_string, find_template_source from django.conf import settings register = Library() class ExtendsError(Exception): pass class BlockNode(Node): def __init__(self, name, nodelist, parent=None): self.name, self.nodelist, self.parent = name, nodelist, parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): context.push() # Save context in case of block.super(). self.context = context context['block'] = self result = self.nodelist.render(context) context.pop() return result def super(self): if self.parent: return self.parent.render(self.context) return '' def add_parent(self, nodelist): if self.parent: self.parent.add_parent(nodelist) else: self.parent = BlockNode(self.name, nodelist) class ExtendsNode(Node): def __init__(self, nodelist, parent_name, parent_name_expr, template_dirs=None): self.nodelist = nodelist self.parent_name, self.parent_name_expr = parent_name, parent_name_expr self.template_dirs = template_dirs def get_parent(self, context): if self.parent_name_expr: self.parent_name = self.parent_name_expr.resolve(context) parent = self.parent_name if not parent: error_msg = "Invalid template name in 'extends' tag: %r." % parent if self.parent_name_expr: error_msg += " Got this from the %r variable." % self.parent_name_expr #TODO nice repr. raise TemplateSyntaxError, error_msg if hasattr(parent, 'render'): return parent # parent is a Template object try: source, origin = find_template_source(parent, self.template_dirs) except TemplateDoesNotExist: raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent else: return get_template_from_string(source, origin, parent) def render(self, context): compiled_parent = self.get_parent(context) parent_is_child = isinstance(compiled_parent.nodelist[0], ExtendsNode) parent_blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)]) for block_node in self.nodelist.get_nodes_by_type(BlockNode): # Check for a BlockNode with this node's name, and replace it if found. try: parent_block = parent_blocks[block_node.name] except KeyError: # This BlockNode wasn't found in the parent template, but the # parent block might be defined in the parent's *parent*, so we # add this BlockNode to the parent's ExtendsNode nodelist, so # it'll be checked when the parent node's render() is called. if parent_is_child: compiled_parent.nodelist[0].nodelist.append(block_node) else: # Keep any existing parents and add a new one. Used by BlockNode. parent_block.parent = block_node.parent parent_block.add_parent(parent_block.nodelist) parent_block.nodelist = block_node.nodelist return compiled_parent.render(context) class ConstantIncludeNode(Node): def __init__(self, template_path): try: t = get_template(template_path) self.template = t except: if settings.TEMPLATE_DEBUG: raise self.template = None def render(self, context): if self.template: return self.template.render(context) else: return '' class IncludeNode(Node): def __init__(self, template_name): self.template_name = template_name def render(self, context): try: template_name = resolve_variable(self.template_name, context) t = get_template(template_name) return t.render(context) except TemplateSyntaxError, e: if settings.TEMPLATE_DEBUG: raise return '' except: return '' # Fail silently for invalid included templates. def do_block(parser, token): """ Define a block that can be overridden by child templates. """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "'%s' tag takes only one argument" % bits[0] block_name = bits[1] # Keep track of the names of BlockNodes found in this template, so we can # check for duplication. try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError, "'%s' tag with name '%s' appears more than once" % (bits[0], block_name) parser.__loaded_blocks.append(block_name) except AttributeError: # parser.__loaded_blocks isn't a list yet parser.__loaded_blocks = [block_name] nodelist = parser.parse(('endblock', 'endblock %s' % block_name)) parser.delete_first_token() return BlockNode(block_name, nodelist) def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent template to extend (if it evaluates to a string,) or as the parent tempate itelf (if it evaluates to a Template object). """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "'%s' takes one argument" % bits[0] parent_name, parent_name_expr = None, None if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: parent_name = bits[1][1:-1] else: parent_name_expr = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[0] return ExtendsNode(nodelist, parent_name, parent_name_expr) def do_include(parser, token): """ Loads a template and renders it with the current context. Example:: {% include "foo/some_include" %} """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0] path = bits[1] if path[0] in ('"', "'") and path[-1] == path[0]: return ConstantIncludeNode(path[1:-1]) return IncludeNode(bits[1]) register.tag('block', do_block) register.tag('extends', do_extends) register.tag('include', do_include)
Python
VERSION = (0, 96.1, None)
Python
from django import http from django.utils.translation import check_for_language, activate, to_locale, get_language from django.utils.text import javascript_quote from django.conf import settings import os import gettext as gettext_module def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the GET parameters. """ lang_code = request.GET.get('language', None) next = request.GET.get('next', None) if not next: next = request.META.get('HTTP_REFERER', None) if not next: next = '/' response = http.HttpResponseRedirect(next) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code else: response.set_cookie('django_language', lang_code) return response NullSource = """ /* gettext identity library */ function gettext(msgid) { return msgid; } function ngettext(singular, plural, count) { return (count == 1) ? singular : plural; } function gettext_noop(msgid) { return msgid; } """ LibHead = """ /* gettext library */ var catalog = new Array(); """ LibFoot = """ function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } """ SimplePlural = """ function pluralidx(count) { return (count == 1) ? 0 : 1; } """ InterPolate = r""" function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/, function(match){return String(obj.shift())}); } } """ def null_javascript_catalog(request, domain=None, packages=None): """ Returns "identity" versions of the JavaScript i18n functions -- i.e., versions that don't actually do anything. """ return http.HttpResponse(NullSource + InterPolate, 'text/javascript') def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ if request.GET: if request.GET.has_key('language'): if check_for_language(request.GET['language']): activate(request.GET['language']) if packages is None: packages = ['django.conf'] if type(packages) in (str, unicode): packages = packages.split('+') packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS] default_locale = to_locale(settings.LANGUAGE_CODE) locale = to_locale(get_language()) t = {} paths = [] # first load all english languages files for defaults for package in packages: p = __import__(package, {}, {}, ['']) path = os.path.join(os.path.dirname(p.__file__), 'locale') paths.append(path) catalog = gettext_module.translation(domain, path, ['en']) t.update(catalog._catalog) # next load the settings.LANGUAGE_CODE translations if it isn't english if default_locale != 'en': for path in paths: try: catalog = gettext_module.translation(domain, path, [default_locale]) except IOError: catalog = None if catalog is not None: t.update(catalog._catalog) # last load the currently selected language, if it isn't identical to the default. if locale != default_locale: for path in paths: try: catalog = gettext_module.translation(domain, path, [locale]) except IOError: catalog = None if catalog is not None: t.update(catalog._catalog) src = [LibHead] plural = None if t.has_key(''): for l in t[''].split('\n'): if l.startswith('Plural-Forms:'): plural = l.split(':',1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1] src.append('function pluralidx(n) {\n return %s;\n}\n' % plural) else: src.append(SimplePlural) csrc = [] pdict = {} for k, v in t.items(): if k == '': continue if type(k) in (str, unicode): csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v))) elif type(k) == tuple: if not pdict.has_key(k[0]): pdict[k[0]] = k[1] else: pdict[k[0]] = max(k[1], pdict[k[0]]) csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v))) else: raise TypeError, k csrc.sort() for k,v in pdict.items(): src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1)))) src.extend(csrc) src.append(LibFoot) src.append(InterPolate) src = ''.join(src) return http.HttpResponse(src, 'text/javascript')
Python
from django.core.exceptions import ObjectDoesNotExist from django.template import Context, RequestContext, loader from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django import http def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: raise http.Http404, "Content type %s object %s doesn't exist" % (content_type_id, object_id) try: absurl = obj.get_absolute_url() except AttributeError: raise http.Http404, "%s objects don't have get_absolute_url() methods" % content_type.name # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith('http://'): return http.HttpResponseRedirect(absurl) object_domain = None # Otherwise, we need to introspect the object's relationships for a # relation to the Site object opts = obj._meta # First, look for an many-to-many relationship to sites for field in opts.many_to_many: if field.rel.to is Site: try: object_domain = getattr(obj, field.name).all()[0].domain except IndexError: pass if object_domain is not None: break # Next look for a many-to-one relationship to site if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domain except Site.DoesNotExist: pass if object_domain is not None: break # Fall back to the current site (if possible) if object_domain is None: try: object_domain = Site.objects.get_current().domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it; otherwise fall back # to whatever get_absolute_url() returned. if object_domain is not None: return http.HttpResponseRedirect('http://%s%s' % (object_domain, absurl)) else: return http.HttpResponseRedirect(absurl) def page_not_found(request, template_name='404.html'): """ Default 404 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ t = loader.get_template(template_name) # You need to create a 404.html template. return http.HttpResponseNotFound(t.render(RequestContext(request, {'request_path': request.path}))) def server_error(request, template_name='500.html'): """ 500 error handler. Templates: `500.html` Context: None """ t = loader.get_template(template_name) # You need to create a 500.html template. return http.HttpResponseServerError(t.render(Context({})))
Python
from django.utils.cache import patch_vary_headers def vary_on_headers(*headers): """ A view decorator that adds the specified headers to the Vary header of the response. Usage: @vary_on_headers('Cookie', 'Accept-language') def index(request): ... Note that the header names are not case-sensitive. """ def decorator(func): def inner_func(*args, **kwargs): response = func(*args, **kwargs) patch_vary_headers(response, headers) return response return inner_func return decorator def vary_on_cookie(func): """ A view decorator that adds "Cookie" to the Vary header of a response. This indicates that a page's contents depends on cookies. Usage: @vary_on_cookie def index(request): ... """ def inner_func(*args, **kwargs): response = func(*args, **kwargs) patch_vary_headers(response, ('Cookie',)) return response return inner_func
Python
""" Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the sites.get_current().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ from django.utils.decorators import decorator_from_middleware from django.utils.cache import patch_cache_control, add_never_cache_headers from django.middleware.cache import CacheMiddleware cache_page = decorator_from_middleware(CacheMiddleware) def cache_control(**kwargs): def _cache_controller(viewfunc): def _cache_controlled(request, *args, **kw): response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return _cache_controlled return _cache_controller def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ def _wrapped_view_func(request, *args, **kwargs): response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return _wrapped_view_func
Python
"Decorator for views that gzips pages if the client supports it." from django.utils.decorators import decorator_from_middleware from django.middleware.gzip import GZipMiddleware gzip_page = decorator_from_middleware(GZipMiddleware)
Python
""" Decorators for views based on HTTP headers. """ from django.utils.decorators import decorator_from_middleware from django.middleware.http import ConditionalGetMiddleware from django.http import HttpResponseNotAllowed conditional_page = decorator_from_middleware(ConditionalGetMiddleware) def require_http_methods(request_method_list): """ Decorator to make a view only accept particular request methods. Usage:: @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... Note that request methods should be in uppercase. """ def decorator(func): def inner(request, *args, **kwargs): if request.method not in request_method_list: return HttpResponseNotAllowed(request_method_list) return func(request, *args, **kwargs) return inner return decorator require_GET = require_http_methods(["GET"]) require_GET.__doc__ = "Decorator to require that a view only accept the GET method." require_POST = require_http_methods(["POST"]) require_POST.__doc__ = "Decorator to require that a view only accept the POST method."
Python
from django.template import loader from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified from django.template import Template, Context, TemplateDoesNotExist import mimetypes import os import posixpath import re import rfc822 import stat import urllib def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index``. """ # Clean up given path to only allow serving files below document_root. path = posixpath.normpath(urllib.unquote(path)) newpath = '' for part in path.split('/'): if not part: # strip empty path components continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # strip '.' amd '..' in path continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404, "Directory indexes are not allowed here." if not os.path.exists(fullpath): raise Http404, '"%s" does not exist' % fullpath # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified() mimetype = mimetypes.guess_type(fullpath)[0] contents = open(fullpath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = rfc822.formatdate(statobj[stat.ST_MTIME]) return response DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>Index of {{ directory|escape }}</title> </head> <body> <h1>Index of {{ directory|escape }}</h1> <ul> {% for f in file_list %} <li><a href="{{ f|urlencode }}">{{ f|escape }}</a></li> {% endfor %} </ul> </body> </html> """ def directory_index(path, fullpath): try: t = loader.get_template('static/directory_index') except TemplateDoesNotExist: t = Template(DEFAULT_DIRECTORY_INDEX_TEMPLATE, name='Default directory index template') files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory' : path + '/', 'file_list' : files, }) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0, size=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking about. """ try: if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) header_mtime = rfc822.mktime_tz(rfc822.parsedate_tz( matches.group(1))) header_len = matches.group(3) if header_len and int(header_len) != size: raise ValueError if mtime > header_mtime: raise ValueError except (AttributeError, ValueError): return True return False
Python
from django.conf import settings from django.template import Template, Context, TemplateDoesNotExist from django.utils.html import escape from django.http import HttpResponseServerError, HttpResponseNotFound import os, re HIDDEN_SETTINGS = re.compile('SECRET|PASSWORD|PROFANITIES_LIST') def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p+1 p = template_source.find('\n', p+1) yield len(template_source) + 1 def get_template_exception_info(exc_type, exc_value, tb): origin, (start, end) = exc_value.source template_source = origin.reload() context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(template_source)): if start >= upto and end <= next: line = num before = escape(template_source[upto:start]) during = escape(template_source[start:end]) after = escape(template_source[end:next]) source_lines.append( (num, escape(template_source[upto:next])) ) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) template_info = { 'message': exc_value.args[0], 'source_lines': source_lines[top:bottom], 'before': before, 'during': during, 'after': after, 'top': top, 'bottom': bottom, 'total': total, 'line': line, 'name': origin.name, } exc_info = hasattr(exc_value, 'exc_info') and exc_value.exc_info or (exc_type, exc_value, tb) return exc_info + (template_info,) def get_safe_settings(): "Returns a dictionary of the settings module, with sensitive settings blurred out." settings_dict = {} for k in dir(settings): if k.isupper(): if HIDDEN_SETTINGS.search(k): settings_dict[k] = '********************' else: settings_dict[k] = getattr(settings, k) return settings_dict def technical_500_response(request, exc_type, exc_value, tb): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ template_info = None template_does_not_exist = False loader_debug_info = None if issubclass(exc_type, TemplateDoesNotExist): from django.template.loader import template_source_loaders template_does_not_exist = True loader_debug_info = [] for loader in template_source_loaders: try: source_list_func = getattr(__import__(loader.__module__, {}, {}, ['get_template_sources']), 'get_template_sources') # NOTE: This assumes exc_value is the name of the template that # the loader attempted to load. template_list = [{'name': t, 'exists': os.path.exists(t)} \ for t in source_list_func(str(exc_value))] except (ImportError, AttributeError): template_list = [] loader_debug_info.append({ 'loader': loader.__module__ + '.' + loader.__name__, 'templates': template_list, }) if settings.TEMPLATE_DEBUG and hasattr(exc_value, 'source'): exc_type, exc_value, tb, template_info = get_template_exception_info(exc_type, exc_value, tb) frames = [] while tb is not None: filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 pre_context_lineno, pre_context, context_line, post_context = _get_lines_from_file(filename, lineno, 7) if pre_context_lineno: frames.append({ 'tb': tb, 'filename': filename, 'function': function, 'lineno': lineno + 1, 'vars': tb.tb_frame.f_locals.items(), 'id': id(tb), 'pre_context': pre_context, 'context_line': context_line, 'post_context': post_context, 'pre_context_lineno': pre_context_lineno + 1, }) tb = tb.tb_next if not frames: frames = [{ 'filename': '&lt;unknown&gt;', 'function': '?', 'lineno': '?', }] t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template') c = Context({ 'exception_type': exc_type.__name__, 'exception_value': exc_value, 'frames': frames, 'lastframe': frames[-1], 'request': request, 'request_protocol': request.is_secure() and "https" or "http", 'settings': get_safe_settings(), 'template_info': template_info, 'template_does_not_exist': template_does_not_exist, 'loader_debug_info': loader_debug_info, }) return HttpResponseServerError(t.render(c), mimetype='text/html') def technical_404_response(request, exception): "Create a technical 404 error response. The exception should be the Http404." try: tried = exception.args[0]['tried'] except (IndexError, TypeError): tried = [] else: if not tried: # tried exists but is an empty list. The URLconf must've been empty. return empty_urlconf(request) t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template') c = Context({ 'root_urlconf': settings.ROOT_URLCONF, 'urlpatterns': tried, 'reason': str(exception), 'request': request, 'request_protocol': request.is_secure() and "https" or "http", 'settings': get_safe_settings(), }) return HttpResponseNotFound(t.render(c), mimetype='text/html') def empty_urlconf(request): "Create an empty URLconf 404 error response." t = Template(EMPTY_URLCONF_TEMPLATE, name='Empty URLConf template') c = Context({ 'project_name': settings.SETTINGS_MODULE.split('.')[0] }) return HttpResponseNotFound(t.render(c), mimetype='text/html') def _get_lines_from_file(filename, lineno, context_lines): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ try: source = open(filename).readlines() lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines pre_context = [line.strip('\n') for line in source[lower_bound:lineno]] context_line = source[lineno].strip('\n') post_context = [line.strip('\n') for line in source[lineno+1:upper_bound]] return lower_bound, pre_context, context_line, post_context except (OSError, IOError): return None, [], None, [] # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. # TECHNICAL_500_TEMPLATE = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>{{ exception_type }} at {{ request.path|escape }}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } table.vars { margin:5px 0 2px 40px; } table.vars td, table.req td { font-family:monospace; } table td.code { width:100%; } table td.code div { overflow:hidden; } table.source th { color:#666; } table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } ul.traceback { list-style-type:none; } ul.traceback li.frame { margin-bottom:1em; } div.context { margin: 10px 0; } div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; } div.context ol li { font-family:monospace; white-space:pre; color:#666; cursor:pointer; } div.context ol.context-line li { color:black; background-color:#ccc; } div.context ol.context-line li span { float: right; } div.commands { margin-left: 40px; } div.commands a { color:black; text-decoration:none; } #summary { background: #ffc; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #template, #template-not-exist { background:#f6f6f6; } #template-not-exist ul { margin: 0 0 0 20px; } #traceback { background:#eee; } #requestinfo { background:#f6f6f6; padding-left:120px; } #summary table { border:none; background:transparent; } #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } #requestinfo h3 { margin-bottom:-1em; } .error { background: #ffc; } .specific { color:#cc3300; font-weight:bold; } </style> <script type="text/javascript"> //<!-- function getElementsByClassName(oElm, strTagName, strClassName){ // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName); var arrReturnElements = new Array(); strClassName = strClassName.replace(/\-/g, "\\-"); var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)"); var oElement; for(var i=0; i<arrElements.length; i++){ oElement = arrElements[i]; if(oRegExp.test(oElement.className)){ arrReturnElements.push(oElement); } } return (arrReturnElements) } function hideAll(elems) { for (var e = 0; e < elems.length; e++) { elems[e].style.display = 'none'; } } window.onload = function() { hideAll(getElementsByClassName(document, 'table', 'vars')); hideAll(getElementsByClassName(document, 'ol', 'pre-context')); hideAll(getElementsByClassName(document, 'ol', 'post-context')); hideAll(getElementsByClassName(document, 'div', 'pastebin')); } function toggle() { for (var i = 0; i < arguments.length; i++) { var e = document.getElementById(arguments[i]); if (e) { e.style.display = e.style.display == 'none' ? 'block' : 'none'; } } return false; } function varToggle(link, id) { toggle('v' + id); var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.innerHTML = s.innerHTML == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to copy-and-paste view"; s2 = "Switch back to interactive view"; link.innerHTML = link.innerHTML == s1 ? s2 : s1; toggle('browserTraceback', 'pastebinTraceback'); return false; } //--> </script> </head> <body> <div id="summary"> <h1>{{ exception_type }} at {{ request.path|escape }}</h1> <h2>{{ exception_value|escape }}</h2> <table class="meta"> <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request_protocol }}://{{ request.META.HTTP_HOST }}{{ request.path|escape }}</td> </tr> <tr> <th>Exception Type:</th> <td>{{ exception_type }}</td> </tr> <tr> <th>Exception Value:</th> <td>{{ exception_value|escape }}</td> </tr> <tr> <th>Exception Location:</th> <td>{{ lastframe.filename }} in {{ lastframe.function }}, line {{ lastframe.lineno }}</td> </tr> </table> </div> {% if template_does_not_exist %} <div id="template-not-exist"> <h2>Template-loader postmortem</h2> {% if loader_debug_info %} <p>Django tried loading these templates, in this order:</p> <ul> {% for loader in loader_debug_info %} <li>Using loader <code>{{ loader.loader }}</code>: <ul>{% for t in loader.templates %}<li><code>{{ t.name }}</code> (File {% if t.exists %}exists{% else %}does not exist{% endif %})</li>{% endfor %}</ul> </li> {% endfor %} </ul> {% else %} <p>Django couldn't find any templates because your <code>TEMPLATE_LOADERS</code> setting is empty!</p> {% endif %} </div> {% endif %} {% if template_info %} <div id="template"> <h2>Template error</h2> <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p> <h3>{{ template_info.message|escape }}</h3> <table class="source{% if template_info.top %} cut-top{% endif %}{% ifnotequal template_info.bottom template_info.total %} cut-bottom{% endifnotequal %}"> {% for source_line in template_info.source_lines %} {% ifequal source_line.0 template_info.line %} <tr class="error"><th>{{ source_line.0 }}</th> <td>{{ template_info.before }}<span class="specific">{{ template_info.during }}</span>{{ template_info.after }}</td></tr> {% else %} <tr><th>{{ source_line.0 }}</th> <td>{{ source_line.1 }}</td></tr> {% endifequal %} {% endfor %} </table> </div> {% endif %} <div id="traceback"> <h2>Traceback <span>(innermost last)</span></h2> <div class="commands"><a href="#" onclick="return switchPastebinFriendly(this);">Switch to copy-and-paste view</a></div> <br/> <div id="browserTraceback"> <ul class="traceback"> {% for frame in frames %} <li class="frame"> <code>{{ frame.filename }}</code> in <code>{{ frame.function }}</code> {% if frame.context_line %} <div class="context" id="c{{ frame.id }}"> {% if frame.pre_context %} <ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}">{% for line in frame.pre_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol> {% endif %} <ol start="{{ frame.lineno }}" class="context-line"><li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ frame.context_line|escape }} <span>...</span></li></ol> {% if frame.post_context %} <ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}">{% for line in frame.post_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol> {% endif %} </div> {% endif %} {% if frame.vars %} <div class="commands"> <a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a> </div> <table class="vars" id="v{{ frame.id }}"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in frame.vars|dictsort:"0" %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> {% endif %} </li> {% endfor %} </ul> </div> <div id="pastebinTraceback" class="pastebin"> <table> <tbody> <tr> <td> <code> Traceback (most recent call last):<br/> {% for frame in frames %} File "{{ frame.filename }}" in {{ frame.function }}<br/> {% if frame.context_line %} &nbsp;&nbsp;{{ frame.lineno }}. {{ frame.context_line|escape }}<br/> {% endif %} {% endfor %}<br/> &nbsp;&nbsp;{{ exception_type }} at {{ request.path|escape }}<br/> &nbsp;&nbsp;{{ exception_value|escape }}</code> </td> </tr> </tbody> </table> </div> </div> <div id="requestinfo"> <h2>Request information</h2> <h3 id="get-info">GET</h3> {% if request.GET %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.GET.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No GET data</p> {% endif %} <h3 id="post-info">POST</h3> {% if request.POST %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.POST.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No POST data</p> {% endif %} <h3 id="cookie-info">COOKIES</h3> {% if request.COOKIES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.COOKIES.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No cookie data</p> {% endif %} <h3 id="meta-info">META</h3> <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.META.items|dictsort:"0" %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> <h3 id="settings-info">Settings</h3> <h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4> <table class="req"> <thead> <tr> <th>Setting</th> <th>Value</th> </tr> </thead> <tbody> {% for var in settings.items|dictsort:"0" %} <tr> <td>{{ var.0 }}</td> <td class="code"><div>{{ var.1|pprint|escape }}</div></td> </tr> {% endfor %} </tbody> </table> </div> <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 500 page. </p> </div> </body> </html> """ TECHNICAL_404_TEMPLATE = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Page not found at {{ request.path|escape }}</title> <meta name="robots" content="NONE,NOARCHIVE" /> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Page not found <span>(404)</span></h1> <table class="meta"> <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request_protocol }}://{{ request.META.HTTP_HOST }}{{ request.path|escape }}</td> </tr> </table> </div> <div id="info"> {% if urlpatterns %} <p> Using the URLconf defined in <code>{{ settings.ROOT_URLCONF }}</code>, Django tried these URL patterns, in this order: </p> <ol> {% for pattern in urlpatterns %} <li>{{ pattern|escape }}</li> {% endfor %} </ol> <p>The current URL, <code>{{ request.path|escape }}</code>, didn't match any of these.</p> {% else %} <p>{{ reason|escape }}</p> {% endif %} </div> <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. </p> </div> </body> </html> """ EMPTY_URLCONF_TEMPLATE = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } ul { margin-left: 2em; margin-top: 1em; } #summary { background: #e0ebff; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #instructions { background:#f6f6f6; } #summary table { border:none; background:transparent; } </style> </head> <body> <div id="summary"> <h1>It worked!</h1> <h2>Congratulations on your first Django-powered page.</h2> </div> <div id="instructions"> <p>Of course, you haven't actually done any work yet. Here's what to do next:</p> <ul> <li>If you plan to use a database, edit the <code>DATABASE_*</code> settings in <code>{{ project_name }}/settings.py</code>.</li> <li>Start your first app by running <code>python {{ project_name }}/manage.py startapp [appname]</code>.</li> </ul> </div> <div id="explanation"> <p> You're seeing this message because you have <code>DEBUG = True</code> in your Django settings file and you haven't configured any URLs. Get to work! </p> </div> </body></html> """
Python
from django.template import loader, RequestContext from django.core.exceptions import ObjectDoesNotExist from django.core.xheaders import populate_xheaders from django.db.models.fields import DateTimeField from django.http import Http404, HttpResponse import datetime, time def archive_index(request, queryset, date_field, num_latest=15, template_name=None, template_loader=loader, extra_context=None, allow_empty=False, context_processors=None, mimetype=None, allow_future=False): """ Generic top-level archive of date-based objects. Templates: ``<app_label>/<model_name>_archive.html`` Context: date_list List of years latest Latest N (defaults to 15) objects by date """ if extra_context is None: extra_context = {} model = queryset.model if not allow_future: queryset = queryset.filter(**{'%s__lte' % date_field: datetime.datetime.now()}) date_list = queryset.dates(date_field, 'year')[::-1] if not date_list and not allow_empty: raise Http404, "No %s available" % model._meta.verbose_name if date_list and num_latest: latest = queryset.order_by('-'+date_field)[:num_latest] else: latest = None if not template_name: template_name = "%s/%s_archive.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'date_list' : date_list, 'latest' : latest, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype) def archive_year(request, year, queryset, date_field, template_name=None, template_loader=loader, extra_context=None, allow_empty=False, context_processors=None, template_object_name='object', mimetype=None, make_object_list=False, allow_future=False): """ Generic yearly archive view. Templates: ``<app_label>/<model_name>_archive_year.html`` Context: date_list List of months in this year with objects year This year object_list List of objects published in the given month (Only available if make_object_list argument is True) """ if extra_context is None: extra_context = {} model = queryset.model now = datetime.datetime.now() lookup_kwargs = {'%s__year' % date_field: year} # Only bother to check current date if the year isn't in the past and future objects aren't requested. if int(year) >= now.year and not allow_future: lookup_kwargs['%s__lte' % date_field] = now date_list = queryset.filter(**lookup_kwargs).dates(date_field, 'month') if not date_list and not allow_empty: raise Http404 if make_object_list: object_list = queryset.filter(**lookup_kwargs).order_by(date_field) else: object_list = [] if not template_name: template_name = "%s/%s_archive_year.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'date_list': date_list, 'year': year, '%s_list' % template_object_name: object_list, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype) def archive_month(request, year, month, queryset, date_field, month_format='%b', template_name=None, template_loader=loader, extra_context=None, allow_empty=False, context_processors=None, template_object_name='object', mimetype=None, allow_future=False): """ Generic monthly archive view. Templates: ``<app_label>/<model_name>_archive_month.html`` Context: month: (date) this month next_month: (date) the first day of the next month, or None if the next month is in the future previous_month: (date) the first day of the previous month object_list: list of objects published in the given month """ if extra_context is None: extra_context = {} try: date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3]) except ValueError: raise Http404 model = queryset.model now = datetime.datetime.now() # Calculate first and last day of month, for use in a date-range lookup. first_day = date.replace(day=1) if first_day.month == 12: last_day = first_day.replace(year=first_day.year + 1, month=1) else: last_day = first_day.replace(month=first_day.month + 1) lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)} # Only bother to check current date if the month isn't in the past and future objects are requested. if last_day >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now object_list = queryset.filter(**lookup_kwargs) if not object_list and not allow_empty: raise Http404 # Calculate the next month, if applicable. if allow_future: next_month = last_day + datetime.timedelta(days=1) elif last_day < datetime.date.today(): next_month = last_day + datetime.timedelta(days=1) else: next_month = None if not template_name: template_name = "%s/%s_archive_month.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'month': date, 'next_month': next_month, 'previous_month': first_day - datetime.timedelta(days=1), }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype) def archive_week(request, year, week, queryset, date_field, template_name=None, template_loader=loader, extra_context=None, allow_empty=True, context_processors=None, template_object_name='object', mimetype=None, allow_future=False): """ Generic weekly archive view. Templates: ``<app_label>/<model_name>_archive_week.html`` Context: week: (date) this week object_list: list of objects published in the given week """ if extra_context is None: extra_context = {} try: date = datetime.date(*time.strptime(year+'-0-'+week, '%Y-%w-%U')[:3]) except ValueError: raise Http404 model = queryset.model now = datetime.datetime.now() # Calculate first and last day of week, for use in a date-range lookup. first_day = date last_day = date + datetime.timedelta(days=7) lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)} # Only bother to check current date if the week isn't in the past and future objects aren't requested. if last_day >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now object_list = queryset.filter(**lookup_kwargs) if not object_list and not allow_empty: raise Http404 if not template_name: template_name = "%s/%s_archive_week.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'week': date, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype) def archive_day(request, year, month, day, queryset, date_field, month_format='%b', day_format='%d', template_name=None, template_loader=loader, extra_context=None, allow_empty=False, context_processors=None, template_object_name='object', mimetype=None, allow_future=False): """ Generic daily archive view. Templates: ``<app_label>/<model_name>_archive_day.html`` Context: object_list: list of objects published that day day: (datetime) the day previous_day (datetime) the previous day next_day (datetime) the next day, or None if the current day is today """ if extra_context is None: extra_context = {} try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except ValueError: raise Http404 model = queryset.model now = datetime.datetime.now() if isinstance(model._meta.get_field(date_field), DateTimeField): lookup_kwargs = {'%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} else: lookup_kwargs = {date_field: date} # Only bother to check current date if the date isn't in the past and future objects aren't requested. if date >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now object_list = queryset.filter(**lookup_kwargs) if not allow_empty and not object_list: raise Http404 # Calculate the next day, if applicable. if allow_future: next_day = date + datetime.timedelta(days=1) elif date < datetime.date.today(): next_day = date + datetime.timedelta(days=1) else: next_day = None if not template_name: template_name = "%s/%s_archive_day.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'day': date, 'previous_day': date - datetime.timedelta(days=1), 'next_day': next_day, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype) def archive_today(request, **kwargs): """ Generic daily archive view for today. Same as archive_day view. """ today = datetime.date.today() kwargs.update({ 'year': str(today.year), 'month': today.strftime('%b').lower(), 'day': str(today.day), }) return archive_day(request, **kwargs) def object_detail(request, year, month, day, queryset, date_field, month_format='%b', day_format='%d', object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None, allow_future=False): """ Generic detail view from year/month/day/slug or year/month/day/id structure. Templates: ``<app_label>/<model_name>_detail.html`` Context: object: the object to be detailed """ if extra_context is None: extra_context = {} try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except ValueError: raise Http404 model = queryset.model now = datetime.datetime.now() if isinstance(model._meta.get_field(date_field), DateTimeField): lookup_kwargs = {'%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} else: lookup_kwargs = {date_field: date} # Only bother to check current date if the date isn't in the past and future objects aren't requested. if date >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now if object_id: lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError, "Generic detail view must be called with either an object_id or a slug/slugfield" try: obj = queryset.get(**lookup_kwargs) except ObjectDoesNotExist: raise Http404, "No %s found for" % model._meta.verbose_name if not template_name: template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response
Python
from django.core.xheaders import populate_xheaders from django.template import loader from django import oldforms from django.db.models import FileField from django.contrib.auth.views import redirect_to_login from django.template import RequestContext from django.http import Http404, HttpResponse, HttpResponseRedirect from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.utils.translation import gettext def create_object(request, model, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, follow=None, context_processors=None): """ Generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form wrapper for the object """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) manipulator = model.AddManipulator(follow=follow) if request.POST: # If data was POSTed, we're trying to create a new object new_data = request.POST.copy() if model._meta.has_field_type(FileField): new_data.update(request.FILES) # Check for errors errors = manipulator.get_validation_errors(new_data) manipulator.do_html2python(new_data) if not errors: # No errors -- this means we can save the data! new_object = manipulator.save(new_data) if request.user.is_authenticated(): request.user.message_set.create(message=gettext("The %(verbose_name)s was created successfully.") % {"verbose_name": model._meta.verbose_name}) # Redirect to the new object: first by trying post_save_redirect, # then by obj.get_absolute_url; fail if neither works. if post_save_redirect: return HttpResponseRedirect(post_save_redirect % new_object.__dict__) elif hasattr(new_object, 'get_absolute_url'): return HttpResponseRedirect(new_object.get_absolute_url()) else: raise ImproperlyConfigured("No URL to redirect to from generic create view.") else: # No POST, so we want a brand new form without any data or errors errors = {} new_data = manipulator.flatten_data() # Create the FormWrapper, template, context, response form = oldforms.FormWrapper(manipulator, new_data, errors) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c)) def update_object(request, model, object_id=None, slug=None, slug_field=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, follow=None, context_processors=None, template_object_name='object'): """ Generic object-update function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form wrapper for the object object the original object being edited """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) # Look up the object to be edited lookup_kwargs = {} if object_id: lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError("Generic edit view must be called with either an object_id or a slug/slug_field") try: object = model.objects.get(**lookup_kwargs) except ObjectDoesNotExist: raise Http404, "No %s found for %s" % (model._meta.verbose_name, lookup_kwargs) manipulator = model.ChangeManipulator(getattr(object, object._meta.pk.attname), follow=follow) if request.POST: new_data = request.POST.copy() if model._meta.has_field_type(FileField): new_data.update(request.FILES) errors = manipulator.get_validation_errors(new_data) manipulator.do_html2python(new_data) if not errors: object = manipulator.save(new_data) if request.user.is_authenticated(): request.user.message_set.create(message=gettext("The %(verbose_name)s was updated successfully.") % {"verbose_name": model._meta.verbose_name}) # Do a post-after-redirect so that reload works, etc. if post_save_redirect: return HttpResponseRedirect(post_save_redirect % object.__dict__) elif hasattr(object, 'get_absolute_url'): return HttpResponseRedirect(object.get_absolute_url()) else: raise ImproperlyConfigured("No URL to redirect to from generic create view.") else: errors = {} # This makes sure the form acurate represents the fields of the place. new_data = manipulator.flatten_data() form = oldforms.FormWrapper(manipulator, new_data, errors) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, template_object_name: object, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(object, object._meta.pk.attname)) return response def delete_object(request, model, post_delete_redirect, object_id=None, slug=None, slug_field=None, template_name=None, template_loader=loader, extra_context=None, login_required=False, context_processors=None, template_object_name='object'): """ Generic object-delete function. The given template will be used to confirm deletetion if this view is fetched using GET; for safty, deletion will only be performed if this view is POSTed. Templates: ``<app_label>/<model_name>_confirm_delete.html`` Context: object the original object being deleted """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) # Look up the object to be edited lookup_kwargs = {} if object_id: lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError("Generic delete view must be called with either an object_id or a slug/slug_field") try: object = model._default_manager.get(**lookup_kwargs) except ObjectDoesNotExist: raise Http404, "No %s found for %s" % (model._meta.app_label, lookup_kwargs) if request.method == 'POST': object.delete() if request.user.is_authenticated(): request.user.message_set.create(message=gettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name}) return HttpResponseRedirect(post_delete_redirect) else: if not template_name: template_name = "%s/%s_confirm_delete.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: object, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(object, object._meta.pk.attname)) return response
Python
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse, HttpResponsePermanentRedirect, HttpResponseGone def direct_to_template(request, template, extra_context={}, **kwargs): """ Render a given template with any extra URL parameters in the context as ``{{ params }}``. """ dictionary = {'params': kwargs} for key, value in extra_context.items(): if callable(value): dictionary[key] = value() else: dictionary[key] = value return render_to_response(template, dictionary, context_instance=RequestContext(request)) def redirect_to(request, url, **kwargs): """ Redirect to a given URL. The given url may contain dict-style string formatting, which will be interpolated against the params in the URL. For example, to redirect from ``/foo/<id>/`` to ``/bar/<id>/``, you could use the following URLconf:: urlpatterns = patterns('', ('^foo/(?P<id>\d+)/$', 'django.views.generic.simple.redirect_to', {'url' : '/bar/%(id)s/'}), ) If the given url is ``None``, a HttpResponseGone (410) will be issued. """ if url is not None: return HttpResponsePermanentRedirect(url % kwargs) else: return HttpResponseGone()
Python
from django.template import loader, RequestContext from django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): """ Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the results paginated? results_per_page number of objects per page (if paginated) has_next is there a next page? has_previous is there a prev page? page the current page next the next page previous the previous page pages number of pages, total hits number of objects, total last_on_page the result number of the last of object in the object_list (1-indexed) first_on_page the result number of the first object in the object_list (1-indexed) """ if extra_context is None: extra_context = {} queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list = [] else: raise Http404 c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors) else: c = RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors) if not allow_empty and len(queryset) == 0: raise Http404 for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value if not template_name: model = queryset.model template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): """ Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object """ if extra_context is None: extra_context = {} model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError, "Generic detail view must be called with either an object_id or a slug/slug_field." try: obj = queryset.get() except ObjectDoesNotExist: raise Http404, "No %s found matching the query" % (model._meta.verbose_name) if not template_name: template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response
Python
from django.template import Node, resolve_variable from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): from django.conf import settings context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES] return '' class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return '' class TranslateNode(Node): def __init__(self, value, noop): self.value = value self.noop = noop def render(self, context): value = resolve_variable(self.value, context) if self.noop: return value else: return translation.gettext(value) class BlockTranslateNode(Node): def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter def render_token_list(self, tokens): result = [] for token in tokens: if token.token_type == TOKEN_TEXT: result.append(token.contents) elif token.token_type == TOKEN_VAR: result.append('%%(%s)s' % token.contents) return ''.join(result) def render(self, context): context.push() for var,val in self.extra_context.items(): context[var] = val.resolve(context) singular = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural = self.render_token_list(self.plural) result = translation.ngettext(singular, plural, count) % context else: result = translation.gettext(singular) % context context.pop() return result def do_get_available_languages(parser, token): """ This will store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This will just pull the LANGUAGES setting from your setting file (or the default settings) and put it into the named variable. """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError, "'get_available_languages' requires 'as variable' (got %r)" % args return GetAvailableLanguagesNode(args[2]) def do_get_current_language(parser, token): """ This will store the current language in the context. Usage:: {% get_current_language as language %} This will fetch the currently active language and put it's value into the ``language`` context variable. """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError, "'get_current_language' requires 'as variable' (got %r)" % args return GetCurrentLanguageNode(args[2]) def do_get_current_language_bidi(parser, token): """ This will store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This will fetch the currently active language's layout and put it's value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError, "'get_current_language_bidi' requires 'as variable' (got %r)" % args return GetCurrentLanguageBidiNode(args[2]) def do_translate(parser, token): """ This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. """ class TranslateParser(TokenParser): def top(self): value = self.value() if self.more(): if self.tag() == 'noop': noop = True else: raise TemplateSyntaxError, "only option for 'trans' is 'noop'" else: noop = False return (value, noop) value, noop = TranslateParser(token.contents).top() return TranslateNode(value, noop) def do_block_translate(parser, token): """ This will translate a block of text with parameters. Usage:: {% blocktrans with foo|filter as bar and baz|filter as boo %} This is {{ bar }} and {{ boo }}. {% endblocktrans %} Additionally, this supports pluralization:: {% blocktrans count var|length as count %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktrans %} This is much like ngettext, only in template syntax. """ class BlockTranslateParser(TokenParser): def top(self): countervar = None counter = None extra_context = {} while self.more(): tag = self.tag() if tag == 'with' or tag == 'and': value = self.value() if self.tag() != 'as': raise TemplateSyntaxError, "variable bindings in 'blocktrans' must be 'with value as variable'" extra_context[self.tag()] = parser.compile_filter(value) elif tag == 'count': counter = parser.compile_filter(self.value()) if self.tag() != 'as': raise TemplateSyntaxError, "counter specification in 'blocktrans' must be 'count value as variable'" countervar = self.tag() else: raise TemplateSyntaxError, "unknown subtag %s for 'blocktrans' found" % tag return (countervar, counter, extra_context) countervar, counter, extra_context = BlockTranslateParser(token.contents).top() singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags inside it" while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents return BlockTranslateNode(extra_context, singular, plural, countervar, counter) register.tag('get_available_languages', do_get_available_languages) register.tag('get_current_language', do_get_current_language) register.tag('get_current_language_bidi', do_get_current_language_bidi) register.tag('trans', do_translate) register.tag('blocktrans', do_block_translate)
Python
from django.conf import settings for a in settings.INSTALLED_APPS: try: __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__) except ImportError: pass
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^$', 'examples.views.index'), (r'^hello/', include('examples.hello.urls')), )
Python
#!/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" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# Django settings for the example project. DEBUG = True TEMPLATE_DEBUG = DEBUG ROOT_URLCONF = 'examples.urls'
Python
from django import http def index(request): r = http.HttpResponse('<h1>Django examples</h1><ul>') r.write('<li><a href="hello/html/">Hello world (HTML)</a></li>') r.write('<li><a href="hello/text/">Hello world (text)</a></li>') r.write('<li><a href="hello/write/">HttpResponse objects are file-like objects</a></li>') r.write('<li><a href="hello/metadata/">Displaying request metadata</a></li>') r.write('<li><a href="hello/getdata/">Displaying GET data</a></li>') r.write('<li><a href="hello/postdata/">Displaying POST data</a></li>') r.write('</ul>') return r
Python
from django.conf.urls.defaults import * urlpatterns = patterns('examples.hello.views', (r'^html/$', 'hello_html'), (r'^text/$', 'hello_text'), (r'^write/$', 'hello_write'), (r'^metadata/$', 'metadata'), (r'^getdata/$', 'get_data'), (r'^postdata/$', 'post_data'), )
Python
from django.http import HttpResponse from django.utils.html import escape def hello_html(request): "This view is a basic 'hello world' example in HTML." return HttpResponse('<h1>Hello, world.</h1>') def hello_text(request): "This view is a basic 'hello world' example in plain text." return HttpResponse('Hello, world.', mimetype='text/plain') def hello_write(request): "This view demonstrates how an HttpResponse object has a write() method." r = HttpResponse() r.write("<p>Here's a paragraph.</p>") r.write("<p>Here's another paragraph.</p>") return r def metadata(request): "This view demonstrates how to retrieve request metadata, such as HTTP headers." r = HttpResponse('<h1>All about you</h1>') r.write("<p>Here's all known metadata about your request, according to <code>request.META</code>:</p>") r.write('<table>') meta_items = request.META.items() meta_items.sort() for k, v in meta_items: r.write('<tr><th>%s</th><td>%r</td></tr>' % (k, v)) r.write('</table>') return r def get_data(request): "This view demonstrates how to retrieve GET data." r = HttpResponse() if request.GET: r.write('<p>GET data found! Here it is:</p>') r.write('<ul>%s</ul>' % ''.join(['<li><strong>%s:</strong> %r</li>' % (escape(k), escape(v)) for k, v in request.GET.items()])) r.write('<form action="" method="get">') r.write('<p>First name: <input type="text" name="first_name"></p>') r.write('<p>Last name: <input type="text" name="last_name"></p>') r.write('<p><input type="submit" value="Submit"></p>') r.write('</form>') return r def post_data(request): "This view demonstrates how to retrieve POST data." r = HttpResponse() if request.POST: r.write('<p>POST data found! Here it is:</p>') r.write('<ul>%s</ul>' % ''.join(['<li><strong>%s:</strong> %r</li>' % (escape(k), escape(v)) for k, v in request.POST.items()])) r.write('<form action="" method="post">') r.write('<p>First name: <input type="text" name="first_name"></p>') r.write('<p>Last name: <input type="text" name="last_name"></p>') r.write('<p><input type="submit" value="Submit"></p>') r.write('</form>') return r
Python
#!/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" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python