打开命令行窗口,进入文件夹py2022,在目录输入:
django-admin startproject pyweb
python manage.py startapp blog
python manage.py runserver
编辑settings.py文件,添加blog.apps.BlogConfig到INSTALLED_APPS设置中:
'blog.apps.BlogConfig',
在blog应用下的models.py文件中添加下列代码:
from django.db import models
class Article(models.Model):
title = models.CharField('标题',max_length=50)
content = models.TextField('内容')
追踪模型的变动:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
用户名: kexin 密码: kexin1234 出现警告时:输入y 回车
修改成中文,settings文件
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
编辑blog应用的admin.py文件为如下这样:
from django.contrib import admin
from .models import Article
admin.site.register(Article)
打开网址: http://127.0.0.1:8000/admin
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('', include('blog.urls')),
path('admin/', admin.site.urls),
]
from django.urls import path
from . import views
urlpatterns = [
path('', views.index,name='index'),
]
修改views.py文件
from django.shortcuts import render
from .models import Article
def index(request):
articles = Article.objects.all()
return render(request,'blog/index.html',{
'articles':articles
})
在blog下建立templates/blog/index.html 修改index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的博客</title>
</head>
<body>
{% for article in articles %}
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
{% endfor %}
</body>
</html>
留言