簡體   English   中英

如何將Markdown編輯器添加到自定義Django評論?

[英]How to add markdown editor to custom django comment?

我是django的新手,並創建了一個簡單的博客應用,現在嘗試在評論中添加markdown:

這是評論模型:

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用於管理后端,並且在那里可以正常工作,但是我不確定如何將此應用程序(或其他具有相同效果的東西)應用於博客評論,並且找不到任何有關它的教程。 因此,感謝您的幫助。

您需要為Comment模型編寫一個自定義表格

評論/ forms.py

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

假設您沒有在模板中顯式定義資源,但是markdown小部件將為編輯器添加必要的js和css到頁面,但是您的表單或視圖需要將評論與正確的帖子和用戶相關聯。

在顯示方面,顯示評論時需要使用markdown templatetag

評論/模板/ comment.html

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM