如何在同一网站上发帖添加评论?

时间:2016-09-08 21:02:13

标签: django

我创建了博客和评论每篇文章的可能性。但现在我在两个不同的网站上拥有它。在页面上发布我有链接到我的评论表单,我在那里创建评论。是否可以在此帖子中添加表单?

所以我想有post_detail,表单在同一个网站上添加新的评论和评论。现在我只发帖和评论。

views.py:

def comment_new(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect(post_detail, pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/post_detail.html', {'form': form})

模板: post_detail.html(部分评论内容):

<a class="btn btn-default" href="{% url 'comment_new' pk=post.pk %}">Add comment</a>

{% for comment in post.comments.all %}
    {{ comment.created_date }}
    <strong>{{ comment.author }}</strong>
    {{ comment.text }}
{% endfor %}

comment_new.html

<form method="POST">{% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Send</button>
</form>

urls.py:

url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
url(r'^post/(?P<pk>[0-9]+)/comment/$', views.comment_new, name='comment_new'),

models.py

class Category(models.Model):
    name = models.CharField(unique=True)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Categories'

class Post(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(unique=True)
    text = models.TextField(max_length=256)
    source = models.CharField(max_length=64)
    photo = models.ImageField(upload_to='photos/')
    created_date = models.DateTimeField(
            default=timezone.now)

    def __unicode__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    author = models.CharField(max_length=64)
    text = models.TextField(max_length=1028)
    created_date = models.DateTimeField(
            default=timezone.now)

0 个答案:

没有答案