【django】【my_blog】創(chuàng)建模型并渲染頁面

創(chuàng)建模型并渲染頁面

創(chuàng)建模型文件

  • 創(chuàng)建文件: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

生成數(shù)據(jù)庫(模型遷移:migrate)

  • 生成遷移文件:
(EnvPython2) bash-3.2# python manage.py makemigrations
Migrations for 'blog':
  blog/migrations/0001_initial.py:
    - Create model Article
  • 執(zhí)行遷移:
(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

手動加入數(shù)據(jù)

  • 打開Navicat Premium,并新建鏈接


    image

    image
  • 打開數(shù)據(jù)庫,并添加數(shù)據(jù)


    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):
    # 讀取文章列表數(shù)據(jù)
    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>

查看結(jié)果,訪問:http://localhost:8000/blog/article/index/

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容