magic-removal: Converted core and contrib models to use managers, and fixed some API code in django.middleware.sessions and django.contrib.admin.views.main
git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@1648 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
e18d87f84e
commit
47a0ec00f2
|
@ -2,6 +2,15 @@ from django.db import models
|
|||
from django.models import auth, core
|
||||
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.klass(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(auth.User)
|
||||
|
@ -10,16 +19,12 @@ class LogEntry(models.Model):
|
|||
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',)
|
||||
module_constants = {
|
||||
'ADDITION': 1,
|
||||
'CHANGE': 2,
|
||||
'DELETION': 3,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return str(self.action_time)
|
||||
|
@ -43,7 +48,3 @@ class LogEntry(models.Model):
|
|||
This is relative to the Django admin index page.
|
||||
"""
|
||||
return "%s/%s/%s/" % (self.get_content_type().get_package(), self.get_content_type().python_module_name, self.object_id)
|
||||
|
||||
def _module_log_action(user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
|
||||
e = LogEntry(None, None, user_id, content_type_id, object_id, object_repr[:200], action_flag, change_message)
|
||||
e.save()
|
||||
|
|
|
@ -10,7 +10,7 @@ from django.core.extensions import get_object_or_404, render_to_response
|
|||
from django.core.paginator import ObjectPaginator, InvalidPage
|
||||
from django.conf.settings import ADMIN_MEDIA_PREFIX
|
||||
try:
|
||||
from django.models.admin import log
|
||||
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
|
||||
except ImportError:
|
||||
raise ImproperlyConfigured, "You don't have 'django.contrib.admin' in INSTALLED_APPS."
|
||||
from django.db import models
|
||||
|
@ -391,7 +391,7 @@ def render_change_form(opts, manipulator, app_label, context, add=False, change=
|
|||
|
||||
def log_add_message(user, opts,manipulator,new_object):
|
||||
pk_value = getattr(new_object, opts.pk.attname)
|
||||
log.log_action(user.id, opts.get_content_type_id(), pk_value, str(new_object), log.ADDITION)
|
||||
LogEntry.objects.log_action(user.id, opts.get_content_type_id(), pk_value, str(new_object), ADDITION)
|
||||
|
||||
def add_stage(request, app_label, module_name, show_delete=False, form_url='', post_url='../', post_url_continue='../%s/', object_id_override=None):
|
||||
mod, opts = _get_mod_opts(app_label, module_name)
|
||||
|
@ -462,7 +462,7 @@ def log_change_message(user, opts,manipulator,new_object):
|
|||
change_message = ' '.join(change_message)
|
||||
if not change_message:
|
||||
change_message = _('No fields changed.')
|
||||
log.log_action(user.id, opts.get_content_type_id(), pk_value, str(new_object), log.CHANGE, change_message)
|
||||
LogEntry.objects.log_action(user.id, opts.get_content_type_id(), pk_value, str(new_object), CHANGE, change_message)
|
||||
|
||||
def change_stage(request, app_label, module_name, object_id):
|
||||
mod, opts = _get_mod_opts(app_label, module_name)
|
||||
|
@ -644,7 +644,7 @@ def delete_stage(request, app_label, module_name, object_id):
|
|||
raise PermissionDenied
|
||||
obj_display = str(obj)
|
||||
obj.delete()
|
||||
log.log_action(request.user.id, opts.get_content_type_id(), object_id, obj_display, log.DELETION)
|
||||
LogEntry.objects.log_action(request.user.id, opts.get_content_type_id(), object_id, obj_display, DELETION)
|
||||
request.user.add_message(_('The %(name)s "%(obj)s" was deleted successfully.') % {'name':opts.verbose_name, 'obj':obj_display})
|
||||
return HttpResponseRedirect("../../")
|
||||
return render_to_response('admin/delete_confirmation', {
|
||||
|
@ -658,7 +658,7 @@ delete_stage = staff_member_required(delete_stage)
|
|||
|
||||
def history(request, app_label, module_name, object_id):
|
||||
mod, opts = _get_mod_opts(app_label, module_name)
|
||||
action_list = log.get_list(object_id__exact=object_id, content_type__id__exact=opts.get_content_type_id(),
|
||||
action_list = LogEntry.objects.get_list(object_id__exact=object_id, content_type__id__exact=opts.get_content_type_id(),
|
||||
order_by=("action_time",), select_related=True)
|
||||
# If no history was found, see whether this object even exists.
|
||||
obj = get_object_or_404(mod, pk=object_id)
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
from django.conf.settings import SESSION_COOKIE_NAME, SESSION_COOKIE_AGE, SESSION_COOKIE_DOMAIN, SESSION_SAVE_EVERY_REQUEST
|
||||
from django.models.core import sessions
|
||||
from django.models.core import Session
|
||||
from django.utils.cache import patch_vary_headers
|
||||
import datetime
|
||||
|
||||
|
@ -43,10 +43,10 @@ class SessionWrapper(object):
|
|||
self._session_cache = {}
|
||||
else:
|
||||
try:
|
||||
s = sessions.get_object(session_key__exact=self.session_key,
|
||||
s = Session.objects.get_object(session_key__exact=self.session_key,
|
||||
expire_date__gt=datetime.datetime.now())
|
||||
self._session_cache = s.get_decoded()
|
||||
except sessions.SessionDoesNotExist:
|
||||
except Session.DoesNotExist:
|
||||
self._session_cache = {}
|
||||
# Set the session_key to None to force creation of a new
|
||||
# key, for extra security.
|
||||
|
@ -68,8 +68,8 @@ class SessionMiddleware:
|
|||
except AttributeError:
|
||||
modified = False
|
||||
if modified or SESSION_SAVE_EVERY_REQUEST:
|
||||
session_key = request.session.session_key or sessions.get_new_session_key()
|
||||
new_session = sessions.save(session_key, request.session._session,
|
||||
session_key = request.session.session_key or Session.objects.get_new_session_key()
|
||||
new_session = Session.objects.save(session_key, request.session._session,
|
||||
datetime.datetime.now() + datetime.timedelta(seconds=SESSION_COOKIE_AGE))
|
||||
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
|
||||
response.set_cookie(SESSION_COOKIE_NAME, session_key,
|
||||
|
|
|
@ -32,6 +32,22 @@ class Group(models.Model):
|
|||
def __repr__(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.klass(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):
|
||||
username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric])
|
||||
first_name = models.CharField(_('first name'), maxlength=30, blank=True)
|
||||
|
@ -46,6 +62,7 @@ class User(models.Model):
|
|||
groups = models.ManyToManyField(Group, 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, blank=True, filter_interface=models.HORIZONTAL)
|
||||
objects = UserManager()
|
||||
class META:
|
||||
verbose_name = _('User')
|
||||
verbose_name_plural = _('Users')
|
||||
|
@ -196,21 +213,6 @@ class User(models.Model):
|
|||
raise SiteProfileNotAvailable
|
||||
return self._profile_cache
|
||||
|
||||
def _module_create_user(username, email, password):
|
||||
"Creates and saves a User with the given username, e-mail and password."
|
||||
now = datetime.datetime.now()
|
||||
user = User(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
|
||||
user.set_password(password)
|
||||
user.save()
|
||||
return user
|
||||
|
||||
def _module_make_random_password(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 Message(models.Model):
|
||||
user = models.ForeignKey(User)
|
||||
message = models.TextField(_('Message'))
|
||||
|
|
|
@ -3,9 +3,15 @@ import cPickle as pickle
|
|||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
class SiteManager(models.Manager):
|
||||
def get_current(self):
|
||||
from django.conf.settings import SITE_ID
|
||||
return self.get_object(pk=SITE_ID)
|
||||
|
||||
class Site(models.Model):
|
||||
domain = models.CharField(_('domain name'), maxlength=100)
|
||||
name = models.CharField(_('display name'), maxlength=50)
|
||||
objects = SiteManager()
|
||||
class META:
|
||||
verbose_name = _('site')
|
||||
verbose_name_plural = _('sites')
|
||||
|
@ -19,11 +25,6 @@ class Site(models.Model):
|
|||
def __repr__(self):
|
||||
return self.domain
|
||||
|
||||
def _module_get_current():
|
||||
"Returns the current site, according to the SITE_ID constant."
|
||||
from django.conf.settings import SITE_ID
|
||||
return get_object(pk=SITE_ID)
|
||||
|
||||
class Package(models.Model):
|
||||
label = models.CharField(_('label'), maxlength=20, primary_key=True)
|
||||
name = models.CharField(_('name'), maxlength=30, unique=True)
|
||||
|
@ -63,10 +64,40 @@ class ContentType(models.Model):
|
|||
"""
|
||||
return self.get_model_module().get_object(**kwargs)
|
||||
|
||||
class SessionManager(models.Manager):
|
||||
def encode(self, session_dict):
|
||||
"Returns the given session dictionary pickled and encoded as a string."
|
||||
from django.conf.settings import SECRET_KEY
|
||||
pickled = pickle.dumps(session_dict)
|
||||
pickled_md5 = md5.new(pickled + SECRET_KEY).hexdigest()
|
||||
return base64.encodestring(pickled + pickled_md5)
|
||||
|
||||
def get_new_session_key(self):
|
||||
"Returns session key that isn't being used."
|
||||
from django.conf.settings import SECRET_KEY
|
||||
# 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)) + SECRET_KEY).hexdigest()
|
||||
try:
|
||||
self.get_object(session_key__exact=session_key)
|
||||
except SessionDoesNotExist:
|
||||
break
|
||||
return session_key
|
||||
|
||||
def save(self, session_key, session_dict, expire_date):
|
||||
s = self.klass(session_key, encode(session_dict), expire_date)
|
||||
if session_dict:
|
||||
s.save()
|
||||
else:
|
||||
s.delete() # Clear sessions with no data.
|
||||
return s
|
||||
|
||||
class Session(models.Model):
|
||||
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:
|
||||
verbose_name = _('session')
|
||||
verbose_name_plural = _('sessions')
|
||||
|
@ -91,31 +122,3 @@ class Session(models.Model):
|
|||
# just return an empty dictionary (an empty session).
|
||||
except:
|
||||
return {}
|
||||
|
||||
def _module_encode(session_dict):
|
||||
"Returns the given session dictionary pickled and encoded as a string."
|
||||
from django.conf.settings import SECRET_KEY
|
||||
pickled = pickle.dumps(session_dict)
|
||||
pickled_md5 = md5.new(pickled + SECRET_KEY).hexdigest()
|
||||
return base64.encodestring(pickled + pickled_md5)
|
||||
|
||||
def _module_get_new_session_key():
|
||||
"Returns session key that isn't being used."
|
||||
from django.conf.settings import SECRET_KEY
|
||||
# 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)) + SECRET_KEY).hexdigest()
|
||||
try:
|
||||
get_object(session_key__exact=session_key)
|
||||
except SessionDoesNotExist:
|
||||
break
|
||||
return session_key
|
||||
|
||||
def _module_save(session_key, session_dict, expire_date):
|
||||
s = Session(session_key, encode(session_dict), expire_date)
|
||||
if session_dict:
|
||||
s.save()
|
||||
else:
|
||||
s.delete() # Clear sessions with no data.
|
||||
return s
|
||||
|
|
Loading…
Reference in New Issue