diff --git a/django/contrib/admin/views/doc.py b/django/contrib/admin/views/doc.py index a68da7d2c9..ee52078187 100644 --- a/django/contrib/admin/views/doc.py +++ b/django/contrib/admin/views/doc.py @@ -6,7 +6,7 @@ from django.core.extensions import DjangoContext, render_to_response from django.core.exceptions import Http404, ViewDoesNotExist from django.core import template, urlresolvers from django.contrib.admin import utils -from django.models.core import sites +from django.models.core import Site import inspect, os, re # Exclude methods starting with these strings from documentation @@ -101,7 +101,7 @@ def view_index(request): 'name': func.__name__, 'module': func.__module__, 'site_id': settings_mod.SITE_ID, - 'site': sites.get_object(pk=settings_mod.SITE_ID), + 'site': Site.objects.get_object(pk=settings_mod.SITE_ID), 'url': simplify_regex(regex), }) return render_to_response('admin_doc/view_index', {'views': views}, context_instance=DjangoContext(request)) @@ -200,7 +200,7 @@ def template_detail(request, template): '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': sites.get_object(pk=settings_mod.SITE_ID), + 'site': Site.objects.get_object(pk=settings_mod.SITE_ID), 'order': list(settings_mod.TEMPLATE_DIRS).index(dir), }) return render_to_response('admin_doc/template_detail', { diff --git a/django/contrib/auth/handlers/modpython.py b/django/contrib/auth/handlers/modpython.py index a29051b4a3..5e5aac4183 100644 --- a/django/contrib/auth/handlers/modpython.py +++ b/django/contrib/auth/handlers/modpython.py @@ -10,7 +10,7 @@ def authenhandler(req, **kwargs): # that so that the following import works os.environ.update(req.subprocess_env) - from django.models.auth import users + from django.models.auth import User # check for PythonOptions _str_to_bool = lambda s: s.lower() in '1', 'true', 'on', 'yes' @@ -27,8 +27,8 @@ def authenhandler(req, **kwargs): if superuser_only: kwargs['is_superuser__exact'] = True try: - user = users.get_object(**kwargs) - except users.UserDoesNotExist: + user = User.objects.get_object(**kwargs) + except User.DoesNotExist: return apache.HTTP_UNAUTHORIZED # check the password and any permission given diff --git a/django/contrib/comments/feeds.py b/django/contrib/comments/feeds.py index dd6c6ecf15..e402d02cc6 100644 --- a/django/contrib/comments/feeds.py +++ b/django/contrib/comments/feeds.py @@ -1,48 +1,48 @@ from django.conf import settings +from django.contrib.comments.models import Comment, FreeComment from django.contrib.syndication.feeds import Feed from django.core.exceptions import ObjectDoesNotExist -from django.models.core import sites -from django.models.comments import comments, freecomments +from django.models.core import Site class LatestFreeCommentsFeed(Feed): """Feed of latest comments on the current site""" - - comments_module = freecomments - + + comments_class = FreeComment + def title(self): if not hasattr(self, '_site'): - self._site = sites.get_current() + self._site = Site.objects.get_current() return "%s comments" % self._site.name - + def link(self): if not hasattr(self, '_site'): - self._site = sites.get_current() + self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) - + def description(self): if not hasattr(self, '_site'): - self._site = sites.get_current() + self._site = Site.objects.get_current() return "Latest comments on %s" % self._site.name def items(self): - return self.comments_module.get_list(**self._get_lookup_kwargs()) + return self.comments_class.objects.get_list(**self._get_lookup_kwargs()) def _get_lookup_kwargs(self): return { - 'site__pk' : settings.SITE_ID, - 'is_public__exact' : True, - 'limit' : 40, + 'site__pk': settings.SITE_ID, + 'is_public__exact': True, + 'limit': 40, } class LatestCommentsFeed(LatestFreeCommentsFeed): """Feed of latest free comments on the current site""" - - comments_module = comments - + + comments_class = Comment + def _get_lookup_kwargs(self): kwargs = LatestFreeCommentsFeed._get_lookup_kwargs(self) kwargs['is_removed__exact'] = False if settings.COMMENTS_BANNED_USERS_GROUP: kwargs['where'] = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] kwargs['params'] = [COMMENTS_BANNED_USERS_GROUP] - return kwargs \ No newline at end of file + return kwargs diff --git a/django/contrib/comments/models/comments.py b/django/contrib/comments/models/comments.py index 703a543ee2..582a897a93 100644 --- a/django/contrib/comments/models/comments.py +++ b/django/contrib/comments/models/comments.py @@ -1,6 +1,63 @@ from django.db import models from django.models import auth, core from django.utils.translation import gettext_lazy as _ +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. + """ + from django.conf.settings import SECRET_KEY + import md5 + return md5.new(options + photo_options + rating_options + target + 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" + >>> 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. + """ + 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 self.get_list(**kwargs) + + def user_is_moderator(self, user): + from django.conf.settings import COMMENTS_MODERATORS_GROUP + if user.is_superuser: + return True + for g in user.get_group_list(): + if g.id == COMMENTS_MODERATORS_GROUP: + return True + return False class Comment(models.Model): user = models.ForeignKey(auth.User, raw_id_admin=True) @@ -26,22 +83,11 @@ class Comment(models.Model): 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(core.Site) + objects = CommentManager() class META: db_table = 'comments' verbose_name = _('Comment') verbose_name_plural = _('Comments') - module_constants = { - # 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',) admin = models.Admin( fields = ( @@ -114,47 +160,6 @@ class Comment(models.Model): {'user': self.get_user().username, 'date': self.submit_date, 'comment': self.comment, 'domain': self.get_site().domain, 'url': 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. - """ - from django.conf.settings import SECRET_KEY - import md5 - return md5.new(options + photo_options + rating_options + target + SECRET_KEY).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_group_list(): - if g.id == COMMENTS_MODERATORS_GROUP: - return True - return False - class FreeComment(models.Model): # A FreeComment is a comment by a non-registered user. content_type = models.ForeignKey(core.ContentType) @@ -203,37 +208,19 @@ class FreeComment(models.Model): get_content_object.short_description = _('Content object') -class KarmaScore(models.Model): - user = models.ForeignKey(auth.User) - comment = models.ForeignKey(Comment) - score = models.SmallIntegerField(_('score'), db_index=True) - scored_date = models.DateTimeField(_('score date'), auto_now=True) - class META: - module_name = 'karma' - verbose_name = _('Karma score') - verbose_name_plural = _('Karma scores') - unique_together = (('user', 'comment'),) - module_constants = { - # what users get if they don't have any karma - 'DEFAULT_KARMA': 5, - 'KARMA_NEEDED_BEFORE_DISPLAYED': 3, - } - - def __repr__(self): - return _("%(score)d rating by %(user)s") % {'score': self.score, 'user': self.get_user()} - - def _module_vote(user_id, comment_id, score): +class KarmaScoreManager(models.Manager): + def vote(self, 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 = self.get_object(comment__id__exact=comment_id, user__id__exact=user_id) + except self.klass.DoesNotExist: + karma = self.klass(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): + 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. @@ -242,20 +229,22 @@ class KarmaScore(models.Model): return DEFAULT_KARMA return int(round((4.5 * score) + 5.5)) -class UserFlag(models.Model): +class KarmaScore(models.Model): user = models.ForeignKey(auth.User) comment = models.ForeignKey(Comment) - flag_date = models.DateTimeField(_('flag date'), auto_now_add=True) + score = models.SmallIntegerField(_('score'), db_index=True) + scored_date = models.DateTimeField(_('score date'), auto_now=True) + objects = KarmaScoreManager() class META: - db_table = 'comments_user_flags' - verbose_name = _('User flag') - verbose_name_plural = _('User flags') + verbose_name = _('Karma score') + verbose_name_plural = _('Karma scores') unique_together = (('user', 'comment'),) def __repr__(self): - return _("Flag by %r") % self.get_user() + return _("%(score)d rating by %(user)s") % {'score': self.score, 'user': self.get_user()} - def _module_flag(comment, 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, @@ -264,14 +253,28 @@ class UserFlag(models.Model): 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: + f = self.get_object(user__id__exact=user.id, comment__id__exact=comment.id) + except self.klass.DoesNotExist: from django.core.mail import mail_managers - f = UserFlag(None, user.id, comment.id, None) + f = self.klass(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(auth.User) + comment = models.ForeignKey(Comment) + flag_date = models.DateTimeField(_('flag date'), auto_now_add=True) + objects = UserFlagManager() + class META: + db_table = 'comments_user_flags' + verbose_name = _('User flag') + verbose_name_plural = _('User flags') + unique_together = (('user', 'comment'),) + + def __repr__(self): + return _("Flag by %r") % self.get_user() + class ModeratorDeletion(models.Model): user = models.ForeignKey(auth.User, verbose_name='moderator') comment = models.ForeignKey(Comment) @@ -284,4 +287,3 @@ class ModeratorDeletion(models.Model): def __repr__(self): return _("Moderator deletion by %r") % self.get_user() - diff --git a/django/contrib/comments/templatetags/comments.py b/django/contrib/comments/templatetags/comments.py index c2c4ab47d5..1b79232df4 100644 --- a/django/contrib/comments/templatetags/comments.py +++ b/django/contrib/comments/templatetags/comments.py @@ -1,8 +1,8 @@ -"Custom template tags for user comments" - +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.core import template from django.core.exceptions import ObjectDoesNotExist -from django.models.comments import comments, freecomments from django.models.core import contenttypes import re @@ -93,24 +93,24 @@ class CommentFormNode(template.Node): context['display_form'] = True context['target'] = '%s:%s' % (self.content_type.id, self.obj_id) options = [] - for var, abbr in (('photos_required', comments.PHOTOS_REQUIRED), - ('photos_optional', comments.PHOTOS_OPTIONAL), - ('ratings_required', comments.RATINGS_REQUIRED), - ('ratings_optional', comments.RATINGS_OPTIONAL), - ('is_public', comments.IS_PUBLIC)): + 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'] = comments.get_security_hash(context['options'], '', '', context['target']) + context['hash'] = Comment.objects.get_security_hash(context['options'], '', '', context['target']) default_form = 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'] = comments.get_rating_options(self.rating_options) - context['hash'] = comments.get_security_hash(context['options'], context['photo_options'], context['rating_options'], context['target']) + 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 = COMMENT_FORM output = template.Template(default_form).render(context) context.pop() @@ -124,7 +124,7 @@ class CommentCountNode(template.Node): def render(self, context): from django.conf.settings import SITE_ID - get_count_function = self.free and freecomments.get_count or comments.get_count + get_count_function = self.free and FreeComment.objects.get_count or Comment.objects.get_count if self.context_var_name is not None: self.obj_id = template.resolve_variable(self.context_var_name, context) comment_count = get_count_function(object_id__exact=self.obj_id, @@ -143,7 +143,7 @@ class CommentListNode(template.Node): def render(self, context): from django.conf.settings import COMMENTS_BANNED_USERS_GROUP, SITE_ID - get_list_function = self.free and freecomments.get_list or comments.get_list_with_karma + get_list_function = self.free and FreeComment.objects.get_list 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) @@ -165,7 +165,7 @@ class CommentListNode(template.Node): if not self.free: if context.has_key('user') and not context['user'].is_anonymous(): user_id = context['user'].id - context['user_can_moderate_comments'] = comments.user_is_moderator(context['user']) + context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user']) else: user_id = None context['user_can_moderate_comments'] = False @@ -230,8 +230,8 @@ class DoCommentForm: 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 (comments.MIN_PHOTO_DIMENSION <= int(opt) <= comments.MAX_PHOTO_DIMENSION): - raise template.TemplateSyntaxError, "Invalid photo dimension in %r tag: '%s'. Only values between %s and %s are allowed." % (tokens[0], opt, comments.MIN_PHOTO_DIMENSION, comments.MAX_PHOTO_DIMENSION) + 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 diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py index af114dc136..589cf0fbb0 100644 --- a/django/contrib/comments/views/comments.py +++ b/django/contrib/comments/views/comments.py @@ -3,8 +3,8 @@ from django.core.mail import mail_admins, mail_managers from django.core.exceptions import Http404, ObjectDoesNotExist from django.core.extensions import DjangoContext, render_to_response from django.models.auth import SESSION_KEY -from django.models.comments import comments, freecomments -from django.models.core import contenttypes +from django.contrib.comments.models import Comment, FreeComment, PHOTOS_REQUIRED, PHOTOS_OPTIONAL, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC +from django.models.core import ContentType from django.parts.auth.formfields import AuthenticationForm from django.utils.httpwrappers import HttpResponseRedirect from django.utils.text import normalize_newlines @@ -75,7 +75,7 @@ class PublicCommentManipulator(AuthenticationForm): def get_comment(self, new_data): "Helper function" - return comments.Comment(None, self.get_user_id(), new_data["content_type_id"], + 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), @@ -87,7 +87,7 @@ class PublicCommentManipulator(AuthenticationForm): def save(self, new_data): today = datetime.date.today() c = self.get_comment(new_data) - for old in comments.get_list(content_type__id__exact=new_data["content_type_id"], + for old in Comment.objects.get_list(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 @@ -132,7 +132,7 @@ class PublicFreeCommentManipulator(formfields.Manipulator): def get_comment(self, new_data): "Helper function" - return freecomments.FreeComment(None, new_data["content_type_id"], + 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, SITE_ID) @@ -143,7 +143,7 @@ class PublicFreeCommentManipulator(formfields.Manipulator): # 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 freecomments.get_list(content_type__id__exact=new_data["content_type_id"], + for old_comment in FreeComment.objects.get_list(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): @@ -190,16 +190,16 @@ def post_comment(request): 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 comments.get_security_hash(options, photo_options, rating_options, target) != security_hash: + 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 = comments.get_rating_options(base64.decodestring(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 = contenttypes.get_object(pk=content_type_id).get_object_for_this_type(pk=object_id) + obj = ContentType.objects.get_object(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' @@ -207,9 +207,9 @@ def post_comment(request): 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'] = comments.IS_PUBLIC in option_list + new_data['is_public'] = IS_PUBLIC in option_list manipulator = PublicCommentManipulator(request.user, - ratings_required=comments.RATINGS_REQUIRED in option_list, + ratings_required=RATINGS_REQUIRED in option_list, ratings_range=rating_range, num_rating_choices=len(rating_choices)) errors = manipulator.get_validation_errors(new_data) @@ -236,8 +236,8 @@ def post_comment(request): 'target': target, 'hash': security_hash, 'rating_options': rating_options, - 'ratings_optional': comments.RATINGS_OPTIONAL in option_list, - 'ratings_required': comments.RATINGS_REQUIRED in option_list, + 'ratings_optional': RATINGS_OPTIONAL in option_list, + 'ratings_required': RATINGS_REQUIRED in option_list, 'rating_range': rating_range, 'rating_choices': rating_choices, }, context_instance=DjangoContext(request)) @@ -279,10 +279,10 @@ def post_free_comment(request): 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 comments.get_security_hash(options, '', '', target) != security_hash: + 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 = contenttypes.get_object(pk=content_type_id) + content_type = ContentType.objects.get_object(pk=content_type_id) try: obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: @@ -292,7 +292,7 @@ def post_free_comment(request): 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'] = comments.IS_PUBLIC in option_list + 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'): @@ -330,7 +330,7 @@ def comment_was_posted(request): if request.GET.has_key('c'): content_type_id, object_id = request.GET['c'].split(':') try: - content_type = contenttypes.get_object(pk=content_type_id) + content_type = ContentType.objects.get_object(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: pass diff --git a/django/contrib/redirects/middleware.py b/django/contrib/redirects/middleware.py index c8f09ada8e..7e490d5a21 100644 --- a/django/contrib/redirects/middleware.py +++ b/django/contrib/redirects/middleware.py @@ -1,4 +1,4 @@ -from django.models.redirects import redirects +from django.contrib.redirects.models import Redirect from django.utils import httpwrappers from django.conf.settings import APPEND_SLASH, SITE_ID @@ -8,15 +8,15 @@ class RedirectFallbackMiddleware: return response # No need to check for a redirect for non-404 responses. path = request.get_full_path() try: - r = redirects.get_object(site__id__exact=SITE_ID, old_path__exact=path) - except redirects.RedirectDoesNotExist: + r = Redirect.objects.get_object(site__id__exact=SITE_ID, old_path__exact=path) + except Redirect.DoesNotExist: r = None if r is None and APPEND_SLASH: # Try removing the trailing slash. try: - r = redirects.get_object(site__id__exact=SITE_ID, + r = Redirect.objects.get_object(site__id__exact=SITE_ID, old_path__exact=path[:path.rfind('/')]+path[path.rfind('/')+1:]) - except redirects.RedirectDoesNotExist: + except Redirect.DoesNotExist: pass if r is not None: if r == '': diff --git a/django/core/management.py b/django/core/management.py index 85d4071337..2d02bb924d 100644 --- a/django/core/management.py +++ b/django/core/management.py @@ -427,17 +427,17 @@ install.args = APP_ARGS def installperms(mod): "Installs any permissions for the given model, if needed." - from django.models.auth import permissions - from django.models.core import packages + from django.models.auth import Permission + from django.models.core import Package num_added = 0 - package = packages.get_object(pk=mod._MODELS[0]._meta.app_label) + package = Package.objects.get_object(pk=mod._MODELS[0]._meta.app_label) for klass in mod._MODELS: opts = klass._meta for codename, name in _get_all_permissions(opts): try: - permissions.get_object(name__exact=name, codename__exact=codename, package__label__exact=package.label) - except permissions.PermissionDoesNotExist: - p = permissions.Permission(name=name, package=package, codename=codename) + Permission.objects.get_object(name__exact=name, codename__exact=codename, package__label__exact=package.label) + except Permission.DoesNotExist: + p = Permission(name=name, package=package, codename=codename) p.save() print "Added permission '%r'." % p num_added += 1 diff --git a/django/parts/auth/formfields.py b/django/parts/auth/formfields.py index 7d0cea2f52..fae488ef23 100644 --- a/django/parts/auth/formfields.py +++ b/django/parts/auth/formfields.py @@ -1,4 +1,4 @@ -from django.models.auth import users +from django.models.auth import User from django.core import formfields, validators class AuthenticationForm(formfields.Manipulator): @@ -28,8 +28,8 @@ class AuthenticationForm(formfields.Manipulator): def isValidUser(self, field_data, all_data): try: - self.user_cache = users.get_object(username__exact=field_data) - except users.UserDoesNotExist: + self.user_cache = User.objects.get_object(username__exact=field_data) + except User.DoesNotExist: raise validators.ValidationError, "Please enter a correct username and password. Note that both fields are case-sensitive." def isValidPasswordForUser(self, field_data, all_data): diff --git a/django/views/defaults.py b/django/views/defaults.py index 95c18b4263..0823d42347 100644 --- a/django/views/defaults.py +++ b/django/views/defaults.py @@ -1,13 +1,13 @@ from django.core.exceptions import Http404, ObjectDoesNotExist from django.core.template import Context, loader -from django.models.core import sites, contenttypes +from django.models.core import ContentType, Site from django.utils import httpwrappers 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 = contenttypes.get_object(pk=content_type_id) + content_type = ContentType.objects.get_object(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: raise Http404, "Content type %s object %s doesn't exist" % (content_type_id, object_id) @@ -35,14 +35,14 @@ def shortcut(request, content_type_id, object_id): elif hasattr(obj, 'get_site'): try: object_domain = obj.get_site().domain - except sites.SiteDoesNotExist: + except Site.DoesNotExist: pass # Then, fall back to the current site (if possible) else: try: - object_domain = sites.get_current().domain - except sites.SiteDoesNotExist: + object_domain = Site.objects.get_current().domain + except Site.DoesNotExist: # Finally, give up and use a URL without the domain name return httpwrappers.HttpResponseRedirect(obj.get_absolute_url()) return httpwrappers.HttpResponseRedirect('http://%s%s' % (object_domain, obj.get_absolute_url()))