Django传递数据

1.添加booktest/models.py模型

from django.db import models


class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField()

    def __str__(self):
        return self.btitle


class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField()
    hcontent = models.CharField(max_length=1000)
    hbook = models.ForeignKey(BookInfo, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.hname


2.数据迁移
python manage.py makemigrations
python manage.py migrate

3.添加booktest/admin后台管理关联
from django.contrib import admin
from .models import HeroInfo, BookInfo


class HeroInfoInline(admin.TabularInline):
    model = HeroInfo
    extra = 3


class BookInfoAdmin(admin.ModelAdmin):
    list_display = ['id', 'btitle', 'bpub_date']
    list_filter = ['btitle']
    search_fields = ['btitle']
    list_per_page = 10
    fieldsets = [
        ('base', {'fields': ['btitle']}),
        ('super', {'fields': ['bpub_date']})
    ]
    inlines = [HeroInfoInline]


admin.site.register(BookInfo, BookInfoAdmin)
admin.site.register(HeroInfo)

注:手动去后台添加几条数据,以下查询使用

4.编写视图booktest/views.py
from django.shortcuts import render
from django.http import *
from django.template import RequestContext, loader
from .models import BookInfo


# Create your views here.
def index(request):
    bookList = BookInfo.objects.all()
    context = {'list': bookList}
    return render(request, 'booktest/index.html', context)

def show(request, id):
    book = BookInfo.objects.get(pk=id)
    herolist = book.heroinfo_set.all()
    context = {'list': herolist}
    return render(request, 'booktest/show.html', context)

注:heroinfo_set查询book下的集合

5.编写路由booktest/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index),
    path('<int:id>/', views.show),
]



6.编写templates/booktest/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BookTest</title>
</head>
<body>
<h1>index</h1>
<ul>
    {% for book in list %}
        <li><a href="{{ book.id }}">{{ book.btitle }}</a></li>
    {% endfor %}
</ul>
</body>
</html>

7.编写templates/booktest/show.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BookTest</title>
</head>
<body>
<h1>show</h1>
<ul>
    {% for hero in list %}
        <li>{{ hero.hname }}</li>
    {% endfor %}
</ul>
</body>
</html>
8.访问地址

http://127.0.0.1:8000/booktest/index/

	

Django使用模板

一.模板添加

1.新建app

python manage.py startapp booktest

2.配置setting.py添加新建app名booktest

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    'blog',
]
3.配置根目录urls
from django.contrib import admin
from django.urls import path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    path('booktest/', include('booktest.urls'))
]
4.配置booktest中的urls
from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index)
]

5.根目录会有templates文件,新建booktest/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BookTest</title>
</head>
<body>
    <h1>您好,世界!</h1>
</body>
</html>

6.编写视图
(1)方式一:
from django.shortcuts import render
from django.http import *
from django.template import RequestContext, loader


# Create your views here.
def index(request):
    temp = loader.get_template('booktest/index.html')
    return HttpResponse(temp.render())

(2)方式二:
from django.shortcuts import render
from django.http import *



# Create your views here.
def index(request):
    return render(request, 'booktest/index.html')

注:推荐方式二,其中原理内部封装也是方式一

 

7.访问地址

http://127.0.0.1:8000/booktest/index/

 

Django视图与urls

一.视图

1.编辑blog/views.py

from django.shortcuts import render
from django.http import *


# Create your views here.
def index(request):
    return HttpResponse('Hello World!')

注:这里先编辑最简单视图,页面输出Hello World!


二.urls配置

一.配置setting.py文件

from django.contrib import admin
from django.urls import path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    path('booktest/', include('booktest.urls'))
]
注:这里独立每个文件urls的路由!blog是一个app,booktest是另外一个app!

二.blog/urls.py设置路由
from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index)
]

三.访问地址
http://127.0.0.1:8000/blog/index/


Django后台管理

一.后台管理搭建

1.新建一个app

python manage.py startapp blog

注:前提已经有建立好Django项目,见环境搭建。执行上面命令,会在根目录下生成一个blog文件夹

2.编写blog/models

from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(u'标题', max_length=256)
    content = models.TextField(u'内容')

    pub_date = models.DateTimeField(u'发表时间')
    create_date = models.DateTimeField(u'创建时间', auto_now_add=True, editable=True)
    update_time = models.DateTimeField(u'更新时间', auto_now=True, null=True)

    def __str__(self):
        return self.title

class Category(models.Model):
    name = models.CharField(u'分类名称', max_length=64)
    type = models.IntegerField(u'分类类型')
    # 表示外键关联到文章表,当文章表删除了该条数据,分类表中不删除,仅仅是把外键置空
    # https://blog.csdn.net/kuangshp128/article/details/78946316
    article_id = models.ForeignKey(Article, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

注:这里分类等等后面后台管理关联使用!!!
其中注意2.0.5版本中外键参数需要设置on_delete!!!

3.把blog加入setting.py文件
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    'blog',
]
4.数据迁移
python manage.py makemigrations
python manage.py migrate
注:前提数据量有设置好,见:Django开发准备

5.创建管理员
python manage.py createsuperuser

注:根据提示设置设置账号密码

6.运行项目

python manage.py runserver

7.访问地址

http://127.0.0.1:8000/admin/

 

 

二.后台关联添加

1.编辑blog/admin.py文件

from django.contrib import admin
from .models import Article

admin.site.register(Article)

注:最简单的后台模型添加,会在后台自动生成blog列表

2.文章列表详情显示设置
from django.contrib import admin
from .models import Article


# 文章信息
class ArticleInfoAdmin(admin.ModelAdmin):
    list_display = ['id', 'title', 'content', 'pub_date', 'update_time']
    list_filter = ['title', 'content']
    search_fields = ['title']
    list_per_page = 10
    fieldsets = [
        ('basic', {'fields': ['title', 'content']}),
        ('more', {'fields': ['pub_date']})
    ]

admin.site.register(Article, ArticleInfoAdmin)

2.文章与分类关联设置

from django.contrib import admin
from .models import Article, Category


# 文章内联多个分类
class CategoryInfoInline(admin.TabularInline):
    model = Category
    extra = 3


# 文章信息
class ArticleInfoAdmin(admin.ModelAdmin):
    list_display = ['id', 'title', 'content', 'pub_date', 'update_time']
    list_filter = ['title', 'content']
    search_fields = ['title']
    list_per_page = 10
    fieldsets = [
        ('basic', {'fields': ['title', 'content']}),
        ('more', {'fields': ['pub_date']})
    ]
    inlines = [CategoryInfoInline]


admin.site.register(Article, ArticleInfoAdmin)
注:inlines 内联,前提是在models设置的时候,需要设置外键!!!否则会报错!!!

 

Django模型类

一.模板添加

1.新建app

python manage.py startapp booktest

python manage.py startapp blog

2.添加到setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    'blog',
]

3.编写各自模型

(1) . booktest/models

from django.db import models


class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField()

    def __str__(self):
        return self.btitle


class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField()
    hcontent = models.CharField(max_length=1000)
    hbook = models.ForeignKey(BookInfo, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.hname

(2) . blog/models

from django.db import models


# Create your models here.
class Article(models.Model):
    title = models.CharField(u'标题', max_length=256)
    content = models.TextField(u'内容')

    pub_date = models.DateTimeField(u'发表时间')
    create_date = models.DateTimeField(u'创建时间', auto_now_add=True, editable=True)
    update_time = models.DateTimeField(u'更新时间', auto_now=True, null=True)

    def __str__(self):
        return self.title


class Category(models.Model):
    name = models.CharField(u'分类名称', max_length=64)
    type = models.IntegerField(u'分类类型')
    # 表示外键关联到文章表,当文章表删除了该条数据,分类表中不删除,仅仅是把外键置空
    # https://blog.csdn.net/kuangshp128/article/details/78946316
    article_id = models.ForeignKey(Article, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

 

4.数据迁移

python manage.py makemigrations
python manage.py migrate

Django 开发准备

一.setting文件配置

0.进入虚拟环境,安装mysql客户端

workon django2.0

pip install mysqlclient

1.数据库配置

不使用自带的sqlite3数据库,连接mysql数据库

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.mysql',  # 或者使用 mysql.connector.django
        'NAME': 'djangotest',
        'USER': 'gerry',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'CHARSET': 'utf8'
    }
}

2.时区和语言设置

语言:设置为中文

时区:设置为上海

LANGUAGE_CODE = ‘zh-hans’ # en-us
TIME_ZONE = ‘Asia/Shanghai’ # UTC
USE_I18N = True
USE_L10N = True
USE_TZ = False

 

3.静态文件访问位置

templates文件,2.0.5版本默认生成,默认也配置了,没有的话就自行拷贝以下代码
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


Django 虚拟环境

前提安装pip,不懂得可以百度一下。

Windows 下:

 

一.virtualenv 安装

1.利用pip安装

pip install virtualenv virtualenvwrapper-win

2.虚拟环境更换位置(可选)

【可选】Windows下默认虚拟环境是放在用户名下面的Envs中的。我这里习惯将他移动到D盘。 更改方法:计算机,属性,高级系统设置,环境变量,添加WORKON_HOME。

 

 

二.虚拟环境使用

1.创建虚拟环境
mkvirtualenv env(环境名)

2.查看虚拟环境有哪些

workon

3.进入虚拟环境

workon django2.0

4.搭建django

pip install django

pip install -i https://pypi.douban.com/simple django

注:(二选一) 最新版本2.0.5,这里用了豆瓣的镜像,下载会比较快!

5.通过pycharm创建django项目

注:pycharm可以去官方下载!

6.查看django版本

python -m django –version

7.运行django

python manage.py runserver

注:进入工程根目录运行, manage.py所在的层级目录

8.访问网址

http://127.0.0.1:8000