{ { article.title }}
{ {article.brief}}
python环境安装
https://www.python.org/ftp/python/3.8.3/python-3.8.3.exe
conda安装 https://www.anaconda.com/products/individual
Django安装: cmd 命令:
pip install django==2.0
安装完成后 运行命令: django-admin查看安装是否完成
Django基本命令: django-admin 可查看基本命令
项目目录介绍
创建项目运行命令 : django-admin startproject projectname
创建项目成功后的项目结构:
Django 应用 VS Django 项目
每个应用可以自己管理模型、视图、模板、路由、静态文件等; 一个Django项目包含一组配置和若干个Django应用。
在Django项目中创建Django应用
在Terminal中运行命令:python manage.py startapp blog
应用目录介绍
Django Hello world
编辑应用中的views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello_world(request):
return HttpResponse("hello World")
编辑应用中的 urls.py
from django.urls import path,include
import blog.views
urlpatterns = [
path('hello_world',blog.views.hello_world)
]
编辑项目的 urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("blog/",include('blog.urls')) //应用的路由
]
编辑项目的 settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 新增应用的配置
'blog.apps.BlogConfig'
]
启动项目:
浏览器访问: http://127.0.0.1:8000/blog/hello_world
执行原理:
创建博客文章模型
编辑应用的models.py
from django.db import models
# Create your models here.
class Article(models.Model):
# 文章标题 唯一ID
article_id = models.AutoField(primary_key=True)
# 文章辩题
title = models.TextField()
# 文章摘要
brief = models.TextField()
# 文章的主要内容
content = models.TextField()
# 文章的发布日期
publish_date = models.DateTimeField(auto_now=True)
创建迁移文件:python manage.py makemigrations
执行迁移文件:python manage.py migrate
Django Shell
D:\JavaWorkspace\IdeaSpace\django_demo>python manage.py shell
Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from blog.models import Article
In [2]: a = Article()
In [3]: a.title = 'Test Shell'
In [4]: a.brief = 'Test Shell, brief'
In [5]: a.content = 'Test Shell, New Article, Main Content...'
In [6]: print(a)
Article object (None)
In [7]: a.save()
In [8]: articles = Article.objects.all();
In [9]: article = articles[0]
In [10]: print(article.title)
Test Shell
In [11]: print(article.content)
Test Shell, New Article, Main Content...
Django Admin 模块是什么
为什么需要 Django Admin模块?
Django Admin模块的使用
D:\JavaWorkspace\IdeaSpace\django_demo>python manage.py createsuperuser
Username (leave blank to use 'lyx05'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
引用模型注册到admin : 编辑 应用中的admin.py
from django.contrib import admin
# Register your models here.
from .models import Article
admin.site.register(Article)
进入Article, 可进行增删查改操作;
由于默认显示的object(1) 这样的数据,无法分辨数据,可以自定义显示: 编辑 models.py。
from django.db import models
# Create your models here.
class Article(models.Model):
# 文章标题 唯一ID
article_id = models.AutoField(primary_key=True)
# 文章辩题
title = models.TextField()
# 文章摘要
brief = models.TextField()
# 文章的主要内容
content = models.TextField()
# 文章的发布日期
publish_date = models.DateTimeField(auto_now=True)
# 显示标题
def __str__(self):
return self.title
实现博客数据返回页面
修改应用的views.py 新增以下代码
from blog.models import Article
def article_content(request):
article = Article.objects.all()[0]
article_id = article.article_id
title = article.title
brief = article.brief
content = article.content
publish_date = article.publish_date
return_str = 'ID:%s,title:%s,brief:%s,content:%s,publish_date:%s' % (article_id,title,brief,content,publish_date)
return HttpResponse(return_str)
配置应用路由:urls.py, 增加路由
path('content',blog.views.article_content)
浏览器访问 content 地址
Django 模板
基本语法
Dear {
{ person_name }},
{% for item in item_list %}
- {
{ item }}
{% endfor %}
{% if ordered_warranty %}
Your warranty information will be included in the packaging.
{% else %}
You didn't order a warranty, so you're on your own when
the products inevitably stop working.
{% endif %}
在引用blog下新建文件夹 templates/blog ,在blog文件夹下新建index.html , detail.html
简易博客
三小时入门Django Web框架
—— by LYX
{% for article in article_list %}
{
{ article.title }}
{
{article.brief}}
{% endfor %}
最新文章
{% for article in top10_article_list %}
{
{ article.title }}
{% endfor %}
详情
{
{ curr_article.title }}
{% for section in section_list %}
{
{ section }}
{% endfor %}
编辑 应用的 views.py ,增加 代码:
from django.core.paginator import Paginator
def get_index_page(request):
page = request.GET.get('page')
if page:
page = int(page)
else:
page = 1
all_article = Article.objects.all()
top10_article_list = Article.objects.order_by('-publish_date')[:10]
paginator = Paginator(all_article, 6)
page_num = paginator.num_pages
page_article_list = paginator.page(page)
if page_article_list.has_next():
next_page = page + 1
else :
next_page = page
if page_article_list.has_previous():
previous_page = page - 1
else :
previous_page = page
return render(request, 'blog/index.html', {'article_list': all_article,'page_num':range(1,page_num + 1), 'curr_page':page,'next_page':next_page,'previous_page':previous_page,'top10_article_list':top10_article_list})
def get_detail_page(request,article_id):
all_article = Article.objects.all();
curr_article = None
previous_index = 0
next_index = 0
previous_article = None
next_article = None
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})
配置urls.py
urlpatterns = [
path('hello_world',blog.views.hello_world),
path('content',blog.views.article_content),
path('index',blog.views.get_index_page),
path('detail/',blog.views.get_detail_page)
]
启动项目:
至此, 使用 Django 创建一个web博客已完成。