创建模型并渲染页面
创建模型文件
- 创建文件:
blog/model/article.py
- 写入:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=255, null=True)
content = models.TextField(max_length=0, null=True)
修改模型文件:blog/models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from model import article
生成数据库(模型迁移:migrate)
- 生成迁移文件:
(EnvPython2) bash-3.2# python manage.py makemigrations
Migrations for 'blog':
blog/migrations/0001_initial.py:
- Create model Article
- 执行迁移:
(EnvPython2) bash-3.2# python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, 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 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 blog.0001_initial... OK
Applying sessions.0001_initial... OK
手动加入数据
-
打开Navicat Premium,并新建链接
image
image -
打开数据库,并添加数据
image
image
在view中读取并显示
- 修改:
blog/view/article.py
# encoding: utf-8
from django.http import HttpResponse
from django.shortcuts import render
from blog import models
# 文章列表页
def index(request):
# 读取文章列表数据
article_list = models.article.Article.objects.all()
return render(request=request, template_name='article/index.html', context={'article_list': article_list})
修改模型文件:blog/templates/article/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章列表页</title>
</head>
<body>
<h2>文章列表</h2>
<ul>
{% for article in article_list %}
<li>{{ article.id }}</li>
<li><a href="javascript:">{{ article.title }}</a></li>
{% endfor %}
</ul>
</body>
</html>
网友评论