实现评论功能的方式有:
- 第三方社会化评论插件
- Django评论库:django-comment
- 自己写代码实现(我们要使用的方法)
首先需要创建评论模型:
- 评论对象
- 评论内容
- 评论时间
- 评论者
python manage.py startapp comment
models.py中新增评论模块:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
# Create your models here.
class Comment(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
text = models.TextField()
comment_time = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
写admin.py
from django.contrib import admin
from .models import Comment
# Register your models here.
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('content_object', 'text', 'comment_time', 'user')
注册应用:settings
迁移
登陆后台查看效果:
评论一般在浏览时要显示评论和提交评论,所以需要写前端代码:
但是考虑到评论是要权限的,必须先登录才能评论,目的有三个:
- 确保较低程度减少垃圾评论
- 提高评论门槛(第三方登录解决)
- 还可以通知用户
**pycharm技能:ctrl+shift+F:用于全局替换
django文档地址:www.djangoproject.com**
方法如下:
blog/blog_detail.html
<div class="row">
<div class="col-xs-10 col-xs-offset-1">
<div style="margin-top:2em;border:1px dashed;padding:2em;">
提交评论区域
{% if user.is_authenticated %}
已登录
{% else %}
未登录
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="登录">
</form>
{% endif %}
</div>
<div style="margin-top:2em;border:1px dashed;padding:2em;">评论列表区域</div>
</div>
</div>
注意:csrf会自动验证,需要我们添加{% csfr_token%}来验证(只有render没问题,render_to_response会出错)
在mysite/views.py中新建login方法:
# mysite/views.py
from django.shortcuts import render,redirect
from django.contrib import auth
def login(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
return render(request, 'error.html', {'message':'用户名或密码不正确'})
在公共的模板templates中新建error.html
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %}
我的网站|错误
{% endblock %}
{% block nav_home_active %}active{% endblock %}
{% block content %}
{{ message }}
{% endblock %}
效果:
已登录效果:
但是如果登出后再查看博文发现有问题:
记录在madpecker中了
再mysite/urls.py中新增路由:
但现在登录以后还是无法编辑评论以及提交
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。