创建项目
django-admin startproject 项目名
创建应用
python manage.py startapp 应用名
在 settings.py 文件 INSTALLED_APPS 里添加app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#blog_app
'blog.apps.BlogConfig'
]
配置路由
在新建的blog应用里新建urls.py,设置访问路径
urlpatterns = [
path('index',blog.views.get_index_page),
path('detail/<int:article_id>',blog.views.get_detail_page)
]
在项目下的urls.py里把碰到 blog/ 的 url 将交由 blog.urls 来处理
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls'))
]
模型定义
models.py 里新建一个类继承models.Model,定义博客文章模型的字段
class Article(models.Model):
article_id = models.AutoField(primary_key = True)
title = models.TextField()
brief_content = models.TextField()
content = models.TextField()
publish_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
模型迁移保存到数据库里面
python manage.py makemigrations
迁移文件同步到数据库
python manage.py migrate
Django Admin模块
创建超级用户:python manage.py createsuperuser
把模型注册到admin里面,在admin.py里设置
from .models import Article
admin.site.register(Article)
视图层views.py返回数据,进行模板渲染
def get_index_page(request):
page = request.GET.get('page')
all_article = Article.objects.all().order_by('article_id')
top5_article_list = Article.objects.order_by('-publish_date')[:5]
paginator = Paginator(all_article,3)
page_num = paginator.page_range
page_sum = paginator.num_pages
if page:
page = int(page)
if page > page_sum:
page = page_sum
else:
page = 1
return render(request,'blog/index.html',
{
'article_list':paginator.page(page),
'page_num':page_num,
'curr_page':page,
'page_sum':page_sum,
'top5_article_list':top5_article_list
})
def get_detail_page(request,article_id):
all_article = Article.objects.all()
for index,article in enumerate(all_article):
if index == 0:
previous_index = 0
next_index = index + 1
elif index == len(all_article) - 1:
previous_index = index - 1
next_index = index
else:
previous_index = index - 1
next_index = index + 1
if article.article_id == article_id:
curr_article = article
previous_article = all_article[previous_index]
next_article = all_article[next_index]
break
section_list = curr_article.content.split('\n')
return render(request,'blog/detail.html',
{
'curr_article':curr_article,
'section_list':section_list,
'previous_article':previous_article,
'next_article':next_article
})
模板系统标签
- 变量标签:{{ 变量 }}
- for循环标签:{% for x in list %},{% endfor %}
- if-else分支标签:{% if %},{% else %},{% endif %}
然后再加一点细节
一个简易的博客就完成了,在慕课网里学习的,有兴趣可以看看三小时带你入门Django框架