Начав изучение Django и сделав простейший блог, решил подключить стандартные комментарии фреймворка Django. django.contrib.comments
Исходные данные:
models.py
from django.db import models
from django.contrib import admin
class BlogPost(models.Model):
title = models.CharField(max_length=150)
short_body = models.TextField()
body = models.TextField()
timestamp = models.DateTimeField()
logo = models.ImageField(upload_to="static/")
class Meta:
ordering = ("-timestamp",)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ("id", "title", "timestamp")
admin.site.register(BlogPost, BlogPostAdmin)
urls.py
from django.conf.urls.defaults import *
from blog.views import archive
urlpatterns = patterns("", url(r"^$", archive), )
views.py
from django.template import loader, Context
from django.http import HttpResponse
from blog.models import BlogPost
def archive(request):
posts = BlogPost.objects.all()
t = loader.get_template("archive.html")
c = Context({"posts": posts })
return HttpResponse(t.render(c))
и два шаблона для отображения записей блога (base.html, archive.html. Указал тот, который имеет отношение к теме)
archive.html
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<div>
<h2>{{ post.timestamp }} : {{ post.title }}</h2>
<div class='bloglogo'><img src='/static/{{ post.logo }}'></div>
<div class='bloginfo'>
<p>{{ post.timestamp }}</p>
<p>{{ post.short_body }}</p>
<div>
</div>
<div style='clear:left'> </div>
{% endfor %}
<p><small>Yunin Ivan 2010 ©</small></p>
{% endblock%}
Для подключения стандартных комментариев необходимо:
urls.py
Добавляем строку
(r"^comments/", include("django.contrib.comments.urls")),
archive.html
Добавляем:
- {% load comments %} - Загрузка комментариев
- {% get_comment_count for post as comment_count %} - получаем количество комментариев для объекта post (в нашем случае — запись блога)
- Комментарии: [{{ comment_count }}] - Вывожу кол-во комментариев для записи блога
- {% render_comment_form for post %} - выводим стандартную форму для добавления комментариев
В моем случае, archive.html выглядит так:
{% extends "base.html" %}
{% load comments %}
{% block content %}
{% for post in posts %}
{% get_comment_count for post as comment_count %}
<div>
<h2>{{ post.timestamp }} : {{ post.title }}</h2>
<div class='bloglogo'><img src='/static/{{ post.logo }}'></div>
<div class='bloginfo'>
<p>{{ post.timestamp }}</p>
<p>{{ post.short_body }}</p>
<div>
</div>
<div style='clear:left'> </div>
<small onClick='onSmall({{ post.id }})' style='text-aling: right;'>Комментарии: [{{ comment_count }}]</small>
<div id='comment{{ post.id }}' style='display: none;'>
{% render_comment_form for post %}
</div>
{% endfor %}
<p><small>Yunin Ivan 2010 ©</small></p> {% endblock%}
Форма комментариев появилась. При попытке оставить комментарий, получаем ошибку:
CSRF verification failed. Request aborted.
Причина в том, что обработчик формы не смог обнаружить скрытое поле csrfmiddlewaretoken, которое используется для защиты форм от подделок межсайтовых запросов.
Чтобы скрытое поле csrfmiddlewaretoken появилось в нашей форме, необходимо сделать следующее:
Добавить во views.py (выделено жирным)
**from django.core.context_processors import csrf**
def archive(request):
posts = BlogPost.objects.all()
t = loader.get_template("archive.html")
c = Context({"posts": posts })
**c.update(csrf(request)) **
return HttpResponse(t.render(c))
Теперь в блоге есть возможность добавлять комментарии.