Debian Codegraph @

django_comments/templatetags/comments.py

raw symbols SCIP
1 from django import template
2 from django.template.loader import render_to_string
3 from django.conf import settings
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.sites.shortcuts import get_current_site
6 from django.utils.encoding import smart_str
7
8 import django_comments
9
10 register = template.Library()
11
12
13 class BaseCommentNode(template.Node):
14 """
15 Base helper class (abstract) for handling the get_comment_* template tags.
16 Looks a bit strange, but the subclasses below should make this a bit more
17 obvious.
18 """
19
20 @classmethod
21 def handle_token(cls, parser, token):
22 """Class method to parse get_comment_list/count/form and return a Node."""
23 tokens = token.split_contents()
24 if tokens[1] != 'for':
25 raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
26
27 # {% get_whatever for obj as varname %}
28 if len(tokens) == 5:
29 if tokens[3] != 'as':
30 raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0])
31 return cls(
32 object_expr=parser.compile_filter(tokens[2]),
33 as_varname=tokens[4],
34 )
35
36 # {% get_whatever for app.model pk as varname %}
37 elif len(tokens) == 6:
38 if tokens[4] != 'as':
39 raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0])
40 return cls(
41 ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),
42 object_pk_expr=parser.compile_filter(tokens[3]),
43 as_varname=tokens[5]
44 )
45
46 else:
47 raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0])
48
49 @staticmethod
50 def lookup_content_type(token, tagname):
51 try:
52 app, model = token.split('.')
53 return ContentType.objects.get_by_natural_key(app, model)
54 except ValueError:
55 raise template.TemplateSyntaxError("Third argument in %r must be in the format 'app.model'" % tagname)
56 except ContentType.DoesNotExist:
57 raise template.TemplateSyntaxError("%r tag has non-existant content-type: '%s.%s'" % (tagname, app, model))
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(
62 "Comment nodes must be given either a literal object or a ctype and object pk.")
63 self.comment_model = django_comments.get_model()
64 self.as_varname = as_varname
65 self.ctype = ctype
66 self.object_pk_expr = object_pk_expr
67 self.object_expr = object_expr
68 self.comment = comment
69
70 def render(self, context):
71 qs = self.get_queryset(context)
72 context[self.as_varname] = self.get_context_value_from_queryset(context, qs)
73 return ''
74
75 def get_queryset(self, context):
76 ctype, object_pk = self.get_target_ctype_pk(context)
77 if not object_pk:
78 return self.comment_model.objects.none()
79
80 # Explicit SITE_ID takes precedence over request. This is also how
81 # get_current_site operates.
82 site_id = getattr(settings, "SITE_ID", None)
83 if not site_id and ('request' in context):
84 site_id = get_current_site(context['request']).pk
85
86 qs = self.comment_model.objects.filter(
87 content_type=ctype,
88 object_pk=smart_str(object_pk),
89 site__pk=site_id,
90 )
91
92 # The is_public and is_removed fields are implementation details of the
93 # built-in comment model's spam filtering system, so they might not
94 # be present on a custom comment model subclass. If they exist, we
95 # should filter on them.
96 field_names = [f.name for f in self.comment_model._meta.fields]
97 if 'is_public' in field_names:
98 qs = qs.filter(is_public=True)
99 if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names:
100 qs = qs.filter(is_removed=False)
101 if 'user' in field_names:
102 qs = qs.select_related('user')
103 return qs
104
105 def get_target_ctype_pk(self, context):
106 if self.object_expr:
107 try:
108 obj = self.object_expr.resolve(context)
109 except template.VariableDoesNotExist:
110 return None, None
111 return ContentType.objects.get_for_model(obj), obj.pk
112 else:
113 return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True)
114
115 def get_context_value_from_queryset(self, context, qs):
116 """Subclasses should override this."""
117 raise NotImplementedError
118
119
120 class CommentListNode(BaseCommentNode):
121 """Insert a list of comments into the context."""
122
123 def get_context_value_from_queryset(self, context, qs):
124 return qs
125
126
127 class CommentCountNode(BaseCommentNode):
128 """Insert a count of comments into the context."""
129
130 def get_context_value_from_queryset(self, context, qs):
131 return qs.count()
132
133
134 class CommentFormNode(BaseCommentNode):
135 """Insert a form for the comment model into the context."""
136
137 def get_form(self, context):
138 obj = self.get_object(context)
139 if obj:
140 return django_comments.get_form()(obj)
141 else:
142 return None
143
144 def get_object(self, context):
145 if self.object_expr:
146 try:
147 return self.object_expr.resolve(context)
148 except template.VariableDoesNotExist:
149 return None
150 else:
151 object_pk = self.object_pk_expr.resolve(context,
152 ignore_failures=True)
153 return self.ctype.get_object_for_this_type(pk=object_pk)
154
155 def render(self, context):
156 context[self.as_varname] = self.get_form(context)
157 return ''
158
159
160 class RenderCommentFormNode(CommentFormNode):
161 """Render the comment form directly"""
162
163 @classmethod
164 def handle_token(cls, parser, token):
165 """Class method to parse render_comment_form and return a Node."""
166 tokens = token.split_contents()
167 if tokens[1] != 'for':
168 raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
169
170 # {% render_comment_form for obj %}
171 if len(tokens) == 3:
172 return cls(object_expr=parser.compile_filter(tokens[2]))
173
174 # {% render_comment_form for app.models pk %}
175 elif len(tokens) == 4:
176 return cls(
177 ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),
178 object_pk_expr=parser.compile_filter(tokens[3])
179 )
180
181 def render(self, context):
182 ctype, object_pk = self.get_target_ctype_pk(context)
183 if object_pk:
184 template_search_list = [
185 "comments/%s/%s/form.html" % (ctype.app_label, ctype.model),
186 "comments/%s/form.html" % ctype.app_label,
187 "comments/form.html"
188 ]
189 context_dict = context.flatten()
190 context_dict['form'] = self.get_form(context)
191 formstr = render_to_string(template_search_list, context_dict)
192 return formstr
193 else:
194 return ''
195
196
197 class RenderCommentListNode(CommentListNode):
198 """Render the comment list directly"""
199
200 @classmethod
201 def handle_token(cls, parser, token):
202 """Class method to parse render_comment_list and return a Node."""
203 tokens = token.split_contents()
204 if tokens[1] != 'for':
205 raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
206
207 # {% render_comment_list for obj %}
208 if len(tokens) == 3:
209 return cls(object_expr=parser.compile_filter(tokens[2]))
210
211 # {% render_comment_list for app.models pk %}
212 elif len(tokens) == 4:
213 return cls(
214 ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),
215 object_pk_expr=parser.compile_filter(tokens[3])
216 )
217
218 def render(self, context):
219 ctype, object_pk = self.get_target_ctype_pk(context)
220 if object_pk:
221 template_search_list = [
222 "comments/%s/%s/list.html" % (ctype.app_label, ctype.model),
223 "comments/%s/list.html" % ctype.app_label,
224 "comments/list.html"
225 ]
226 qs = self.get_queryset(context)
227 context_dict = context.flatten()
228 context_dict['comment_list'] = self.get_context_value_from_queryset(context, qs)
229 liststr = render_to_string(template_search_list, context_dict)
230 return liststr
231 else:
232 return ''
233
234
235 # We could just register each classmethod directly, but then we'd lose out on
236 # the automagic docstrings-into-admin-docs tricks. So each node gets a cute
237 # wrapper function that just exists to hold the docstring.
238
239 @register.tag
240 def get_comment_count(parser, token):
241 """
242 Gets the comment count for the given params and populates the template
243 context with a variable containing that value, whose name is defined by the
244 'as' clause.
245
246 Syntax::
247
248 {% get_comment_count for [object] as [varname] %}
249 {% get_comment_count for [app].[model] [object_id] as [varname] %}
250
251 Example usage::
252
253 {% get_comment_count for event as comment_count %}
254 {% get_comment_count for calendar.event event.id as comment_count %}
255 {% get_comment_count for calendar.event 17 as comment_count %}
256
257 """
258 return CommentCountNode.handle_token(parser, token)
259
260
261 @register.tag
262 def get_comment_list(parser, token):
263 """
264 Gets the list of comments for the given params and populates the template
265 context with a variable containing that value, whose name is defined by the
266 'as' clause.
267
268 Syntax::
269
270 {% get_comment_list for [object] as [varname] %}
271 {% get_comment_list for [app].[model] [object_id] as [varname] %}
272
273 Example usage::
274
275 {% get_comment_list for event as comment_list %}
276 {% for comment in comment_list %}
277 ...
278 {% endfor %}
279
280 """
281 return CommentListNode.handle_token(parser, token)
282
283
284 @register.tag
285 def render_comment_list(parser, token):
286 """
287 Render the comment list (as returned by ``{% get_comment_list %}``)
288 through the ``comments/list.html`` template
289
290 Syntax::
291
292 {% render_comment_list for [object] %}
293 {% render_comment_list for [app].[model] [object_id] %}
294
295 Example usage::
296
297 {% render_comment_list for event %}
298
299 """
300 return RenderCommentListNode.handle_token(parser, token)
301
302
303 @register.tag
304 def get_comment_form(parser, token):
305 """
306 Get a (new) form object to post a new comment.
307
308 Syntax::
309
310 {% get_comment_form for [object] as [varname] %}
311 {% get_comment_form for [app].[model] [object_id] as [varname] %}
312 """
313 return CommentFormNode.handle_token(parser, token)
314
315
316 @register.tag
317 def render_comment_form(parser, token):
318 """
319 Render the comment form (as returned by ``{% render_comment_form %}``) through
320 the ``comments/form.html`` template.
321
322 Syntax::
323
324 {% render_comment_form for [object] %}
325 {% render_comment_form for [app].[model] [object_id] %}
326 """
327 return RenderCommentFormNode.handle_token(parser, token)
328
329
330 @register.simple_tag
331 def comment_form_target():
332 """
333 Get the target URL for the comment form.
334
335 Example::
336
337 <form action="{% comment_form_target %}" method="post">
338 """
339 return django_comments.get_form_target()
340
341
342 @register.simple_tag
343 def get_comment_permalink(comment, anchor_pattern=None):
344 """
345 Get the permalink for a comment, optionally specifying the format of the
346 named anchor to be appended to the end of the URL.
347
348 Example::
349 {% get_comment_permalink comment "#c%(id)s-by-%(user_name)s" %}
350 """
351
352 if anchor_pattern:
353 return comment.get_absolute_url(anchor_pattern)
354 return comment.get_absolute_url()