Django做一个简单的博客系统(12)----发表评论

前言

    添加一个发表评论功能.
    感谢大神的教程:Django搭建个人博客.

一.准备工作

    发表评论是一个相对独立的功能,所以再创建一个app:

python manager.py startapp comment

    然后在settings中注册这个app:

INSTALLED_APPS = [
    ...
    'comment',
]

    修改一下时间,还是在settings.py中:

TIME_ZONE = 'Asia/Shanghai'

    在Personal_blog中注册路由:
Personal_blog/urls.py

...
urlpatterns = [
    ...
    # 评论
    path('comment/', include('comment.url', namespace='comment')),
]
...

注:这里有很关键的一步,在注册好路由后,需要在comment目录下创建一个url.py文件,然后这个文件里一定要写上app_name = ‘comment’,要不然会报错的:

from django.urls import path,re_path
from comment import views

app_name = 'comment'    # 正在部署的应用的名称

urlpatterns = []

    准备工作就绪后,接下来就来实现发表评论功能.

二.发表评论

1.编写模型

comment/models.py:

from django.db import models
from django.contrib.auth.models import User
from article.models import ArticlePost

# Create your models here.

# 模型中有2个外键:
# article是被评论的文章
# user是评论的发布者
# 博文的评论
class Comment(models.Model):
    article = models.ForeignKey(
        ArticlePost,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return self.body[:20]

这里别忘了进行数据迁移

python manager.py makemigrations
python manager.py migrate

2.编写评论表单

comment/forms.py:

from django import forms
from comment.models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        # 因为模型中的两个外键将通过视图逻辑自动填写,
        # 所以这里只需要提交body就足够了
        model = Comment
        fields = ['body']

3.配置url

comment/url.py:

from django.urls import path,re_path
from comment import views

app_name = 'comment'    # 正在部署的应用的名称

urlpatterns = [
    # 发表评论
    path('post-comment/',views.post_comment,name='post_comment'),
]

4.编写视图函数

comment/views.py:

from django.shortcuts import render,get_object_or_404,redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from comment.models import Comment
from comment.form import CommentForm
from article.models import ArticlePost

# Create your views here.

# 文章评论
@login_required(login_url='/userprofile/login/')
def post_comment(request,article_id):
    article = get_object_or_404(ArticlePost,id=article_id)

    # 处理 POST 请求
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.article = article
            new_comment.user = request.user
            new_comment.save()
            return redirect(article)
        else:
            return HttpResponse("表单内容有误,请重新填写。")
    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求。")

5.修改文章模型

    在文章模型中添加get_absolute_url()方法:
article/models.py:

from django.db import models

# 导入内建的User模型
from django.contrib.auth.models import User
# timezone用于处理时间相关事务
from django.utils import timezone
from django.urls import reverse

# Create your models here.

# 博客文章数据类型
# 包括:文章作者,文章标题,文章正文,文章创建时间,文章更新时间
class ArticlePost(models.Model):
	...
	# 添加下面这个函数
    # 获取文章地址
    def get_absolute_url(self):
        return reverse('article:article_detail',args=[self.id])

6.修改文章详情视图

article/views.py:

...
from comment.models import Comment

def article_detail(request, id):
    # 已有代码
    article = ArticlePost.objects.get(id=id)

    # 取出文章评论
    comments = Comment.objects.filter(article=id)
    ...

    # 添加comments上下文
    context = {
      'article': article, 'toc': md.toc, 'comments': comments }

    ...

7.修改文章详情模板

templates/article/detail.html:


{% extends "base.html" %}
{#加载静态文件#}
{% load staticfiles %}


{#写入title#}
{% block title %}
    文章详情
{% endblock %}

{#写入自定义content#}
{% block content %}
    <div class="container">
        <div class="row">
            
            <h1 class="col-12 mt-4 mb-4">{
    { article.title }}h1>
            <div class="col-12 alert alert-success">
            <div>
                作者:{
    { article.author }}
                {% if user == article.author %}
                    · <a href="#" onclick="confirm_delete()">删除文章a>
                    · 
                        编辑文章
                    a>
                {% endif %}
            div>
                <div>
                    浏览:{
    { article.total_views }}
                div>
            div>

            
            <div class="col-12">
                <p>{
    { article.body|safe }}p>
            div>
        div>
        
    <hr>
    {% if user.is_authenticated %}
        <div>
            <form
                action="{% url 'comment:post_comment' article.id %}"
                method="POST"
            >
            {% csrf_token %}
                <div class="form-group">
                    <label for="body">
                        <strong>
                            我也要发言:
                        strong>
                    label>
                    <textarea
                        type="text"
                        class="form-control"
                        id="body"
                        name="body"
                        rows="2">textarea>
                div>
                
                <button type="submit" class="btn btn-primary ">发送button>
            form>
        div>
        <br>
    {% else %}
        <br>
        <h5 class="row justify-content-center"><a href="{% url 'userprofile:login' %}">登录a>后回复
        h5>
        <br>
    {% endif %}



    
    <h4>共有{
    { comments.count }}条评论h4>
    <div>
        {% for comment in comments %}
            <hr>
            <p>
                <strong style="color: pink">
                    {
    { comment.user }}
                strong><span style="color: green">
                    {
    { comment.created|date:"Y-m-d H:i:s" }}
                span> 时说:
            p>
            <pre style="font-family: inherit; font-size: 1em;">
{
    { comment.body }}pre>
        {% endfor %}
    div>
    div>



    {#   新增一个隐藏的表单 #}
    <form
        style="display:none;"
        id="safe_delete"
        action="{% url 'article:article_safe_delete' article.id %}"
        method="POST"
        >
        {% csrf_token %}
        <button type="submit">发送button>
    form>


    <script>
        {
      # 删除文章函数       #}
            function confirm_safe_delete() {
      
                layer.open({
      
                    title: "确认删除",
                    content: "确认删除这篇文章吗?",
                    yes: function(index, layero) {
      
                        $('form#safe_delete button').click();
                        layer.close(index);
                    }
                })
            }
    script>

{% endblock %}

    这样,一个简单的评论功能就完成了.

写在最后

    本文是个人的一些学习笔记,如有侵权,请及时联系我进行删除,谢谢大家.

你可能感兴趣的:(python,Django)