Django学习---多人博客项目(1)

拟墨画扇 提交于 2020-02-10 18:50:57

一、创建项目和应用

​ 在Pycharm中用Django模板创建一个工程文件

创建项目
    python manage.py startproject 项目名 .
创建应用
    python manage.py startapp 应用名

二、配置项目名中的settings文件

#1、添加应用
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog', #将添加的应用添加在此处
]
#2、设置编码为中文
LANGUAGE_CODE = 'zh-Hans'  # 'en-us'
#3、设置时区
TIME_ZONE = 'Asia/Shanghai'  #'UTC'
USE_I18N = True
USE_L10N = True
#4、改为False时区才能生效
USE_TZ =  False #True

​ 完成上述步骤可以启动Django服务器看看能否运行出初始界面

python manage.py runserver

三、添加数据模型

在应用程序(blog)的models.py文件中添加数据模型

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.


class BlogArticles(models.Model):
    title = models.CharField(max_length=300)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    
    class Meta:
        ordering = ("-publish",)
        
        def __str__(self):
            return self.title

数据模型添加后执行如下命令

python manage.py makemigrations

接着执行数据迁移命令

python manage.py migrate

四、创建超级用户

python manage.py createsuperuser
    用户名:admin 
    邮箱:admin@admin.com
    密码:django1234

刷新浏览器,使用上述账号和密码进行登录

五、数据模型注册

在应用程序名(blog)下的admin.py中注册数据模型类

from django.contrib import admin
from .models import BlogArticles    #导入数据模型类到当前文件夹
admin.site.register(BlogArticles)   #将该类注册到admin中

刷新浏览器,出现博客功能,优化数据注册模型:

from django.contrib import admin
from .models import BlogArticles    #导入数据模型类到当前文件夹

class BlogArticlesAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "publish")
    list_filter = ("publish", "author")
    search_fields = ("title", "body")
    # raw_id_fields = ("author") #这一句添加感觉有点问题,在后面刷新后重新写博客author哪儿不能选择了,造成博客生成不了,注释了即可
    date_hierarchy = "publish"
    ordering = ['-publish', 'author']
admin.site.register(BlogArticles, BlogArticlesAdmin)    #将该类注册到admin中

六、显示博客标题

(1)添加视图

​ 在./blog/views.py文件中添加基于视图的函数(还有一种视图是基于类的视图)

from django.shortcuts import render
from .models import BlogArticles

def blog_title(request):
    blogs = BlogArticles.objects.all()
    return render(requset, "blog/titles.html", {"blogs": blogs})

(2)添加模板

​ 在templates中添加基础模板base.html文件,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="https://github.com/necolas/normalize.css/blob/master/normalize.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        {% block content %}
        {% endblock %}
    </div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

​ 在./templates/blog/下面创建titles.html, 添加如下内容:

{% extends "base.html" %}
{% block title %}blog titles{% endblock %}
{% block content %}
    <div class="row text-center vertical-middle-sm">
        <h1>我的博客</h1>
    </div>
    <div class="row">
        <div class="col-xs-12 col-md-8">
            <ul>
            {% for blog in blogs %}
              <li>{{ blog.title }}</li>
            {% endfor %}
            </ul>
        </div>
        <div class="col-xs-6 col-md-4">
            <h2>广告</h2>
            <p>跟老齐学:www.itdiffer.com</p>
            <img width="200px" src="           https://raw.githubusercontent.com/qiwsir/DjangoPracticeProject/master/python-book2.png">
        </div>
    </div>
{% endblock %}

(3)配置路由

路由需要配置两个地方的路由

# 配置 ./mystie/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns=[
    path('admin/',admin.site.urls),
    path('blog/', inclue('blog.urls'))
]

# 上面用到的blog.urls还没有创建在./blog/下创建urls.py 并添加如下内容:
from django.urls import path
from . import views
urlpatterns = [
    path('', views.blog_title), #此处将函数视图添加进来
]

七、显示博客内容

(1)文章标题设置超链接

​ 首先需要在titels.html中显示标题的部分做相应修改。即给标题添加超链接,如下:

{% for blog in blogs %}
    <li>    
        <a href="{{blog.id}}">{{blog.title}}</a>
    </li>
{% endfor %}

(2)添加视图

​ 编辑./blog/view.py,增加响应查看文章详情的请求函数blog_article()

def blog_article(request, article_id):
    article = BlogArticles.objects.get(id=article_id)
    pub = article.publish
    return render(request, "blog/content.html", {"article":article, "publish":pub})

(3)添加模板

​ 在./templates/blog/下面创建content.html, 添加如下内容:

{% extends "base.html" %}
{% block title %}blog article{% endblock %}
{% block content %}
    <div class="row text-center vertical-middle-sm">
        <h1>{{article.title}}</h1>
    </div>
    <div class="row">
        <div class="col-xs-12 col-md-8">
            <p class="text-center">
                <span>
                  {{article.author.username}}  
                </span>
                <span style="margin-lefet:20px">
                    {{publish}}
                </span>
            </p>
            <div>
                {{article.body}
            </div>
        </div>
        <div class="col-xs-6 col-md-4">
            <h2>广告</h2>
            <p>跟老齐学:www.itdiffer.com</p>
            <img width="200px" src="           https://raw.githubusercontent.com/qiwsir/DjangoPracticeProject/master/python-book2.png">
        </div>
    </div>
{% endblock %}

(4)配置路由

# ./mystie/urls.py 不需要修改

# ./blog/urls.py 添加博客内容也的路由
from django.urls import path
from . import views
urlpatterns = [
    path('', views.blog_title), #此处将函数视图添加进来
    path('<int:article_id>', views.blog_article),
]

(4)处理异常

from django.shortcuts import render, get_object_or_404
from .models. import BlogArticles
def blog_article(request, article_id):
    #article = BlogArticles.objects.get(id=article_id)
    article = get_object_or_404(BlogArticles, id=article_id)
    pub = article.publish
    return render(request, "blog/content.html", {"article":article, "publish":pub})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!