Python Django个人网站搭建2-编写文章的Model模型以及Views视图

2021-12-14 12:19:50 浏览数 (1)

作者: zifanwang  发布于2020-05-07

1. 编写 Model. py

打开article/models.py输入如下代码:

代码语言:javascript复制
from django.db import models

# 导入内建的User模型
from django.contrib.auth.models import User
from django.utils import timezone

# 文章数据模型
class ArticlePost(models.Model):
    # 文章作者。参数on_delete 用于指定数据删除的方式,避免两个关联表数据不一致
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    # 文章标题
    title = models.CharField(max_length=100)

    # 文章正文
    body = models.TextField()

    created = models.DateTimeField(default=timezone.now())

    # 文章更新时间 参数 auto_now=True 指定每次数据更新时自动写入当前时间
    updated = models.DateTimeField(auto_now=True)
    # 内部类class Meta用于给model定义元数据
    class Meta:
        # ordering 指定模型返回的数据的排列顺序
        # ’-created‘ 表明数据应该以倒叙排列
        ordering = ('-created',)

    def __str__(self):
        return self.title

使用ForeignKey定义一个关系。这将告诉 Django,每个(或多个)ArticlePost对象都关联到一个User对象。 Django 本身具有一个简单完整的账号系统(User),足以满足一般网站的账号申请、建立、权限、群组等基本功能。

ArticlePost类定义了一篇文章所必须具备的要素:作者、标题、正文、创建时间以及更新时间。

2. 数据迁移

进入到 manage.py同级目录下输入:

代码语言:javascript复制
python manage.py makemigrations

如果一切正常,就会看到以下结果:

代码语言:javascript复制
C:mysite >python manage.py makemigrations
System check identified some issues:

WARNINGS:
article.ArticlePost.created: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Migrations for 'article':
  articlemigrations001_initial.py
    - Create model ArticlePost

C:mysite >

可以看见成功进行了迁移 然后迁移到数据库中

代码语言:javascript复制
C:mysite >python manage.py migrate
System check identified some issues:

WARNINGS:
article.ArticlePost.created: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Apply all migrations: admin, article, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying article.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

C:mysite >

迁移到数据库成功

3. 编写视图函数 article/views.py

打开article/views.py输入如下代码:

代码语言:javascript复制
from django.shortcuts import render
from django.http import HttpResponse

# 视图函数
def article_list(request):
    return HttpResponse("Hello World!")

将用户请求的url关联起来,修改article/urls.py

代码语言:javascript复制
from django.urls import path
from . import views
# 正在部署的应用的名称
app_name = 'article'
urlpatterns = [
    # path函数将url映射到视图
    path('list/', views.article_list, name='article_list'),
]

修改后打开cmd,cd到mysite目录下然后输入命令python manage.py runserver,再输入网址http://127.0.0.1:8000/article/list 后看到如下界面:

0 人点赞