diff options
| author | Adrian Holovaty <adrian@holovaty.com> | 2005-07-13 01:25:57 +0000 |
|---|---|---|
| committer | Adrian Holovaty <adrian@holovaty.com> | 2005-07-13 01:25:57 +0000 |
| commit | ed114e15106192b22ebb78ef5bf5bce72b419d13 (patch) | |
| tree | f7c27f035cca8d50bd69e2ecbd7497fccec4a35a /django/models | |
| parent | 07ffc7d605cc96557db28a9e35da69bc0719611b (diff) | |
Imported Django from private SVN repository (created from r. 8825)
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/models')
| -rw-r--r-- | django/models/__init__.py | 91 | ||||
| -rw-r--r-- | django/models/auth.py | 290 | ||||
| -rw-r--r-- | django/models/comments.py | 281 | ||||
| -rw-r--r-- | django/models/core.py | 107 |
4 files changed, 769 insertions, 0 deletions
diff --git a/django/models/__init__.py b/django/models/__init__.py new file mode 100644 index 0000000000..63cedc9af1 --- /dev/null +++ b/django/models/__init__.py @@ -0,0 +1,91 @@ +from django.core import meta
+
+__all__ = ['auth', 'comments', 'core']
+
+# Alter this package's __path__ variable so that calling code can import models
+# from "django.models" even though the model code doesn't physically live
+# within django.models.
+for mod in meta.get_installed_models():
+ __path__.extend(mod.__path__)
+
+# First, import all models so the metaclasses run.
+modules = meta.get_installed_model_modules(__all__)
+
+# Now, create the extra methods that we couldn't create earlier because
+# relationships hadn't been known until now.
+for mod in modules:
+ for klass in mod._MODELS:
+
+ # Add "get_thingie", "get_thingie_count" and "get_thingie_list" methods
+ # for all related objects.
+ for rel_obj, rel_field in klass._meta.get_all_related_objects():
+ # Determine whether this related object is in another app.
+ # If it's in another app, the method names will have the app
+ # label prepended, and the add_BLAH() method will not be
+ # generated.
+ rel_mod = rel_obj.get_model_module()
+ rel_obj_name = klass._meta.get_rel_object_method_name(rel_obj, rel_field)
+ if isinstance(rel_field.rel, meta.OneToOne):
+ # Add "get_thingie" methods for one-to-one related objects.
+ # EXAMPLE: Place.get_restaurants_restaurant()
+ func = meta.curry(meta.method_get_related, 'get_object', rel_mod, rel_field)
+ func.__doc__ = "Returns the associated `%s.%s` object." % (rel_obj.app_label, rel_obj.module_name)
+ setattr(klass, 'get_%s' % rel_obj_name, func)
+ elif isinstance(rel_field.rel, meta.ManyToOne):
+ # Add "get_thingie" methods for many-to-one related objects.
+ # EXAMPLE: Poll.get_choice()
+ func = meta.curry(meta.method_get_related, 'get_object', rel_mod, rel_field)
+ func.__doc__ = "Returns the associated `%s.%s` object matching the given criteria." % (rel_obj.app_label, rel_obj.module_name)
+ setattr(klass, 'get_%s' % rel_obj_name, func)
+ # Add "get_thingie_count" methods for many-to-one related objects.
+ # EXAMPLE: Poll.get_choice_count()
+ func = meta.curry(meta.method_get_related, 'get_count', rel_mod, rel_field)
+ func.__doc__ = "Returns the number of associated `%s.%s` objects." % (rel_obj.app_label, rel_obj.module_name)
+ setattr(klass, 'get_%s_count' % rel_obj_name, func)
+ # Add "get_thingie_list" methods for many-to-one related objects.
+ # EXAMPLE: Poll.get_choice_list()
+ func = meta.curry(meta.method_get_related, 'get_list', rel_mod, rel_field)
+ func.__doc__ = "Returns a list of associated `%s.%s` objects." % (rel_obj.app_label, rel_obj.module_name)
+ setattr(klass, 'get_%s_list' % rel_obj_name, func)
+ # Add "add_thingie" methods for many-to-one related objects,
+ # but only for related objects that are in the same app.
+ # EXAMPLE: Poll.add_choice()
+ if rel_obj.app_label == klass._meta.app_label:
+ func = meta.curry(meta.method_add_related, rel_obj, rel_mod, rel_field)
+ func.alters_data = True
+ setattr(klass, 'add_%s' % rel_obj_name, func)
+ del func
+ del rel_obj_name, rel_mod, rel_obj, rel_field # clean up
+
+ # Do the same for all related many-to-many objects.
+ for rel_opts, rel_field in klass._meta.get_all_related_many_to_many_objects():
+ rel_mod = rel_opts.get_model_module()
+ rel_obj_name = klass._meta.get_rel_object_method_name(rel_opts, rel_field)
+ setattr(klass, 'get_%s' % rel_obj_name, meta.curry(meta.method_get_related_many_to_many, 'get_object', rel_mod, rel_field))
+ setattr(klass, 'get_%s_count' % rel_obj_name, meta.curry(meta.method_get_related_many_to_many, 'get_count', rel_mod, rel_field))
+ setattr(klass, 'get_%s_list' % rel_obj_name, meta.curry(meta.method_get_related_many_to_many, 'get_list', rel_mod, rel_field))
+ if rel_opts.app_label == klass._meta.app_label:
+ func = meta.curry(meta.method_set_related_many_to_many, rel_opts, rel_field)
+ func.alters_data = True
+ setattr(klass, 'set_%s' % rel_opts.module_name, func)
+ del func
+ del rel_obj_name, rel_mod, rel_opts, rel_field # clean up
+
+ # Add "set_thingie_order" and "get_thingie_order" methods for objects
+ # that are ordered with respect to this.
+ for obj in klass._meta.get_ordered_objects():
+ func = meta.curry(meta.method_set_order, obj)
+ func.__doc__ = "Sets the order of associated `%s.%s` objects to the given ID list." % (obj.app_label, obj.module_name)
+ func.alters_data = True
+ setattr(klass, 'set_%s_order' % obj.object_name.lower(), func)
+
+ func = meta.curry(meta.method_get_order, obj)
+ func.__doc__ = "Returns the order of associated `%s.%s` objects as a list of IDs." % (obj.app_label, obj.module_name)
+ setattr(klass, 'get_%s_order' % obj.object_name.lower(), func)
+ del func, obj # clean up
+ del klass # clean up
+ del mod
+del modules
+
+# Expose get_app and get_module.
+from django.core.meta import get_app, get_module
diff --git a/django/models/auth.py b/django/models/auth.py new file mode 100644 index 0000000000..96e6af9667 --- /dev/null +++ b/django/models/auth.py @@ -0,0 +1,290 @@ +from django.core import meta, validators +from django.models import core + +class Permission(meta.Model): + fields = ( + meta.CharField('name', 'name', maxlength=50), + meta.ForeignKey(core.Package, name='package'), + meta.CharField('codename', 'code name', maxlength=100), + ) + unique_together = (('package', 'codename'),) + ordering = (('package', 'ASC'), ('codename', 'ASC')) + + def __repr__(self): + return "%s | %s" % (self.package, self.name) + +class Group(meta.Model): + fields = ( + meta.CharField('name', 'name', maxlength=80, unique=True), + meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL), + ) + ordering = (('name', 'ASC'),) + admin = meta.Admin( + fields = ( + (None, {'fields': ('name', 'permissions')}), + ), + search_fields = ('name',), + ) + + def __repr__(self): + return self.name + +class User(meta.Model): + fields = ( + meta.CharField('username', 'username', maxlength=30, unique=True, + validator_list=[validators.isAlphaNumeric]), + meta.CharField('first_name', 'first name', maxlength=30, blank=True), + meta.CharField('last_name', 'last name', maxlength=30, blank=True), + meta.EmailField('email', 'e-mail address', blank=True), + meta.CharField('password_md5', 'password', maxlength=32), + meta.BooleanField('is_staff', 'staff status', + help_text="Designates whether the user can log into this admin site."), + meta.BooleanField('is_active', 'active', default=True), + meta.BooleanField('is_superuser', 'superuser status'), + meta.DateTimeField('last_login', 'last login', default=meta.LazyDate()), + meta.DateTimeField('date_joined', 'date joined', default=meta.LazyDate()), + meta.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."), + meta.ManyToManyField(Permission, name='user_permissions', blank=True, filter_interface=meta.HORIZONTAL), + ) + ordering = (('username', 'ASC'),) + exceptions = ('SiteProfileNotAvailable',) + admin = meta.Admin( + fields = ( + (None, {'fields': ('username', 'password_md5')}), + ('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 __repr__(self): + return self.username + + def get_absolute_url(self): + return "/users/%s/" % self.username + + def is_anonymous(self): + return False + + def get_full_name(self): + full_name = '%s %s' % (self.first_name, self.last_name) + return full_name.strip() + + def set_password(self, raw_password): + import md5 + self.password_md5 = md5.new(raw_password).hexdigest() + + def check_password(self, raw_password): + "Returns a boolean of whether the raw_password was correct." + import md5 + return self.password_md5 == md5.new(raw_password).hexdigest() + + 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 = db.cursor() + cursor.execute(""" + SELECT p.package, p.codename + FROM auth_permissions p, auth_groups_permissions gp, auth_users_groups ug + WHERE p.id = gp.permission_id + AND gp.group_id = ug.group_id + AND ug.user_id = %s""", [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.package, p.codename) for p in self.get_user_permissions()]) + 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, package_name): + "Returns True if the user has any permissions in the given package." + if self.is_superuser: + return True + return bool(len([p for p in self.get_all_permissions() if p[:p.index('.')] == package_name])) + + def get_and_delete_messages(self): + messages = [] + for m in self.get_message_list(): + 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.settings import AUTH_PROFILE_MODULE + if not AUTH_PROFILE_MODULE: + raise SiteProfileNotAvailable + try: + app, mod = AUTH_PROFILE_MODULE.split('.') + module = __import__('ellington.%s.apps.%s' % (app, mod), [], [], ['']) + self._profile_cache = module.get_object(user_id=self.id) + except ImportError: + try: + module = __import__('django.models.%s' % AUTH_PROFILE_MODULE, [], [], ['']) + self._profile_cache = module.get_object(user_id__exact=self.id) + except ImportError: + 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." + import md5 + password_md5 = md5.new(password).hexdigest() + now = datetime.datetime.now() + user = User(None, username, '', '', email.strip().lower(), password_md5, False, True, False, now, now) + 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 whrandom import choice + return ''.join([choice(allowed_chars) for i in range(length)]) + +class Session(meta.Model): + fields = ( + meta.ForeignKey(User), + meta.CharField('session_md5', 'session MD5 hash', maxlength=32), + meta.DateTimeField('start_time', 'start time', auto_now=True), + ) + module_constants = { + # Used for providing pseudo-entropy in creating random session strings. + 'SESSION_SALT': 'ijw2f3_MUPPET_avo#*5)(*', + # Secret used in cookie to guard against cookie tampering. + 'TAMPER_SECRET': 'lj908_PIGGY_j0vajeawej-092j3f', + 'TEST_COOKIE_NAME': 'testcookie', + 'TEST_COOKIE_VALUE': 'worked', + } + + def __repr__(self): + return "session started at %s" % self.start_time + + def get_cookie(self): + "Returns a tuple of the cookie name and value for this session." + import md5 + from django.conf.settings import AUTH_SESSION_COOKIE + return AUTH_SESSION_COOKIE, self.session_md5 + md5.new(self.session_md5 + TAMPER_SECRET).hexdigest() + + def _module_create_session(user_id): + "Registers a session and returns the session_md5." + import md5, random, sys + # The random module is seeded when this Apache child is created. + # Use person_id and SESSION_SALT as added salt. + session_md5 = md5.new(str(random.randint(user_id, sys.maxint - 1)) + SESSION_SALT).hexdigest() + s = Session(None, user_id, session_md5, None) + s.save() + return s + + def _module_get_session_from_cookie(session_cookie_string): + import md5 + if not session_cookie_string: + raise SessionDoesNotExist + session_md5, tamper_check = session_cookie_string[:32], session_cookie_string[32:] + if md5.new(session_md5 + TAMPER_SECRET).hexdigest() != tamper_check: + raise SuspiciousOperation, "User may have tampered with session cookie." + return get_object(session_md5__exact=session_md5, select_related=True) + + def _module_destroy_all_sessions(user_id): + "Destroys all sessions for a user, logging out all computers." + for session in get_list(user_id__exact=user_id): + session.delete() + + def _module_start_web_session(user_id, request, response): + "Sets the necessary cookie in the given HttpResponse object, also updates last login time for user." + from django.models.auth import users + from django.conf.settings import REGISTRATION_COOKIE_DOMAIN + user = users.get_object(id__exact=user_id) + user.last_login = datetime.datetime.now() + user.save() + session = create_session(user_id) + key, value = session.get_cookie() + cookie_domain = REGISTRATION_COOKIE_DOMAIN or request.META['SERVER_NAME'] + response.set_cookie(key, value, domain=cookie_domain) + +class Message(meta.Model): + fields = ( + meta.AutoField('id', 'ID', primary_key=True), + meta.ForeignKey(User), + meta.TextField('message', 'message'), + ) + + def __repr__(self): + return self.message + +class LogEntry(meta.Model): + module_name = 'log' + verbose_name_plural = 'log entries' + db_table = 'auth_admin_log' + fields = ( + meta.DateTimeField('action_time', 'action time', auto_now=True), + meta.ForeignKey(User), + meta.ForeignKey(core.ContentType, name='content_type_id', rel_name='content_type', blank=True, null=True), + meta.IntegerField('object_id', 'object ID', blank=True, null=True), + meta.CharField('object_repr', 'object representation', maxlength=200), + meta.PositiveSmallIntegerField('action_flag', 'action flag'), + meta.TextField('change_message', 'change message', blank=True), + ) + ordering = (('action_time', 'DESC'),) + module_constants = { + 'ADDITION': 1, + 'CHANGE': 2, + 'DELETION': 3, + } + + 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.get_content_type().get_object_for_this_type(id__exact=self.object_id) + + def get_admin_url(self): + "Returns the admin URL to edit the object represented by this log entry" + return "/%s/%s/%s/" % (self.get_content_type().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() diff --git a/django/models/comments.py b/django/models/comments.py new file mode 100644 index 0000000000..0d610c965c --- /dev/null +++ b/django/models/comments.py @@ -0,0 +1,281 @@ +from django.core import meta +from django.models import auth, core + +class Comment(meta.Model): + db_table = 'comments' + fields = ( + meta.ForeignKey(auth.User, raw_id_admin=True), + meta.ForeignKey(core.ContentType, name='content_type_id', rel_name='content_type'), + meta.IntegerField('object_id', 'object ID'), + meta.CharField('headline', 'headline', maxlength=255, blank=True), + meta.TextField('comment', 'comment', maxlength=3000), + meta.PositiveSmallIntegerField('rating1', 'rating #1', blank=True, null=True), + meta.PositiveSmallIntegerField('rating2', 'rating #2', blank=True, null=True), + meta.PositiveSmallIntegerField('rating3', 'rating #3', blank=True, null=True), + meta.PositiveSmallIntegerField('rating4', 'rating #4', blank=True, null=True), + meta.PositiveSmallIntegerField('rating5', 'rating #5', blank=True, null=True), + meta.PositiveSmallIntegerField('rating6', 'rating #6', blank=True, null=True), + meta.PositiveSmallIntegerField('rating7', 'rating #7', blank=True, null=True), + meta.PositiveSmallIntegerField('rating8', '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 review on the same thing, but the system + # will only use the latest one (with valid_rating=True) in tallying + # the reviews. + meta.BooleanField('valid_rating', 'is valid rating'), + meta.DateTimeField('submit_date', 'date/time submitted', auto_now_add=True), + meta.BooleanField('is_public', 'is public'), + meta.IPAddressField('ip_address', 'IP address', blank=True, null=True), + meta.BooleanField('is_removed', 'is removed', + help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.'), + meta.ForeignKey(core.Site), + ) + module_constants = { + # used as shared secret between comment form and comment-posting script + 'COMMENT_SALT': 'ijw2f3_MRS_PIGGY_LOVES_KERMIT_avo#*5vv0(23j)(*', + + # min. and max. allowed dimensions for photo resizing (in pixels) + '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', + } + ordering = (('submit_date', 'DESC'),) + admin = meta.Admin( + fields = ( + (None, {'fields': ('content_type_id', 'object_id', 'site_id')}), + ('Content', {'fields': ('user_id', '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_id', 'submit_date', 'content_type_id', 'get_content_object'), + list_filter = ('submit_date',), + date_hierarchy = 'submit_date', + search_fields = ('comment', 'user__username'), + ) + + def __repr__(self): + return "%s: %s..." % (self.get_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.get_content_type().get_object_for_this_type(id__exact=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.get_karmascore_list(): + 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 %s at %s\n\n%s\n\nhttp://%s%s' % \ + (self.get_user().username, self.submit_date, + self.comment, self.get_site().domain, self.get_absolute_url()) + + def _module_get_security_hash(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 + COMMENT_SALT).hexdigest() + + def _module_get_rating_options(rating_string): + """ + Given a rating_string, this returns a tuple of (rating_range, options). + >>> s = "scale:1-10|First_category|Second_category" + >>> 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 _module_get_list_with_karma(**kwargs): + """ + Returns a list of Comment objects matching the given lookup terms, with + _karma_total_good and _karma_total_bad filled. + """ + kwargs.setdefault('select', {}) + kwargs['select']['_karma_total_good'] = 'SELECT COUNT(*) FROM comments_karma WHERE comments_karma.comment_id=comments.id AND score=1' + kwargs['select']['_karma_total_bad'] = 'SELECT COUNT(*) FROM comments_karma WHERE comments_karma.comment_id=comments.id AND score=-1' + return get_list(**kwargs) + + def _module_user_is_moderator(user): + from django.conf.settings import COMMENTS_MODERATORS_GROUP + if user.is_superuser: + return True + for g in user.get_groups(): + if g.id == COMMENTS_MODERATORS_GROUP: + return True + return False + +class FreeComment(meta.Model): + "A FreeComment is a comment by a non-registered user" + db_table = 'comments_free' + fields = ( + meta.ForeignKey(core.ContentType, name='content_type_id', rel_name='content_type'), + meta.IntegerField('object_id', 'object ID'), + meta.TextField('comment', 'comment', maxlength=3000), + meta.CharField('person_name', "person's name", maxlength=50), + meta.DateTimeField('submit_date', 'date/time submitted', auto_now_add=True), + meta.BooleanField('is_public', 'is public'), + meta.IPAddressField('ip_address', 'IP address'), + # TODO: Change this to is_removed, like Comment + meta.BooleanField('approved', 'approved by staff'), + meta.ForeignKey(core.Site), + ) + ordering = (('submit_date', 'DESC'),) + admin = meta.Admin( + fields = ( + (None, {'fields': ('content_type_id', 'object_id', 'site_id')}), + ('Content', {'fields': ('person_name', 'comment')}), + ('Meta', {'fields': ('submit_date', 'is_public', 'ip_address', 'approved')}), + ), + list_display = ('person_name', 'submit_date', 'content_type_id', '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_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.get_content_type().get_object_for_this_type(id__exact=self.object_id) + except ObjectDoesNotExist: + return None + + get_content_object.short_description = 'Content object' + +class KarmaScore(meta.Model): + module_name = 'karma' + fields = ( + meta.ForeignKey(auth.User), + meta.ForeignKey(Comment), + meta.SmallIntegerField('score', 'score', db_index=True), + meta.DateTimeField('scored_date', 'date scored', auto_now=True), + ) + unique_together = (('user_id', 'comment_id'),) + module_constants = { + # what users get if they don't have any karma + 'DEFAULT_KARMA': 5, + 'KARMA_NEEDED_BEFORE_DISPLAYED': 3, + } + + def __repr__(self): + return "%d rating by %s" % (self.score, self.get_user()) + + def _module_vote(user_id, comment_id, score): + try: + karma = get_object(comment_id__exact=comment_id, user_id__exact=user_id) + except KarmaScoreDoesNotExist: + karma = KarmaScore(None, user_id, comment_id, score, datetime.datetime.now()) + karma.save() + else: + karma.score = score + karma.scored_date = datetime.datetime.now() + karma.save() + + def _module_get_pretty_score(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 UserFlag(meta.Model): + db_table = 'comments_user_flags' + fields = ( + meta.ForeignKey(auth.User), + meta.ForeignKey(Comment), + meta.DateTimeField('flag_date', 'date flagged', auto_now_add=True), + ) + unique_together = (('user_id', 'comment_id'),) + + def __repr__(self): + return "Flag by %r" % self.get_user() + + def _module_flag(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 = get_object(user_id__exact=user.id, comment_id__exact=comment.id) + except UserFlagDoesNotExist: + from django.core.mail import mail_managers + f = UserFlag(None, user.id, comment.id, None) + message = 'This comment was flagged by %s:\n\n%s' % (user.username, comment.get_as_text()) + mail_managers('Comment flagged', message, fail_silently=True) + f.save() + +class ModeratorDeletion(meta.Model): + db_table = 'comments_moderator_deletions' + fields = ( + meta.ForeignKey(auth.User, verbose_name='moderator'), + meta.ForeignKey(Comment), + meta.DateTimeField('deletion_date', 'date deleted', auto_now_add=True), + ) + unique_together = (('user_id', 'comment_id'),) + + def __repr__(self): + return "Moderator deletion by %r" % self.get_user() diff --git a/django/models/core.py b/django/models/core.py new file mode 100644 index 0000000000..4416f22b76 --- /dev/null +++ b/django/models/core.py @@ -0,0 +1,107 @@ +from django.core import meta, validators + +class Site(meta.Model): + db_table = 'sites' + fields = ( + meta.CharField('domain', 'domain name', maxlength=100), + meta.CharField('name', 'display name', maxlength=50), + ) + ordering = (('domain', 'ASC'),) + + 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(id__exact=SITE_ID) + +class Package(meta.Model): + db_table = 'packages' + fields = ( + meta.CharField('label', 'label', maxlength=20, primary_key=True), + meta.CharField('name', 'name', maxlength=30, unique=True), + ) + ordering = (('name', 'ASC'),) + + def __repr__(self): + return self.name + +class ContentType(meta.Model): + db_table = 'content_types' + fields = ( + meta.CharField('name', 'name', maxlength=100), + meta.ForeignKey(Package, name='package'), + meta.CharField('python_module_name', 'Python module name', maxlength=50), + ) + ordering = (('package', 'ASC'), ('name', 'ASC'),) + unique_together = (('package', 'python_module_name'),) + + def __repr__(self): + return "%s | %s" % (self.package, self.name) + + def get_model_module(self): + "Returns the Python model module for accessing this type of content." + return __import__('django.models.%s.%s' % (self.package, self.python_module_name), '', '', ['']) + + 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.get_model_module().get_object(**kwargs) + +class Redirect(meta.Model): + db_table = 'redirects' + fields = ( + meta.ForeignKey(Site, radio_admin=meta.VERTICAL), + meta.CharField('old_path', 'redirect from', maxlength=200, db_index=True, + help_text="This should be an absolute path, excluding the domain name. Example: '/events/search/'."), + meta.CharField('new_path', 'redirect to', maxlength=200, blank=True, + help_text="This can be either an absolute path (as above) or a full URL starting with 'http://'."), + ) + unique_together=(('site_id', 'old_path'),) + ordering = (('old_path', 'ASC'),) + admin = meta.Admin( + fields = ( + (None, {'fields': ('site_id', 'old_path', 'new_path')}), + ), + list_display = ('__repr__',), + list_filter = ('site_id',), + search_fields = ('old_path', 'new_path'), + ) + + def __repr__(self): + return "%s ---> %s" % (self.old_path, self.new_path) + +class FlatFile(meta.Model): + db_table = 'flatfiles' + fields = ( + meta.CharField('url', 'URL', maxlength=100, validator_list=[validators.isAlphaNumericURL], + help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes."), + meta.CharField('title', 'title', maxlength=200), + meta.TextField('content', 'content', help_text="Full HTML is allowed."), + meta.BooleanField('enable_comments', 'enable comments'), + meta.CharField('template_name', 'template name', maxlength=70, blank=True, + help_text="Example: 'flatfiles/contact_page'. If this isn't provided, the system will use 'flatfiles/default'."), + meta.BooleanField('registration_required', 'registration required', + help_text="If this is checked, only logged-in users will be able to view the page."), + meta.ManyToManyField(Site), + ) + ordering = (('url', 'ASC'),) + admin = meta.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 __repr__(self): + return "%s -- %s" % (self.url, self.title) + + def get_absolute_url(self): + return self.url |
