~ubuntu-branches/ubuntu/jaunty/python-django/jaunty

« back to all changes in this revision

Viewing changes to django/contrib/comments/templatetags/comments.py

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant, Eddy Mulyono
  • Date: 2008-09-16 12:18:47 UTC
  • mfrom: (1.1.5 upstream) (4.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080916121847-mg225rg5mnsdqzr0
Tags: 1.0-1ubuntu1
* Merge from Debian (LP: #264191), remaining changes:
  - Run test suite on build.

[Eddy Mulyono]
* Update patch to workaround network test case failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from django.contrib.comments.models import Comment, FreeComment
2
 
from django.contrib.comments.models import PHOTOS_REQUIRED, PHOTOS_OPTIONAL, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC
3
 
from django.contrib.comments.models import MIN_PHOTO_DIMENSION, MAX_PHOTO_DIMENSION
4
1
from django import template
5
 
from django.template import loader
6
 
from django.core.exceptions import ObjectDoesNotExist
 
2
from django.template.loader import render_to_string
 
3
from django.conf import settings
7
4
from django.contrib.contenttypes.models import ContentType
8
 
import re
 
5
from django.contrib import comments
 
6
from django.utils.encoding import smart_unicode
9
7
 
10
8
register = template.Library()
11
9
 
12
 
COMMENT_FORM = 'comments/form.html'
13
 
FREE_COMMENT_FORM = 'comments/freeform.html'
14
 
 
15
 
class CommentFormNode(template.Node):
16
 
    def __init__(self, content_type, obj_id_lookup_var, obj_id, free,
17
 
        photos_optional=False, photos_required=False, photo_options='',
18
 
        ratings_optional=False, ratings_required=False, rating_options='',
19
 
        is_public=True):
20
 
        self.content_type = content_type
21
 
        self.obj_id_lookup_var, self.obj_id, self.free = obj_id_lookup_var, obj_id, free
22
 
        self.photos_optional, self.photos_required = photos_optional, photos_required
23
 
        self.ratings_optional, self.ratings_required = ratings_optional, ratings_required
24
 
        self.photo_options, self.rating_options = photo_options, rating_options
25
 
        self.is_public = is_public
26
 
 
27
 
    def render(self, context):
28
 
        from django.utils.text import normalize_newlines
29
 
        import base64
30
 
        context.push()
31
 
        if self.obj_id_lookup_var is not None:
32
 
            try:
33
 
                self.obj_id = template.resolve_variable(self.obj_id_lookup_var, context)
34
 
            except template.VariableDoesNotExist:
35
 
                return ''
36
 
            # Validate that this object ID is valid for this content-type.
37
 
            # We only have to do this validation if obj_id_lookup_var is provided,
38
 
            # because do_comment_form() validates hard-coded object IDs.
39
 
            try:
40
 
                self.content_type.get_object_for_this_type(pk=self.obj_id)
41
 
            except ObjectDoesNotExist:
42
 
                context['display_form'] = False
43
 
            else:
44
 
                context['display_form'] = True
45
 
        else:
46
 
            context['display_form'] = True
47
 
        context['target'] = '%s:%s' % (self.content_type.id, self.obj_id)
48
 
        options = []
49
 
        for var, abbr in (('photos_required', PHOTOS_REQUIRED),
50
 
                          ('photos_optional', PHOTOS_OPTIONAL),
51
 
                          ('ratings_required', RATINGS_REQUIRED),
52
 
                          ('ratings_optional', RATINGS_OPTIONAL),
53
 
                          ('is_public', IS_PUBLIC)):
54
 
            context[var] = getattr(self, var)
55
 
            if getattr(self, var):
56
 
                options.append(abbr)
57
 
        context['options'] = ','.join(options)
58
 
        if self.free:
59
 
            context['hash'] = Comment.objects.get_security_hash(context['options'], '', '', context['target'])
60
 
            default_form = loader.get_template(FREE_COMMENT_FORM)
61
 
        else:
62
 
            context['photo_options'] = self.photo_options
63
 
            context['rating_options'] = normalize_newlines(base64.encodestring(self.rating_options).strip())
64
 
            if self.rating_options:
65
 
                context['rating_range'], context['rating_choices'] = Comment.objects.get_rating_options(self.rating_options)
66
 
            context['hash'] = Comment.objects.get_security_hash(context['options'], context['photo_options'], context['rating_options'], context['target'])
67
 
            default_form = loader.get_template(COMMENT_FORM)
68
 
        output = default_form.render(context)
69
 
        context.pop()
70
 
        return output
71
 
 
72
 
class CommentCountNode(template.Node):
73
 
    def __init__(self, package, module, context_var_name, obj_id, var_name, free):
74
 
        self.package, self.module = package, module
75
 
        self.context_var_name, self.obj_id = context_var_name, obj_id
76
 
        self.var_name, self.free = var_name, free
77
 
 
78
 
    def render(self, context):
79
 
        from django.conf import settings
80
 
        manager = self.free and FreeComment.objects or Comment.objects
81
 
        if self.context_var_name is not None:
82
 
            self.obj_id = template.resolve_variable(self.context_var_name, context)
83
 
        comment_count = manager.filter(object_id__exact=self.obj_id,
84
 
            content_type__app_label__exact=self.package,
85
 
            content_type__model__exact=self.module, site__id__exact=settings.SITE_ID).count()
86
 
        context[self.var_name] = comment_count
87
 
        return ''
88
 
 
89
 
class CommentListNode(template.Node):
90
 
    def __init__(self, package, module, context_var_name, obj_id, var_name, free, ordering, extra_kwargs=None):
91
 
        self.package, self.module = package, module
92
 
        self.context_var_name, self.obj_id = context_var_name, obj_id
93
 
        self.var_name, self.free = var_name, free
94
 
        self.ordering = ordering
95
 
        self.extra_kwargs = extra_kwargs or {}
96
 
 
97
 
    def render(self, context):
98
 
        from django.conf import settings
99
 
        get_list_function = self.free and FreeComment.objects.filter or Comment.objects.get_list_with_karma
100
 
        if self.context_var_name is not None:
101
 
            try:
102
 
                self.obj_id = template.resolve_variable(self.context_var_name, context)
103
 
            except template.VariableDoesNotExist:
104
 
                return ''
105
 
        kwargs = {
106
 
            'object_id__exact': self.obj_id,
107
 
            'content_type__app_label__exact': self.package,
108
 
            'content_type__model__exact': self.module,
109
 
            'site__id__exact': settings.SITE_ID,
110
 
        }
111
 
        kwargs.update(self.extra_kwargs)
112
 
        if not self.free and settings.COMMENTS_BANNED_USERS_GROUP:
113
 
            kwargs['select'] = {'is_hidden': 'user_id IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)' % settings.COMMENTS_BANNED_USERS_GROUP}
114
 
        comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
115
 
 
116
 
        if not self.free:
117
 
            if context.has_key('user') and context['user'].is_authenticated():
118
 
                user_id = context['user'].id
119
 
                context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
120
 
            else:
121
 
                user_id = None
122
 
                context['user_can_moderate_comments'] = False
123
 
            # Only display comments by banned users to those users themselves.
124
 
            if settings.COMMENTS_BANNED_USERS_GROUP:
125
 
                comment_list = [c for c in comment_list if not c.is_hidden or (user_id == c.user_id)]
126
 
 
127
 
        context[self.var_name] = comment_list
128
 
        return ''
129
 
 
130
 
class DoCommentForm:
131
 
    """
132
 
    Displays a comment form for the given params.
133
 
 
134
 
    Syntax::
135
 
 
136
 
        {% comment_form for [pkg].[py_module_name] [context_var_containing_obj_id] with [list of options] %}
137
 
 
138
 
    Example usage::
139
 
 
140
 
        {% 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 %}
141
 
 
142
 
    ``[context_var_containing_obj_id]`` can be a hard-coded integer or a variable containing the ID.
143
 
    """
144
 
    def __init__(self, free):
145
 
        self.free = free
146
 
 
147
 
    def __call__(self, parser, token):
148
 
        tokens = token.contents.split()
149
 
        if len(tokens) < 4:
150
 
            raise template.TemplateSyntaxError, "%r tag requires at least 3 arguments" % tokens[0]
151
 
        if tokens[1] != 'for':
152
 
            raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0]
153
 
        try:
154
 
            package, module = tokens[2].split('.')
155
 
        except ValueError: # unpack list of wrong size
156
 
            raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0]
157
 
        try:
158
 
            content_type = ContentType.objects.get(app_label__exact=package, model__exact=module)
159
 
        except ContentType.DoesNotExist:
160
 
            raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module)
161
 
        obj_id_lookup_var, obj_id = None, None
162
 
        if tokens[3].isdigit():
163
 
            obj_id = tokens[3]
164
 
            try: # ensure the object ID is valid
165
 
                content_type.get_object_for_this_type(pk=obj_id)
166
 
            except ObjectDoesNotExist:
167
 
                raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id)
168
 
        else:
169
 
            obj_id_lookup_var = tokens[3]
170
 
        kwargs = {}
171
 
        if len(tokens) > 4:
172
 
            if tokens[4] != 'with':
173
 
                raise template.TemplateSyntaxError, "Fourth argument in %r tag must be 'with'" % tokens[0]
174
 
            for option, args in zip(tokens[5::2], tokens[6::2]):
175
 
                if option in ('photos_optional', 'photos_required') and not self.free:
176
 
                    # VALIDATION ##############################################
177
 
                    option_list = args.split(',')
178
 
                    if len(option_list) % 3 != 0:
179
 
                        raise template.TemplateSyntaxError, "Incorrect number of comma-separated arguments to %r tag" % tokens[0]
180
 
                    for opt in option_list[::3]:
181
 
                        if not opt.isalnum():
182
 
                            raise template.TemplateSyntaxError, "Invalid photo directory name in %r tag: '%s'" % (tokens[0], opt)
183
 
                    for opt in option_list[1::3] + option_list[2::3]:
184
 
                        if not opt.isdigit() or not (MIN_PHOTO_DIMENSION <= int(opt) <= MAX_PHOTO_DIMENSION):
185
 
                            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)
186
 
                    # VALIDATION ENDS #########################################
187
 
                    kwargs[option] = True
188
 
                    kwargs['photo_options'] = args
189
 
                elif option in ('ratings_optional', 'ratings_required') and not self.free:
190
 
                    # VALIDATION ##############################################
191
 
                    if 2 < len(args.split('|')) > 9:
192
 
                        raise template.TemplateSyntaxError, "Incorrect number of '%s' options in %r tag. Use between 2 and 8." % (option, tokens[0])
193
 
                    if re.match('^scale:\d+\-\d+\:$', args.split('|')[0]):
194
 
                        raise template.TemplateSyntaxError, "Invalid 'scale' in %r tag's '%s' options" % (tokens[0], option)
195
 
                    # VALIDATION ENDS #########################################
196
 
                    kwargs[option] = True
197
 
                    kwargs['rating_options'] = args
198
 
                elif option in ('is_public'):
199
 
                    kwargs[option] = (args == 'true')
200
 
                else:
201
 
                    raise template.TemplateSyntaxError, "%r tag got invalid parameter '%s'" % (tokens[0], option)
202
 
        return CommentFormNode(content_type, obj_id_lookup_var, obj_id, self.free, **kwargs)
203
 
 
204
 
class DoCommentCount:
205
 
    """
206
 
    Gets comment count for the given params and populates the template context
207
 
    with a variable containing that value, whose name is defined by the 'as'
208
 
    clause.
209
 
 
210
 
    Syntax::
211
 
 
212
 
        {% get_comment_count for [pkg].[py_module_name] [context_var_containing_obj_id] as [varname]  %}
213
 
 
214
 
    Example usage::
215
 
 
216
 
        {% get_comment_count for lcom.eventtimes event.id as comment_count %}
217
 
 
218
 
    Note: ``[context_var_containing_obj_id]`` can also be a hard-coded integer, like this::
219
 
 
220
 
        {% get_comment_count for lcom.eventtimes 23 as comment_count %}
221
 
    """
222
 
    def __init__(self, free):
223
 
        self.free = free
224
 
 
225
 
    def __call__(self, parser, token):
226
 
        tokens = token.contents.split()
227
 
        # Now tokens is a list like this:
228
 
        # ['get_comment_list', 'for', 'lcom.eventtimes', 'event.id', 'as', 'comment_list']
229
 
        if len(tokens) != 6:
230
 
            raise template.TemplateSyntaxError, "%r tag requires 5 arguments" % tokens[0]
231
 
        if tokens[1] != 'for':
232
 
            raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0]
233
 
        try:
234
 
            package, module = tokens[2].split('.')
235
 
        except ValueError: # unpack list of wrong size
236
 
            raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0]
237
 
        try:
238
 
            content_type = ContentType.objects.get(app_label__exact=package, model__exact=module)
239
 
        except ContentType.DoesNotExist:
240
 
            raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module)
241
 
        var_name, obj_id = None, None
242
 
        if tokens[3].isdigit():
243
 
            obj_id = tokens[3]
244
 
            try: # ensure the object ID is valid
245
 
                content_type.get_object_for_this_type(pk=obj_id)
246
 
            except ObjectDoesNotExist:
247
 
                raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id)
248
 
        else:
249
 
            var_name = tokens[3]
250
 
        if tokens[4] != 'as':
251
 
            raise template.TemplateSyntaxError, "Fourth argument in %r must be 'as'" % tokens[0]
252
 
        return CommentCountNode(package, module, var_name, obj_id, tokens[5], self.free)
253
 
 
254
 
class DoGetCommentList:
255
 
    """
256
 
    Gets comments for the given params and populates the template context with a
257
 
    special comment_package variable, whose name is defined by the ``as``
258
 
    clause.
259
 
 
260
 
    Syntax::
261
 
 
262
 
        {% get_comment_list for [pkg].[py_module_name] [context_var_containing_obj_id] as [varname] (reversed) %}
263
 
 
264
 
    Example usage::
265
 
 
266
 
        {% get_comment_list for lcom.eventtimes event.id as comment_list %}
267
 
 
268
 
    Note: ``[context_var_containing_obj_id]`` can also be a hard-coded integer, like this::
269
 
 
270
 
        {% get_comment_list for lcom.eventtimes 23 as comment_list %}
271
 
 
272
 
    To get a list of comments in reverse order -- that is, most recent first --
273
 
    pass ``reversed`` as the last param::
274
 
 
275
 
        {% get_comment_list for lcom.eventtimes event.id as comment_list reversed %}
276
 
    """
277
 
    def __init__(self, free):
278
 
        self.free = free
279
 
 
280
 
    def __call__(self, parser, token):
281
 
        tokens = token.contents.split()
282
 
        # Now tokens is a list like this:
283
 
        # ['get_comment_list', 'for', 'lcom.eventtimes', 'event.id', 'as', 'comment_list']
284
 
        if not len(tokens) in (6, 7):
285
 
            raise template.TemplateSyntaxError, "%r tag requires 5 or 6 arguments" % tokens[0]
286
 
        if tokens[1] != 'for':
287
 
            raise template.TemplateSyntaxError, "Second argument in %r tag must be 'for'" % tokens[0]
288
 
        try:
289
 
            package, module = tokens[2].split('.')
290
 
        except ValueError: # unpack list of wrong size
291
 
            raise template.TemplateSyntaxError, "Third argument in %r tag must be in the format 'package.module'" % tokens[0]
292
 
        try:
293
 
            content_type = ContentType.objects.get(app_label__exact=package,model__exact=module)
294
 
        except ContentType.DoesNotExist:
295
 
            raise template.TemplateSyntaxError, "%r tag has invalid content-type '%s.%s'" % (tokens[0], package, module)
296
 
        var_name, obj_id = None, None
297
 
        if tokens[3].isdigit():
298
 
            obj_id = tokens[3]
299
 
            try: # ensure the object ID is valid
300
 
                content_type.get_object_for_this_type(pk=obj_id)
301
 
            except ObjectDoesNotExist:
302
 
                raise template.TemplateSyntaxError, "%r tag refers to %s object with ID %s, which doesn't exist" % (tokens[0], content_type.name, obj_id)
303
 
        else:
304
 
            var_name = tokens[3]
305
 
        if tokens[4] != 'as':
306
 
            raise template.TemplateSyntaxError, "Fourth argument in %r must be 'as'" % tokens[0]
307
 
        if len(tokens) == 7:
308
 
            if tokens[6] != 'reversed':
309
 
                raise template.TemplateSyntaxError, "Final argument in %r must be 'reversed' if given" % tokens[0]
310
 
            ordering = "-"
311
 
        else:
312
 
            ordering = ""
313
 
        return CommentListNode(package, module, var_name, obj_id, tokens[5], self.free, ordering)
314
 
 
315
 
# registration comments
316
 
register.tag('get_comment_list', DoGetCommentList(False))
317
 
register.tag('comment_form', DoCommentForm(False))
318
 
register.tag('get_comment_count', DoCommentCount(False))
319
 
# free comments
320
 
register.tag('get_free_comment_list', DoGetCommentList(True))
321
 
register.tag('free_comment_form', DoCommentForm(True))
322
 
register.tag('get_free_comment_count', DoCommentCount(True))
 
10
class BaseCommentNode(template.Node):
 
11
    """
 
12
    Base helper class (abstract) for handling the get_comment_* template tags.
 
13
    Looks a bit strange, but the subclasses below should make this a bit more
 
14
    obvious.
 
15
    """
 
16
 
 
17
    #@classmethod
 
18
    def handle_token(cls, parser, token):
 
19
        """Class method to parse get_comment_list/count/form and return a Node."""
 
20
        tokens = token.contents.split()
 
21
        if tokens[1] != 'for':
 
22
            raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
 
23
 
 
24
        # {% get_whatever for obj as varname %}
 
25
        if len(tokens) == 5:
 
26
            if tokens[3] != 'as':
 
27
                raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0])
 
28
            return cls(
 
29
                object_expr = parser.compile_filter(tokens[2]),
 
30
                as_varname = tokens[4],
 
31
            )
 
32
 
 
33
        # {% get_whatever for app.model pk as varname %}
 
34
        elif len(tokens) == 6:
 
35
            if tokens[4] != 'as':
 
36
                raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0])
 
37
            return cls(
 
38
                ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),
 
39
                object_pk_expr = parser.compile_filter(tokens[3]),
 
40
                as_varname = tokens[5]
 
41
            )
 
42
 
 
43
        else:
 
44
            raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0])
 
45
 
 
46
    handle_token = classmethod(handle_token)
 
47
 
 
48
    #@staticmethod
 
49
    def lookup_content_type(token, tagname):
 
50
        try:
 
51
            app, model = token.split('.')
 
52
            return ContentType.objects.get(app_label=app, model=model)
 
53
        except ValueError:
 
54
            raise template.TemplateSyntaxError("Third argument in %r must be in the format 'app.model'" % tagname)
 
55
        except ContentType.DoesNotExist:
 
56
            raise template.TemplateSyntaxError("%r tag has non-existant content-type: '%s.%s'" % (tagname, app, model))
 
57
    lookup_content_type = staticmethod(lookup_content_type)
 
58
 
 
59
    def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None):
 
60
        if ctype is None and object_expr is None:
 
61
            raise template.TemplateSyntaxError("Comment nodes must be given either a literal object or a ctype and object pk.")
 
62
        self.comment_model = comments.get_model()
 
63
        self.as_varname = as_varname
 
64
        self.ctype = ctype
 
65
        self.object_pk_expr = object_pk_expr
 
66
        self.object_expr = object_expr
 
67
        self.comment = comment
 
68
 
 
69
    def render(self, context):
 
70
        qs = self.get_query_set(context)
 
71
        context[self.as_varname] = self.get_context_value_from_queryset(context, qs)
 
72
        return ''
 
73
 
 
74
    def get_query_set(self, context):
 
75
        ctype, object_pk = self.get_target_ctype_pk(context)
 
76
        if not object_pk:
 
77
            return self.comment_model.objects.none()
 
78
 
 
79
        qs = self.comment_model.objects.filter(
 
80
            content_type = ctype,
 
81
            object_pk    = smart_unicode(object_pk),
 
82
            site__pk     = settings.SITE_ID,
 
83
            is_public    = True,
 
84
        )
 
85
        if getattr(settings, 'COMMENTS_HIDE_REMOVED', True):
 
86
            qs = qs.filter(is_removed=False)
 
87
 
 
88
        return qs
 
89
 
 
90
    def get_target_ctype_pk(self, context):
 
91
        if self.object_expr:
 
92
            try:
 
93
                obj = self.object_expr.resolve(context)
 
94
            except template.VariableDoesNotExist:
 
95
                return None, None
 
96
            return ContentType.objects.get_for_model(obj), obj.pk
 
97
        else:
 
98
            return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True)
 
99
 
 
100
    def get_context_value_from_queryset(self, context, qs):
 
101
        """Subclasses should override this."""
 
102
        raise NotImplementedError
 
103
 
 
104
class CommentListNode(BaseCommentNode):
 
105
    """Insert a list of comments into the context."""
 
106
    def get_context_value_from_queryset(self, context, qs):
 
107
        return list(qs)
 
108
 
 
109
class CommentCountNode(BaseCommentNode):
 
110
    """Insert a count of comments into the context."""
 
111
    def get_context_value_from_queryset(self, context, qs):
 
112
        return qs.count()
 
113
 
 
114
class CommentFormNode(BaseCommentNode):
 
115
    """Insert a form for the comment model into the context."""
 
116
 
 
117
    def get_form(self, context):
 
118
        ctype, object_pk = self.get_target_ctype_pk(context)
 
119
        if object_pk:
 
120
            return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk))
 
121
        else:
 
122
            return None
 
123
 
 
124
    def render(self, context):
 
125
        context[self.as_varname] = self.get_form(context)
 
126
        return ''
 
127
 
 
128
class RenderCommentFormNode(CommentFormNode):
 
129
    """Render the comment form directly"""
 
130
 
 
131
    #@classmethod
 
132
    def handle_token(cls, parser, token):
 
133
        """Class method to parse render_comment_form and return a Node."""
 
134
        tokens = token.contents.split()
 
135
        if tokens[1] != 'for':
 
136
            raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
 
137
 
 
138
        # {% render_comment_form for obj %}
 
139
        if len(tokens) == 3:
 
140
            return cls(object_expr=parser.compile_filter(tokens[2]))
 
141
 
 
142
        # {% render_comment_form for app.models pk %}
 
143
        elif len(tokens) == 4:
 
144
            return cls(
 
145
                ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),
 
146
                object_pk_expr = parser.compile_filter(tokens[3])
 
147
            )
 
148
    handle_token = classmethod(handle_token)
 
149
 
 
150
    def render(self, context):
 
151
        ctype, object_pk = self.get_target_ctype_pk(context)
 
152
        if object_pk:
 
153
            template_search_list = [
 
154
                "comments/%s/%s/form.html" % (ctype.app_label, ctype.model),
 
155
                "comments/%s/form.html" % ctype.app_label,
 
156
                "comments/form.html"
 
157
            ]
 
158
            context.push()
 
159
            formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context)
 
160
            context.pop()
 
161
            return formstr
 
162
        else:
 
163
            return ''
 
164
 
 
165
# We could just register each classmethod directly, but then we'd lose out on
 
166
# the automagic docstrings-into-admin-docs tricks. So each node gets a cute
 
167
# wrapper function that just exists to hold the docstring.
 
168
 
 
169
#@register.tag
 
170
def get_comment_count(parser, token):
 
171
    """
 
172
    Gets the comment count for the given params and populates the template
 
173
    context with a variable containing that value, whose name is defined by the
 
174
    'as' clause.
 
175
 
 
176
    Syntax::
 
177
 
 
178
        {% get_comment_count for [object] as [varname]  %}
 
179
        {% get_comment_count for [app].[model] [object_id] as [varname]  %}
 
180
 
 
181
    Example usage::
 
182
 
 
183
        {% get_comment_count for event as comment_count %}
 
184
        {% get_comment_count for calendar.event event.id as comment_count %}
 
185
        {% get_comment_count for calendar.event 17 as comment_count %}
 
186
 
 
187
    """
 
188
    return CommentCountNode.handle_token(parser, token)
 
189
 
 
190
#@register.tag
 
191
def get_comment_list(parser, token):
 
192
    """
 
193
    Gets the list of comments for the given params and populates the template
 
194
    context with a variable containing that value, whose name is defined by the
 
195
    'as' clause.
 
196
 
 
197
    Syntax::
 
198
 
 
199
        {% get_comment_list for [object] as [varname]  %}
 
200
        {% get_comment_list for [app].[model] [object_id] as [varname]  %}
 
201
 
 
202
    Example usage::
 
203
 
 
204
        {% get_comment_list for event as comment_list %}
 
205
        {% for comment in comment_list %}
 
206
            ...
 
207
        {% endfor %}
 
208
 
 
209
    """
 
210
    return CommentListNode.handle_token(parser, token)
 
211
 
 
212
#@register.tag
 
213
def get_comment_form(parser, token):
 
214
    """
 
215
    Get a (new) form object to post a new comment.
 
216
 
 
217
    Syntax::
 
218
 
 
219
        {% get_comment_form for [object] as [varname] %}
 
220
        {% get_comment_form for [app].[model] [object_id] as [varname] %}
 
221
    """
 
222
    return CommentFormNode.handle_token(parser, token)
 
223
 
 
224
#@register.tag
 
225
def render_comment_form(parser, token):
 
226
    """
 
227
    Render the comment form (as returned by ``{% render_comment_form %}``) through
 
228
    the ``comments/form.html`` template.
 
229
 
 
230
    Syntax::
 
231
 
 
232
        {% render_comment_form for [object] %}
 
233
        {% render_comment_form for [app].[model] [object_id] %}
 
234
    """
 
235
    return RenderCommentFormNode.handle_token(parser, token)
 
236
 
 
237
#@register.simple_tag
 
238
def comment_form_target():
 
239
    """
 
240
    Get the target URL for the comment form.
 
241
 
 
242
    Example::
 
243
 
 
244
        <form action="{% comment_form_target %}" method="POST">
 
245
    """
 
246
    return comments.get_form_target()
 
247
 
 
248
register.tag(get_comment_count)
 
249
register.tag(get_comment_list)
 
250
register.tag(get_comment_form)
 
251
register.tag(render_comment_form)
 
252
register.simple_tag(comment_form_target)