【问题标题】:How to add markdown editor to custom django comment?如何将降价编辑器添加到自定义 django 评论?
【发布时间】:2014-03-07 01:01:48
【问题描述】:

我是 django 的新手并创建了一个简单的博客应用程序,现在尝试将 markdown 添加到 cmets:

这里是评论的模型:

class Comment(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    author = models.CharField(max_length=60)
    body = models.TextField()
    post = models.ForeignKey(Blog)

    def __unicode__(self):
        return unicode("%s: %s" % (self.post, self.body[:60]))

在 post.html 中,我有:

<!-- Add Comments  -->

    {% if user.is_authenticated %}
        <div id="addc">Your Comment?</div>
        <!-- Comment form  -->
        <form action="{% url "blog.views.add_comment" post.id %}" method="POST">{% csrf_token %}
            <div id="comment-form">
                <p>{{ form.body }}</p>
            </div>
            <div id="submit"><input type="submit" value="Submit"></div>
        </form>
    {% endif %}

以及呈现帖子(和评论)的视图:

def post_withslug(request, post_slug):
    post = Blog.objects.get(slug = post_slug)
    comments = Comment.objects.filter(post=post)
    d = dict(post=post, comments=comments, form=CommentForm(), user=request.user)
    d.update(csrf(request))
    return render_to_response("blog/post.html", d)    

在 form.py 我有:

from django_markdown.widgets import MarkdownWidget

class CommentForm(forms.ModelForm):
    body = forms.CharField(widget=MarkdownWidget())
    class Meta:
        model= Comment
        fields= ('body',) 

我已将 django-markdown 用于管理后端,它在那里运行良好,但我不确定如何将此应用程序(或其他具有相同效果的应用程序)应用到博客 cmets,我找不到任何关于它的教程. 非常感谢您的帮助。

【问题讨论】:

  • 您是想为 cmets 使用 markdown 编辑器还是仅仅为了让 markdown 正确显示?
  • 我想添加markdown编辑器,以便用户可以用基本的html标签装饰他们的评论。
  • 你不需要编辑cmets来包含markdown;编辑器只是为不知道如何自己做的用户添加降价。例如,Stackoverflow cmets 支持 markdown,但不使用编辑器。
  • 好吧,我假设我的大多数用户不知道如何直接使用降价,因此需要编辑器/按钮。

标签: django markdown


【解决方案1】:

您需要为您的 Comment 模型编写自定义表单

cmets/forms.py

from django_markdown.widgets import MarkdownWidget
...
class CommentForm(forms.Form):
    body = forms.CharField( widget=MarkdownWidget() )

markdown 小部件负责将编辑器所需的 js 和 css 添加到页面,假设您没有在模板中明确定义资源,但您的表单或视图需要将评论与正确的帖子和用户相关联。

在显示方面,您需要在显示 cmets 时使用 markdown 模板标签

cmets/templates/comment.html

{% load django_markdown %}
...
{{ comment.author }} //etc
{{ comment.body|markdown }}

【讨论】:

  • 我遵循了您的指南,运行 collectstatic 并重新启动了网络服务器,但没有添加到评论表单中。我也没有错误。评论表单上的直接降价也没有任何效果。我可能错过了什么?
  • 您是否在视图中使用自定义表单?
  • 是的,我用 views.py 和 form.py 的相关部分更新了问题。
  • 显然,您还需要在页面中包含表单媒体。看到这个答案 - stackoverflow.com/a/1559034/44816
  • 将form.media 添加到您的页面是否解决了问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
相关资源
最近更新 更多