创建web app
由于django中的内容都是可插拔的组件,所以我们要先创建一个web app。输入如下命令,创建一个简单的blog系统。tips:实在我们之前创建好的项目里吗创建app
python manage.py startapp blog
创建完结构是这个样子的
创建数据库表结构
- 在models.py中写入数据库模型
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField('name',max_length=16)
def __unicode__(self):
return self.name
class Tag(models.Model):
name = models.CharField('name',max_length=16)
def __unicode__(self):
return self.name
class Blog(models.Model):
title = models.CharField('title',max_length=100)
author = models.CharField('author',max_length=50)
content = models.TextField('content')
created= models.DateTimeField('pubdate',auto_now_add=True)
category = models.ForeignKey(Category,verbose_name='category')
tags = models.ManyToManyField(Tag,verbose_name='name')
def __unicode__(self):
return self.title
class Comment(models.Model):
blog = models.ForeignKey(Blog,verbose_name='blog')
name = models.CharField('Name',max_length=50)
email = models.EmailField('Email')
content = models.CharField('Content',max_length=250)
created = models.DateTimeField('pubdate',auto_now_add=True)
- 执行脚本,生成数据库表结构
python manage.py makemigrations blog
python manage.py migrate
- 在admin.py中注册blog实体
from django.contrib import admin
# 注册博客的实体
import blog.models as models
class BlogAdmin(admin.ModelAdmin):
list_display = ('title','author','created') #定义显示字段
admin.site.register(models.Blog,BlogAdmin)
- 在settings.py的INSTALLED_APPS里加入“blog”
这时进入 http://127.0.0.1:8000/admin/可以看到blog模块了,可以写博客了。
显示页面
- 创建templates模板目录
- 在settings.py中添加模板目录
- 创建跳转视图函数
from django.http import Http404
from django.shortcuts import render
from blog.models import Blog
# Create your views here.
def index(request):
latest_articles_list = Blog.objects.order_by('-created')
if len(latest_articles_list) > 5:
latest_articles_list = latest_articles_list[-5:]
context = {
'latest_blog_list' : latest_articles_list,
}
return render(request,'blog/index.html',context)
- 创建html页面
首页
{% if latest_blog_list %}
{% for article in latest_blog_list %}
-
{{article.title}}
{{article.pubdate}}
{{article.content|safe}}
{% endfor %}
{% endif %}
- 定义跳转url
我是在外层的url里面include博客的url,这样便于管理
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/',include('blog.urls')),
]
然后再blog.urls文件里写入
from django.conf.urls import url, include
from blog import views as blogviews
urlpatterns = [
url(r'^$',blogviews.index),
]
- 在浏览器输入http://127.0.0.1:8000/blog 就可以看到在管理后台创建的博客列表了