我的博客开发(015)

实现评论功能的方式有:

  1. 第三方社会化评论插件
  2. Django评论库:django-comment
  3. 自己写代码实现(我们要使用的方法)

首先需要创建评论模型:

  • 评论对象
  • 评论内容
  • 评论时间
  • 评论者

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
迁移
登陆后台查看效果:
我的博客开发(015)_第1张图片
评论一般在浏览时要显示评论和提交评论,所以需要写前端代码:

但是考虑到评论是要权限的,必须先登录才能评论,目的有三个:

  • 确保较低程度减少垃圾评论
  • 提高评论门槛(第三方登录解决)
  • 还可以通知用户

**pycharm技能:ctrl+shift+F:用于全局替换

django文档地址:www.djangoproject.com**
我的博客开发(015)_第2张图片
方法如下:

blog/blog_detail.html

            
                
                    提交评论区域                     {% if user.is_authenticated %}                         已登录                     {% else %}                         未登录                         
                            {% csrf_token %}                                                                                                                
                    {% endif %}                 
                
评论列表区域
            
        

注意:csrf会自动验证,需要我们添加{% csfr_token%}来验证(只有render没问题,render_to_response会出错)
我的博客开发(015)_第3张图片
在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 %}

效果:

已登录效果:
我的博客开发(015)_第4张图片
但是如果登出后再查看博文发现有问题:

记录在madpecker中了
我的博客开发(015)_第5张图片

再mysite/urls.py中新增路由:
我的博客开发(015)_第6张图片


但现在登录以后还是无法编辑评论以及提交

你可能感兴趣的:(javascript,html,css,python,django)