个人博客系统!!!

Posted 不要被骄傲遮蔽了双眼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了个人博客系统!!!相关的知识,希望对你有一定的参考价值。

 

项目代码:https://github.com/venicid/Project1--Bloger

 

1.准备工作

  1.创建project

PS C:\\Users\\Administrator\\Desktop\\bloger> django-admin startproject bloger

 

  2 创建app

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py startapp firstapp

 

  3 setting添加app

INSTALLED_APPS = [
    \'django.contrib.admin\',
    \'django.contrib.auth\',
    \'django.contrib.contenttypes\',
    \'django.contrib.sessions\',
    \'django.contrib.messages\',
    \'django.contrib.staticfiles\',
    \'firstapp\',
]

 

  4 更新数据库表

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py makemigrations

No changes detected
PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py migrate

 

  5 运行runserver

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py runserver

 

  6 创建超级管理员

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py createsuperuser
Username (leave blank to use \'administrator\'): adminuser
Email address:
Password:
Password (again):
Superuser created successfully.

  

 

2.博客主页

 

  1  Model层:

from django.db import models

# Create your models here.

class Article(models.Model):
    """博客内容字段"""
    title = models.CharField(null=True, blank=True, max_length=300) #文章标题
    content = models.TextField(null=True, blank=True)   #文章内容

    def __str__(self):
        return self.title

 

   admin 注册

from django.contrib import admin
from firstapp.models import Article
# Register your models here.


admin.site.register(Article)

 

  合并数据库

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py makemigrations
Migrations for \'firstapp\':
  0001_initial.py:
    - Create model Article
PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py migrate

 

  runserver

    

 

  添加数据

    

 

 2 View层

  1 获取Article表的所有数据 article_list = Article.objects.all()

from django.shortcuts import render,redirect
from firstapp.models import Article

# Create your views here.


def index(request):
    """主页视图"""
    context = {}
    article_list = Article.objects.all()  # 获取Article表的所有数据
    context[\'article_list\'] = article_list
    return render(request, \'index.html\', context)

 

 

 3 T层

  1 导入静态文件,页面

     

 

   2 setting设置

TEMPLATES = [
    {
        \'BACKEND\': \'django.template.backends.django.DjangoTemplates\',
        \'DIRS\': [os.path.join(BASE_DIR,\'templates\').replace(\'\\\\\',\'/\')],

 

  

{% load staticfiles %}

    <link rel="stylesheet" href="{% static \'css/semantic.css\' %}" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="{% static \'css/list_custom.css\' %}" media="screen" title="no title" charset="utf-8">
  
    <img src="{% static \'images/tenlogo.png\' %}" alt="">

 

 

  3 渲染目标语言

          {% for article in article_list  %}

            <div class="column">
                <a class="ui fluid card" href="#detail/215">
                    <div class="image">
                        <img src="{% static \'images/img1.jpg\' %}" alt="" style="height:200px;object-fit: cover;">
                    </div>
                </a>

                <div class="title header" href="/detail/215">{{ article.title }}</div>

                <i class="icon grey unhide"></i>
                <span style="color:#bbbbbb">10K</span>
                <span class="" style="color:rgb(226, 226, 226)">|</span>
                <i class="icon grey checkmark"></i>
                <span style="color:#bbbbbb"> 10 people got it</span>

            </div>

          {% endfor %}

 

 

  4 配置 url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index

urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^index/\', index, name=\'index\'),
]

 

  

 

  5 过滤器

     {{ article.content|truncatechars:150 }}   #过滤器:100个字符

 


 

3 文章分类

 1 M层

     1 tag标签

from django.db import models

# Create your models here.

class Article(models.Model):
    """博客内容字段"""
    title = models.CharField(null=True, blank=True, max_length=300) #文章标题
    content = models.TextField(null=True, blank=True)   #文章内容

    TAG_CHOICES = (
        (\'cry\',\'悬疑类型\'),
        (\'ai\',\'科幻类型\'),
        (\'life\',\'生活类型\')
        )
    tag = models.CharField(null=True, blank=True, max_length=5, choices=TAG_CHOICES)

    def __str__(self):
        return self.title

 

 

  2 数据库注册,合并数据

  3 admin后台

    

 

 2 View层

def index(request):
    """主页视图"""
    queryset = request.GET.get(\'tag\')
    if queryset:
        article_list = Article.objects.filter(tag=queryset)  #过滤器
    else:
        article_list = Article.objects.all()  # 获取Article表的所有数据

    context = {}
    context[\'article_list\'] = article_list
    return render(request, \'index.html\', context)

 

3 T 层

 <a class="item" href="{% url \'index\' %}">全部</a>

  <a class="active item" href="?tag=cry">悬疑</a>

        <div class="ui container nav">
            <div class="ui  text four item menu ">
                <a class="item" href="http://127.0.0.1:8000/index/">全部</a>
                <a class="item" href="?tag=ai">AI</a>
                <a class="item" href="?tag=linux">Linux</a>
                <a class="item" href="?tag=python">Python</a>
            </div>
        </div>

 

 

                    <div class="ui mini tag label">
                        {{ article.tag }}
                    </div>

 

   

 

 

 

 

 

 

3.博客详情页

  1.Model层:

   不变

 

  2 View层

  article = Article.objects.get(id=page_num)  #取出id为1的这篇文章
from django.shortcuts import render,redirect
from firstapp.models import Article

# Create your views here.


def index(request):
    """主页视图"""
    context = {}
    article_list = Article.objects.all()  # 获取Article表的所有数据
    context[\'article_list\'] = article_list
    return render(request, \'index.html\', context)

def detail(request,page_num):
    """detail视图"""
    context = {}
    article = Article.objects.get(id=page_num)  #取出id为1的这篇文章
    context[\'article\'] = article
    return render(request, \'detail.html\', context)

 

  url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index,detail

urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^index/\', index, name=\'index\'),
    url(r\'^detail/(?P<page_num>\\d+)$\', detail, name=\'detail\'),
]

 

  

 3 T层

{% load staticfiles %}    

<link rel="stylesheet" href="{% static \'css/semantic.css\' %}" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="{% static \'css/detail.css\' %}" media="screen" title="no title" charset="utf-8">

  <img src="{% static \'images/tenlogo.png\' %}" alt="">

 

 

      渲染模板语言

          <h1 class="ui header">{{ article.title }}</h1>
            <p>
                {{ article.content }}
            </p>

 

 

 

4. 实现跳转功能

     <a class="item" href="{% url \'index\' %}">全部</a>

  <a href="{% url \'detail\' article.id %}">

               <a href="{% url \'detail\' article.id %}">
                        <h2 class="ui header">
                            {{ article.title }}
                        </h2>
                    </a>

 

                        <a href="{% url \'detail\' article.id %}">
                            <i class="angle tiny double grey right icon">READMORE</i>
                        </a>

 

 <title>{{ article.title }}</title>

 

 

 

 

5.展示这个文章对应的评论

  1 M层

     belong_to = models.ForeignKey(to=Article, related_name=\'under_comments\', null=True, blank=True)

from django.db import models

# Create your models here.


class Article(models.Model):
    """博客内容字段"""
    title = models.CharField(null=True, blank=True, max_length=300)  # 文章标题
    content = models.TextField(null=True, blank=True)  # 文章内容
    TAG_CHOICES = (
        (\'ai\', \'ai\'),
        (\'python\', \'python\'),
        (\'linux\', \'linux\'),
        )
    tag = models.CharField(null=True, blank=True, max_length=10, choices=TAG_CHOICES)

    def __str__(self):
        return self.title

class Comment(models.Model):
    """评论字段表"""
    name = models.CharField(null=True, blank=True, max_length=50)
    comment = models.TextField(null=True, blank=True)
    belong_to = models.ForeignKey(to=Article, related_name=\'under_comments\', null=True, blank=True)

    def __str__(self):
        return self.comment

 

 

  2 注册

from django.contrib import admin
from firstapp.models import Article,Comment
# Register your models here.


admin.site.register(Article)
admin.site.register(Comment)

 

   3  合并数据库

PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py makemigrations
No changes detected
PS C:\\Users\\Administrator\\Desktop\\bloger> python.exe .\\manage.py makemigrations

 

 

 

  2 V 层

  不变

def detail(request,page_num):
    """加载文章,评论视图"""
    context = {}
    article = Article.objects.get(id=page_num)  #取出id为1的这篇文章
    context[\'article\'] = article
    return render(request, \'detail.html\', context)

 

   url 不变

 

 3  T层

通过Article的字段under_comments查找评论

    {% for comment in article.under_comments.all  %}
                <div class="comment">
                    <div class="avatar">
                        <img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
                    </div>
                    <div class="content">
                        <a href="#" class="author">{{ comment.name }}</a>
                        <div class="metadata">
                            <div class="date">2 days ago</div>
                        </div>
                        <p class="text" style="font-family: \'Raleway\', sans-serif;">
                            {{ comment.comment }}
                        </p>
                    </div>
                </div>
          {% endfor %}

  

 



 

6 form表单提交评论

 

   1  M层:不变

 

  2  V层

  1 定义Django表单

from django import forms

class CommentForm(forms.Form):
    """定义Django自带的form表单"""
    name = forms.CharField(max_length=50)
    comment = forms.CharField(widget=forms.Textarea)

 

 

 

   2  get实例化一个表单

      post提交表单数据

from django.shortcuts import render,redirect
from firstapp.models import Article,Comment
from django import forms

class CommentForm(forms.Form):
    """定义个Django自带的表单类"""
    name = forms.CharField(max_length=50)
    comment = forms.CharField()

def detail(request,page_num):
    """加载文章,评论视图"""
    if request.method == \'GET\':
        form = CommentForm   #实例化表单

    if request.method == \'POST\':
        form = CommentForm(request.POST)  #提交数据
        # print(form) for testing
        if form.is_valid():   #判断表单的数据是否通过验证
            name = form.cleaned_data[\'name\']
            comment = form.cleaned_data[\'comment\']
            a = Article.objects.get(id=page_num)   #查找出该文章对应的id
            c = Comment(name=name, comment=comment, belong_to=a)    #写评论
            c.save()   #保存数据库
            return redirect(to=\'detail\',page_num=page_num)  #重定向本页

    context = {}
    article = Article.objects.get(id=page_num)  #取出id为1的这篇文章
    context[\'article\'] = article
    context[\'form\'] = form
    return render(request, \'detail.html\', context)

 

  url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index, detail

urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^index/\', index, name=\'index\'),
    url(r\'^detail/(?P<page_num>\\d+)$\',detail,name=\'detail\'),
]

 

 

 3 T层

        <form class="ui form" action="" method="post">

            {{ form.as_p }}
            {% csrf_token %}
            <button type="submit" class="ui blue button" >Click</button>
        </form>

  

 

 

 

7.Django自带form表单验证

  1  form表单单独写成文件

      

      

        

 

   2.各种验证器

from django import forms
from django.core.exceptions import ValidationError


def words_validator(comment):
    """验证器函数"""
    if len(comment) < 5:
        raise ValidationError(\'内容长度不足5个字符\')

def comment_validator(comment):
    """过滤器"""
    if \'?\' in comment:
        raise ValidationError(\'不能包含这个字符\')

class CommentForm(forms.Form):
    """定义Django自带的form表单"""
    name = forms.CharField(max_length=50,
                           error_messages={
                               \'required\': \'请输入内容\',
                                },
                           )

    comment = forms.CharField(              # 修改表单样式
        widget=forms.Textarea,
        error_messages={
            \'required\':\'请输入内容\',
            },
        validators=[words_validator,comment_validator]
        )

    

 

 

 

 

8.定制表单

  1 sematic ui 的表单

            <form class="ui form" action="" method="post">

                <div class="field">
                    <label> name</label>
                    <input type="text" name="name" value="">
                </div>
                <div class="field">
                    <label>comment</label>
                    <textarea></textarea>
                </div>
                
                <button type="submit" class="ui blue button" >Click</button>
            </form>

 

 

<tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><input id="id_name" maxlength="50" name="name" type="text" /></td></tr>
<tr><th><label for="id_comment">Comment:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><textarea cols="40" id="id_comment" name="comment" rows="10">
</textarea></td></tr>

 

 

  2 错误表单

  

<div class="ui form">
  <div class="two fields">
    <div class="field error">
      <label>First Name</label>
      <input placeholder="First Name" type="text">
    </div>
    <div class="field">
      <label>Last Name</label>
      <input placeholder="Last Name" type="text">
    </div>
  </div>
  <div class="field error">
    <label>Gender</label>
    <div class="ui selection dropdown">
      <div class="default text">Select</div>
      <i class="dropdown icon"></i>
      <input type="hidden" name="gender">
      <div class="menu">
        <div class="item" data-value="male">Male</div>
        <div class="item" data-value="female">Female</div>
      </div>
    </div>
  </div>
  <div class="inline field error">
    <div class="ui checkbox">
      <input type="checkbox" tabindex="0" class="hidden">
      <label>我同意本条款和条件</label>
    </div>
  </div>
</div>

 

   3.post传到后台的数据

    

    

 

      4.定制错误表单

          <form class="ui error tiny form" action="" method="post">

              {% if form.errors %}
                  <div class="ui error message">
                    {{ form.errors }}
                  </div>
                  {% for field in form  %}
                    <div class="{{ field.errors|yesno:\'error, \' }} field">
                      {{ field.label }}
                      {{ field }}
                    </div>
                  {% endfor %}

              {% else %}
                  {% for field in form  %}
                    <div class="field">
                      {{ field.label }}
                      {{ field }}
                    </div>
                  {% endfor %}
              {% endif %}
              {% csrf_token %}
                <button type="submit" <

以上是关于个人博客系统!!!的主要内容,如果未能解决你的问题,请参考以下文章

个人博客系统---基本功能的实现

个人博客系统---基本功能的实现

个人博客系统---基本功能的实现

基于SSM的个人博客系统(数据库+源码)

iOS常用于显示几小时前/几天前/几月前/几年前的代码片段

json 个人的vscode的代码片段