【问题标题】:How to use Django build-in comment framework on any template如何在任何模板上使用 Django 内置评论框架
【发布时间】:2013-01-25 04:30:47
【问题描述】:

我刚开始研究 Django 内置 cmets 函数。起初我认为评论模板应该可以在任何页面上正常工作,只需 get_comment_formrender_comment_form 。但现在当我将这些代码添加到普通页面时真的很烦人。它不起作用。也许换句话说。当涉及到普通页面时,我不知道如何指定要附加的对象。以下是详细信息:

models.py
class Entry(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    pub_date = models.DateTimeField()
    enable_comments = models.BooleanField()

urls.py
urlpatterns = patterns('',
url(r'^profile/','django.views.generic.simple.direct_to_template',{
        'template' : 'admin_ryu_blog/profile.html'},name='profile'),
)

现在我只想在模板 profile.html 上使用评论框架。我该怎么办 ?您现在可以将 profile.html 视为空白页面。如果您可以使用内置评论框架显示评论表单,则可以添加任何您想要的代码。

顺便说一句,我尝试了以下方法:

{% load comments %}
{% render_comment_form for profile %} 

然后它会提示错误消息。与我之前的问题相同的回溯。 点击here

【问题讨论】:

    标签: django django-templates django-comments


    【解决方案1】:

    你不能。 cmets 框架需要一个对象来引用。

    但想到的一个简单的解决方案是构建一个映射到如下 URL 的模型:

    class CommentAnchor(models.Model):
        path = models.CharField(max_length=256)
    

    构建一个context processor 来构建这些对象并将它们添加到所有模板上下文中。记得将你的上下文处理器添加到你的settings.TEMPLATE_CONTEXT_PROCESSORS,并记得在渲染模板时使用RequestContext

    def CommentAnchorProcessor(request):
        comment_anchor, created = CommentAnchor.objects.get_or_create(path=request.path)
        return {
            'comment_anchor': comment_anchor,  # now, this is available in every template.
        }
    

    现在您可以通过这些新对象渲染 cmets。

    {% render_comment_form for comment_anchor %} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多