创建博客
startapp blog
设计数据模型(model.py)
from django.db import models
from django.utils import timezone
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def _str_(self):
return self.title
model.py是数据模块,主要用于设创建数据表
激活应用程序(setting.py)
在INSTALLED_APP中添加
'blog.apps.BlogConfig'
setting.py是全局配置文件,包括数据库,web应用等
设置并使用迁移方案
1.对模型创建初始迁移
python manage.py makemigrations blog
2.执行sql语句,创建模型表
python manage.py sqlmigrate blog
3.数据库与模型同步
python manage.py migrate
管理站点
1.创建超级用户
python manage.py createsuperuser
2.定制模型的显示方式(moduls.py)
from django.db import models
from django.utils import timezone
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def _str_(self):
return self.title
本文详细介绍了如何使用Django框架创建一个博客系统,包括数据模型的设计、应用程序的激活、迁移方案的设置,以及超级用户的创建。重点讲解了model.py文件中Post类的定义,涵盖了从创建到发布的全过程。
2000

被折叠的 条评论
为什么被折叠?



