diff --git a/django/contrib/comments/templatetags/comments.py b/django/contrib/comments/templatetags/comments.py index 42691c63e4..8bc61cd445 100644 --- a/django/contrib/comments/templatetags/comments.py +++ b/django/contrib/comments/templatetags/comments.py @@ -122,12 +122,23 @@ class CommentFormNode(BaseCommentNode): """Insert a form for the comment model into the context.""" def get_form(self, context): - ctype, object_pk = self.get_target_ctype_pk(context) - if object_pk: - return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk)) + obj = self.get_object(context) + if obj: + return comments.get_form()(obj) else: return None + def get_object(self, context): + if self.object_expr: + try: + return self.object_expr.resolve(context) + except template.VariableDoesNotExist: + return None + else: + object_pk = self.object_pk_expr.resolve(context, + ignore_failures=True) + return self.ctype.get_object_for_this_type(pk=object_pk) + def render(self, context): context[self.as_varname] = self.get_form(context) return '' diff --git a/tests/regressiontests/comment_tests/tests/templatetag_tests.py b/tests/regressiontests/comment_tests/tests/templatetag_tests.py index 4c90d9d208..0ead6c2257 100644 --- a/tests/regressiontests/comment_tests/tests/templatetag_tests.py +++ b/tests/regressiontests/comment_tests/tests/templatetag_tests.py @@ -40,6 +40,11 @@ class CommentTemplateTagTests(CommentTestCase): def testRenderCommentFormFromObject(self): self.testRenderCommentForm("{% render_comment_form for a %}") + def testRenderCommentFormFromObjectWithQueryCount(self): + def test(): + self.testRenderCommentFormFromObject() + self.assertNumQueries(1, test) + def testGetCommentCount(self, tag=None): self.createSomeComments() t = "{% load comments %}" + (tag or "{% get_comment_count for comment_tests.article a.id as cc %}") + "{{ cc }}"