基于django的个人博客网站建立(三)

2023-01-31 00:01:36 django 建立 博客网站

前言

今天主要完成的是文章在页面的显示以及评论,留言

具体内容

首先我希望主页面是显示我的所有文章,于是在主页面的视图函数中返回了所有的文章对象:


def index(request):
    if request.method == 'GET':
        all_article = models.Article.objects.all().order_by('id').reverse()
        all_type = models.ArticleType.objects.all()
        return render(request, 'show/index.html',{'all_article':all_article,'all_type':all_type})

all_type为所有的的文章类别,用于导航条的显示,之后就可以遍历所有的文章对象在主页显示了:


{% extends "show/base.html" %}
      <!-- ======================== END HEADER AREA HERE ================================= -->
      <!-- =================== START MaiN CONTENT AREA HERE ========================-->
{% block main %}
      <main class="main-content-area section-padding-bottom">
         <div class="container">
            <div class="row">
               <div class="col-md-12">
                  <div class="row">
                     {% for article in all_article %}
                     <div class="col-md-10 mx-auto nagative-margin" data-aos="fade">
                        <div class="themeix-single-post">
                           <div class="left-post-number float-left">
                              <div class="post-number"><span>{{ article.id }}</span></div>

                           </div>
                           <div class="right-blog-details ">
                              <div class="blog-meta">
                                 <p>{{ article.creationTime }}</p>
                                  {% for type in article.articletotype_set.all %}
                                 <p>{{ type.type.name }}</p>
                                  {% endfor %}
                              </div>
                              <div class="blog-title pb-3 pt-1">
                                 <h2 class="heading-2"><a href="/blog-details/?article_id={{ article.id }}">{{ article.title }}</a></h2>
                              </div>

                              <div class="blog-thumb mb-0">
                                 <a href="/blog-details/?article_id={{ article.id }}"><img src="/static/assets/images/article/{{ article.id }}.jpg" alt="post" /></a>
                              </div>

                           </div>
                        </div>
                     </div>
                     {% endfor %}

                  </div>
               </div>
            </div>
            <div class="post-pagination text-center" data-aos="fade-up">
             <ul>
               <li><a href="#"><i class="fa fa-angle-double-left" aria-hidden="true"></i></a></li>
               <li><a href="#">01</a></li>
               <li><a href="#">02</a></li>
               <li><a href="#">03</a></li>
               <li><a href="#"><i class="fa fa-angle-double-right" aria-hidden="true"></i></a></li>
             </ul>
            </div>

         </div>
      </main>
      <!-- ======================== END MAIN CONTENT AREA HERE ========================-->
      <!-- ==================== START FOOTER AREA ===================================== -->
{% endblock %}

由于只显示标题有一点空,就是感觉少些什么,于是我在写文章时添加了配图,怎么添加配图具体就不说了,结果为:

在主页面,可以点击进入查看具体的文章,发的是get请求,参数是文章id:


def blog_details(request):
    if request.method == 'GET':
        all_type = models.ArticleType.objects.all()
        article_id = request.GET.get('article_id')
        article_obj = models.Article.objects.filter(id=article_id).first()
        return render(request,'show/blog-details.html',{'article_obj':article_obj,'all_type':all_type})

返回的是文章对象,通过这一个文章对象来显示内容,由于之前通过markdown模块渲染成了html,所以文章内容直接显示就行


{% extends "show/base.html" %}
      <!-- ======================== END HEADER AREA HERE ================================= -->
      <!-- =================== START MAIN CONTENT AREA HERE ========================-->

{% block link %}
    <style>
    code {

    color: black;
    background: none;
    text-shadow: 0 1px white;
    font-family: Consolas, Monaco, 'Andale Mono', 'ubuntu Mono', monospace;
    font-size: 1em;
    text-align: left;
    white-space: pre;
    Word-spacing: nORMal;
    word-break: normal;
    word-wrap: normal;
    line-height: 1.5;
    -moz-tab-size: 4;
    -o-tab-size: 4;
    tab-size: 4;
    -WEBkit-hyphens: none;
    -moz-hyphens: none;
    -ms-hyphens: none;
    hyphens: none;
}

    </style>
{% endblock %}
{% block main %}
      <!-- ======================== END HEADER AREA HERE ================================= -->
      <!-- =================== START MAIN CONTENT AREA HERE ========================-->
      <main class="main-content-area section-padding-bottom">
         <div class="container">
            <div class="row">
               <div class="col-md-12">
                  <div class="row">
                     <div class="col-md-10 mx-auto n-margin">
                        <div class="entry-content">
                            <h1 class="text-center" >{{ article_obj.title }}</h1>
                            {{ article_obj.htmlContent|safe }}

                           </div>
                        <div class="tags-social-meta mb-5 row">
                           <div class="col-md-6">
                              <div class="tags">
                                 <span class="float-left"><i class="fa fa-tag" aria-hidden="true"></i> 分类:</span>
                                 <ul class="list-inline">
                                     {% for type in article_obj.articletotype_set.all %}
                                         <li class="list-inline-item"><a href="#">{{ type.type.name }}</a></li>

                                  {% endfor %}
                                 </ul>
                              </div>
                           </div>
                           <div class="col-md-6">

                           </div>
                        </div>

                        <div class="comment-wrapper mb-5">
                           <div class="section-title pb-3">
                              <h3 class="heading-3">{{ article_obj.comment_set.all.count }} Comments</h3>
                           </div>
                           <div class="themeix-comments">
                                {% for comment in article_obj.comment_set.all %}
                              <div class="comments-details">
                                 <div class="author-image">
                                    <a href="author.html"><img src="https://gravatar.com/avatar/{{ comment.email_hash }}?d=wavatar" alt="" /></a>
                                 </div>
                                 <div class="comment-text  pb-5">
                                    <div class="c-title">
                                       <p><a href="#">{{ comment.userName }}</a> <span class="ml-1">{{ comment.creationTime }}</span></p>
                                    </div>
                                    <div class="c-content">
                                       <p>{{ comment.content }}</p>
                                    </div>

                                 </div>
                              </div>
                                {% endfor %}

                           </div>
                        </div>
                        <div class="comment-wrapper">
                           <div class="section-title mb-4 mt-4">
                              <h3 class="heading-3">Post a Comment</h3>
                           </div>
                           <div class="comment-form">
                                 <form action="/article_comment/" method="post">
                                       <div class="form-row">
                                 <div class="col-md-6">
                                <div class="input-group"><input name="username" type="text" placeholder="Your Name" /></div>
                              </div>
                              <div class="col-md-6">
                                <div class="input-group"><input name="email" type="text" placeholder="Your Email" class="float-right" /></div>
                              </div>
                             </div>
                              <div class="form-row"><div class="col-md-12"><div class="form-group"><textarea name="content" placeholder="Type Comment"></textarea></div></div></div>
                                       <input type="hidden" name="article_id" value="{{ article_obj.id }}">
                                       <div class="form-row"><button type="submit" class="btn-submit mt-2">Add Comment</button></div>
                                     {% csrf_token %}
                                 </form>                         
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </main>
      <!-- ======================== END MAIN CONTENT AREA HERE ========================-->
      <!-- ==================== START FOOTER AREA ===================================== -->
{% endblock %}

{% block script %}
    <script>
    window.onload=function() {

        var lables = document.querySelectorAll('code')
        lables.forEach(function (lable) {
            var ele = document.createElement('pre')
            lable.parentnode.replaceChild(ele, lable)
            ele.appendChild(lable)

        })
        $('pre').addClass('language-python mb-60')
        $('code').addClass('language-Python')
    }
    </script>
{% endblock %}

最下方的js代码是为code元素添加pre父元素,这样可以使markdown文章中的代码部分显示的更友好,具体页面为:

接下来是评论功能,先看一下页面:

目前是只有一级评论内容,评论者需要输入username,email和content,创建的评论表为:


class Comment(models.Model):
    userName = models.CharField(max_length=128)
    email = models.CharField(max_length=128)
    content = models.TextField()
    email_hash = models.CharField(max_length=256)
    article = models.ForeignKey(to=Article,on_delete=models.CASCADE)
    creationTime = models.DateTimeField(auto_now_add=True)

评论的表单类为:


class comment_form(forms.Form):
    email = forms.EmailField()
    username = forms.CharField()
    content = forms.CharField()
    article_id = forms.IntegerField()

评论的视图函数为:


def article_comment(request):
    if request.method == 'POST':
        form = comment_form(request.POST)
        if form.is_valid():
            value_dict = form.clean()
            username = value_dict['username']
            email = value_dict['email']
            content = value_dict['content']
            article_id = value_dict['article_id']
            models.Comment.objects.create(userName=username,email=email,content=content,article_id = article_id,email_hash=hashlib.md5(email.encode('utf-8')).hexdigest())
            messages.info(request, '评论成功')
        else:

            error_msg = form.errors.as_JSON()  # 获取错误信息
            error = json.loads(error_msg)
            key_list = error.keys()
            item = ''
            for i in key_list:
                item = i
            message = error[item][0]['message']
            messages.error(request,message)
        obj_url = request.META.get('Http_REFERER', "/")
        return redirect(obj_url)

这里存储了email的hash值是为了应用gravatar.com网站的头像,它根据邮箱的hash值来显示不同的头像,通过一个图片链接就可以显示,具体就不多说了

最后是留言部分,先创建留言表:


class Message(models.Model):
    content = models.TextField()
    creationTime = models.DateTimeField(auto_now_add=True)

只有两个字段且匿名,这个弄的简单点就好

留言的处理函数为:


def saysomethingtome(request):
    if request.method == 'POST':
        content = request.POST.get('content')
        if content:
            models.Message.objects.create(content=content)
            messages.info(request,'发送成功,感谢支持')
        obj_url = request.META.get('HTTP_REFERER', "/")
        return redirect(obj_url)

页面显示为:

留言当然是给我自己看的,所以只在后台显示了

总结

今天的主要部分就是上面所说的,中间还有很多的地方也做了改善但并没有说出来,这里主要是为了进行一个主要内容的记录,同时也可以提供一下思路,并没有记录的太细,不然有点杂了。明天预计完成留言,评论在后台的管理,以及文章在前端的分页显示。

相关文章