Code

Ticket #15904: render_comments_form_query_count.diff

File render_comments_form_query_count.diff, 2.1 KB (added by stefanw, 3 years ago)

Patch and Test

Line 
1diff --git a/django/contrib/comments/templatetags/comments.py b/django/contrib/comments/templatetags/comments.py
2index 42691c6..8bc61cd 100644
3--- a/django/contrib/comments/templatetags/comments.py
4+++ b/django/contrib/comments/templatetags/comments.py
5@@ -122,12 +122,23 @@ class CommentFormNode(BaseCommentNode):
6     """Insert a form for the comment model into the context."""
7 
8     def get_form(self, context):
9-        ctype, object_pk = self.get_target_ctype_pk(context)
10-        if object_pk:
11-            return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk))
12+        obj = self.get_object(context)
13+        if obj:
14+            return comments.get_form()(obj)
15         else:
16             return None
17 
18+    def get_object(self, context):
19+        if self.object_expr:
20+            try:
21+                return self.object_expr.resolve(context)
22+            except template.VariableDoesNotExist:
23+                return None
24+        else:
25+            object_pk = self.object_pk_expr.resolve(context,
26+                    ignore_failures=True)
27+            return self.ctype.get_object_for_this_type(pk=object_pk)
28+
29     def render(self, context):
30         context[self.as_varname] = self.get_form(context)
31         return ''
32diff --git a/tests/regressiontests/comment_tests/tests/templatetag_tests.py b/tests/regressiontests/comment_tests/tests/templatetag_tests.py
33index 4c90d9d..0ead6c2 100644
34--- a/tests/regressiontests/comment_tests/tests/templatetag_tests.py
35+++ b/tests/regressiontests/comment_tests/tests/templatetag_tests.py
36@@ -40,6 +40,11 @@ class CommentTemplateTagTests(CommentTestCase):
37     def testRenderCommentFormFromObject(self):
38         self.testRenderCommentForm("{% render_comment_form for a %}")
39 
40+    def testRenderCommentFormFromObjectWithQueryCount(self):
41+        def test():
42+            self.testRenderCommentFormFromObject()
43+        self.assertNumQueries(1, test)
44+
45     def testGetCommentCount(self, tag=None):
46         self.createSomeComments()
47         t = "{% load comments %}" + (tag or "{% get_comment_count for comment_tests.article a.id as cc %}") + "{{ cc }}"