当前位置: 首页 > 文档资料 > Python 全栈 >

4. 基于Django框架的项目搭建

优质
小牛编辑
135浏览
2023-12-01

(1). 创建数据库 shopdb

  • 进入MySQL数据库中,创建一个数据库名为:shopdb
  • 将上节《项目的数据库设计》中准备好的shopdb.sql脚本导入到shopdb数据库中

(2). 创建项目 myobject 框架和应用 myamdinwebcommon

    # 创建项目框架 `myobject`
    $ django-admin startproject myobject

    $ cd myobject

    # 在项目中创建一个myadmin应用(项目的后台管理)
    $ python manage.py startapp myadmin

    # 在项目中再创建一个web应用(项目前台)
    $ python manage.py startapp web

    # 在项目中再创建一个common应用(项目的前台和后台的公告应用)
    $ python manage.py startapp common

    # 创建模板目录
    $ mkdir templates
    $ mkdir templates/myadmin
    $ mkdir templates/web

    # 创建静态资源目录
    $ mkdir static
    $ mkdir static/myadmin
    $ mkdir static/web

    # 创建前后台应用模板目录,并在里面各创建一个`__init__.py`和`index.py`的空文件
    $ mkdir myadmin/views
    $ touch myadmin/views/__init__.py
    $ touch myadmin/views/index.py
    $ mkdir web/views
    $ touch web/views/__init__.py
    $ touch web/views/index.py

    # 删除前后台应用的默认模板文件
    # rm -rf myadmin/views.py
    # rm -rf web/views.py

    # 拷贝路由文件到应用目录中
    $ cp myobject/urls.py   myadmin/urls.py
    $ cp myobject/urls.py   web/urls.py

    # 退出项目目录
    $ cd ..

    #查看项目目录结构
    $ tree myobject

    myobject/
        ├── manage.py
        ├── myobject
        │   ├── __init__.py
        │   ├── settings.py
        │   ├── urls.py
        │   └── wsgi.py
        ├── myadmin
        │   ├── admin.py
        │   ├── apps.py
        │   ├── __init__.py
        │   ├── migrations
        │   │   └── __init__.py
        │   ├── views
        │   │   ├── __init__.py
        │   │   └── index.py
        │   ├── models.py
        │   ├── tests.py
        │   └── urls.py
        ├── web
        │   ├── admin.py
        │   ├── apps.py
        │   ├── __init__.py
        │   ├── migrations
        │   │   ├── __init__.py
        │   ├── views
        │   │   ├── __init__.py
        │   │   └── index.py
        │   ├── models.py
        │   ├── tests.py
        │   └── urls.py
        ├── common
        │   ├── admin.py
        │   ├── apps.py
        │   ├── __init__.py
        │   ├── migrations
        │   │   ├── __init__.py
        │   ├── models.py
        │   ├── tests.py
        │   └── views.py
        ├── static
        │   ├── myadmin/
        │   └── web/
        └── templates
            ├── myadmin/
            └── web/

(3). 项目框架配置

  • 3.1 编辑myobject/myobject/__init__.py文件,添加Pymysql的数据库操作支持
import pymysql
pymysql.install_as_MySQLdb()

注意:此配置需要安装pymysql软件包, 如:$ pip install pymysql

  • 3.2 编辑myobject/myobject/settings.py文件:
# myobject/myobject/settings.py  项目配置文件

# 1. 配置允许访问的主机名信息
ALLOWED_HOSTS = ['*']
或
ALLOWED_HOSTS = ['localhost','127.0.0.1','192.168.2.240']

...

# 2. 将myadmin和web的应用添加到项目框架结构中
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myadmin',
    'web',
    'common',
]

...

# 3. 配置模板目录 os.path.join(BASE_DIR,'templates')
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',
            ],
        },
    },
]

...

# 4. 配置项目的数据库连接信息:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'shopdb',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

...

# 5. 设置时区和语言 
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

...

# 6. 配置网站的静态资源目录
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

(4). 项目urls路由信息配置

  • 4.1 打开根路由文件:myobject/myobject/urls.py路由文件,编写路由配置信息
# myobject/myobject/urls.py

from django.conf.urls import url,include
#from django.contrib import admin

urlpatterns = [
#   url(r'^admin/', admin.site.urls),
    url(r'^myadmin/', include('myadmin.urls')), #网站后台路由
    url(r'^', include('web.urls')),           #网站前台路由
]
  • 4.2 打开项目后台管理路由文件:myobject/myadmin/urls.py路由文件,编写路由配置信息
# myobject/myadmin/urls.py

from django.conf.urls import url

from myadmin.views import index

urlpatterns = [
    # 后台首页
    url(r'^$', index.index, name="myadmin_index"),

]
  • 4.3 打开项目前台路由文件:myobject/web/urls.py路由文件,编写路由配置信息
# myobject/web/urls.py

from django.conf.urls import url

from web.views import index

urlpatterns = [
   # url(r'^$', index.index, name="index"),
]

(5). 编写后台视图测试

  • 5.1 编辑后台视图文件
# myobject/myadmin/views/index.py
from django.shortcuts import render
from django.http import HttpResponse

#后台首页
def index(request):
    return HttpResponse('欢迎进入商城网站后台!')
# myobject/web/views/index.py
from django.shortcuts import render
from django.http import HttpResponse

#前台首页
def index(request):
    return HttpResponse('欢迎进入商城网站前台首页!')
[root@localhost myobject]# pwd
/python/myobject
[root@localhost myobject]# ls
manage.py  myadmin  myobject  web  static  templates
[root@localhost myobject]# python3 manage.py runserver 0:8000
Performing system checks...

System check identified no issues (0 silenced).

April 06, 2018 - 14:29:36
Django version 1.11, using settings 'myobject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C[root@localhost myobject]#

(6). 摆放后台首页面:

  • 6.1. 使用事先准备好的后台模板:

    • 从github上下载一个后台简洁模板:https://github.com/alecfan/mstp_17_akira
    • 将后台模板目录中的资源目录:cssjsimg复制到项目的后台静态资源目录static/myadmin/
    • templates/myadmin/目录中创建一个基类父模板文件base.html
    • templates/myadmin/目录中创建一个首页模板文件index.html
    • templates/myadmin/目录中创建一个信息提示模板文件info.html
    • 修改myobject/myadmin/views/index.py视图文件中index函数中代码:
      def index(request):
        '''管理后台首页'''
        return render(request,"myadmin/index.html")
      
  • 6.2. 编辑父类模板:/templates/myadmin/base.html

{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="cn">
    <head>
        <meta charset="utf-8">
        <title>网站后台管理</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="{% static 'myadmin/css/bootstrap.min.css' %}" rel="stylesheet">
        <link href="{% static 'myadmin/css/bootstrap-responsive.min.css' %}" rel="stylesheet">
        <link href="{% static 'myadmin/css/site.css' %}" rel="stylesheet">
        <!--[if lt IE 9]><script src="{% static 'myadmin/js/html5.js' %}"></script><![endif]-->
    </head>
    <body>
        <div class="container">
            <!-- 页头开始 -->
            <div class="navbar">
                <div class="navbar-inner">
                    <div class="container">
                        <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">网站后台管理</a>
                        <div class="nav-collapse">
                            <ul class="nav">
                                <li class="active">
                                    <a href="index.html">首页</a>
                                </li>
                                <li>
                                    <a href="settings.htm">在线设置</a>
                                </li>
                                <li>
                                    <a href="help.htm">帮助</a>
                                </li>
                                <li class="dropdown">
                                    <a href="help.htm" class="dropdown-toggle" data-toggle="dropdown">更多 <b class="caret"></b></a>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a href="help.htm">Introduction Tour</a>
                                        </li>
                                        <li>
                                            <a href="help.htm">Project Organisation</a>
                                        </li>
                                        <li>
                                            <a href="help.htm">Task Assignment</a>
                                        </li>
                                        <li>
                                            <a href="help.htm">Access Permissions</a>
                                        </li>
                                        <li class="divider">
                                        </li>
                                        <li class="nav-header">
                                            Files
                                        </li>
                                        <li>
                                            <a href="help.htm">How to upload multiple files</a>
                                        </li>
                                        <li>
                                            <a href="help.htm">Using file version</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                            <form class="navbar-search pull-left" action="">
                                <input type="text" class="search-query span2" placeholder="Search" />
                            </form>
                            <ul class="nav pull-right">
                                <li>
                                    <a href="profile.htm">@管理员</a>
                                </li>
                                <li>
                                    <a href="login.htm">退出</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div><!-- 页头结束-->


            <div class="row">
                <div class="span3">
                    <!-- 侧边导航开始 -->
                    <div class="well" style="padding: 8px 0;">
                        <ul class="nav nav-list">
                            <li class="nav-header">
                                导航栏
                            </li>
                            <li class="active">
                                <a href="index.htm"><i class="icon-white icon-home"></i> 首页</a>
                            </li>
                            <li class="nav-header">
                                会员管理
                            </li>
                            <li>
                                <a href="#"><i class="icon-folder-open"></i> 浏览会员</a>
                            </li>
                            <li>
                                <a href="#"><i class="icon-check"></i> 添加会员</a>
                            </li>
                            <li class="nav-header">
                                商品类别管理
                            </li>
                            <li>
                                <a href="messages.htm"><i class="icon-envelope"></i> 浏览商品类别</a>
                            </li>
                            <li>
                                <a href="files.htm"><i class="icon-file"></i> 添加商品类别</a>
                            </li>
                            <li class="nav-header">
                                商品信息管理
                            </li>
                            <li>
                                <a href="activity.htm"><i class="icon-list-alt"></i> 浏览商品信息</a>
                            </li>
                            <li>
                                <a href="activity.htm"><i class="icon-list-alt"></i> 添加商品信息</a>
                            </li>
                            <li class="divider">
                            </li>
                            <li>
                                <a href="help.htm"><i class="icon-info-sign"></i> Help</a>
                            </li>
                            <li class="nav-header">
                                Bonus Templates
                            </li>
                            <li>
                                <a href="gallery.htm"><i class="icon-picture"></i> Gallery</a>
                            </li>
                            <li>
                                <a href="blank.htm"><i class="icon-stop"></i> Blank Slate</a>
                            </li>
                        </ul>
                    </div><!-- 侧边导航结束 -->
                </div>
                <div class="span9">
                    <!-- 主体开始 -->
                    {% block mainbody %}
                    {% endblock %}
                    <!-- 主体结束 -->
                </div>
            </div>
        </div>
        <script src="{% static 'myadmin/js/jquery.min.js' %}"></script>
        <script src="{% static 'myadmin/js/bootstrap.min.js' %}"></script>
        <script src="{% static 'myadmin/js/site.js' %}"></script>
    </body>
</html>
  • 6.3. 编辑后台首页模板:/templates/myadmin/index.html
{% extends "myadmin/base.html" %}

{% block mainbody %}                
    <h2>
        商城网站后台管理首页
    </h2>
    <div class="hero-unit">
        <h3>
            Welcome!
        </h3>
        <p>
            To get the most out of Akira start with our 3 minute tour.
        </p>
        <p>
            <a href="help.htm" class="btn btn-primary btn-large">Start Tour</a> <a class="btn btn-large">No Thanks</a>
        </p>
    </div>
    <div class="well summary">
        <ul>
            <li>
                <a href="#"><span class="count">3</span> Projects</a>
            </li>
            <li>
                <a href="#"><span class="count">27</span> Tasks</a>
            </li>
            <li>
                <a href="#"><span class="count">7</span> Messages</a>
            </li>
            <li class="last">
                <a href="#"><span class="count">5</span> Files</a>
            </li>
        </ul>
    </div>
{% endblock %}
  • 6.4. 后台公共提示信息模板:/templates/myadmin/info.html
{% extends "myadmin/base.html" %}

{% block mainbody %}                
    <h2>
        操作信息提示
    </h2>
    <h4>
        {{ info }}
    </h4>
{% endblock %}