首页 > 代码库 > Django 项目创建方法

Django 项目创建方法

以下为创建django创建方法步骤:

一、安装django模块

pip3 install Django

二、创建django项目

 (1)通过命令方式创建

django-admin startproject mystie

  (2)通过pycharm创建

  新建django项目

三、文件说明

  1、setting.py 配置文件

  2、urls.py 路由系统

  3、wsgi.py

  4、manage.py 启动文件

四、创建app(其中一个项目的名字,例如cmdb)

python3 manage.py startapp app1

五、在urls.py中添加路由映射关系

from django.conf.urls import url
from django.contrib import admin
from app1 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^index/‘, views.index),
]

 六、设置settings.py

#最后一行添加
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,‘statics‘)
)
暂时注释掉一行
#‘django.middleware.csrf.CsrfViewMiddleware‘,

在INSTALLED_APPS增加一条
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app1‘,
]

 七、创建数据库(举例)

在models.py中配置

class UserInfo(models.Model):
    nid = models.AutoField(primary_key=True)
    user = models.CharField(max_length=30)
    email = models.EmailField()

 执行命令创建数据库:

python3 manage.py  makemigrations
python3 manage.py  migrate

 八、在views.py中设置函数

from django.shortcuts import render
from django.shortcuts import HttpResponse

from app1 import models

# Create your views here.
# USER_INPUT = []
#

 # 内存版本
# def index(request):
#     # return HttpResponse(‘123‘)
#     if(request.method == ‘POST‘):
#         user = request.POST.get(‘user‘,None)
#         email = request.POST.get(‘email‘,None)
#         print(user,email)
#         temp = {‘user‘:user,‘email‘:email}
#         USER_INPUT.append(temp)
#
#     return render(request,‘index.html.bak‘,{‘data‘:USER_INPUT})


#数据库版本
# def index(request):
#     # return HttpResponse(‘123‘)
#     if(request.method == ‘POST‘):
#         u = request.POST.get(‘user‘,None)
#         e = request.POST.get(‘email‘,None)
#         models.UserInfo.objects.create(user=u,email=e)
#
#     # data_list是获取的数据的列表对象
#     data_list = models.UserInfo.objects.all()
#     print(data_list)
#
#     for item in data_list:
#         print(item.user,item.email)
#
#     return render(request, ‘index.html.bak‘, {‘data‘:data_list})

 九、在index.html里面设置

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>运维发布系统</title>
</head>
<body>
<h1 style="color: red">用户输入</h1>
<form action="/index/" method="POST">
    <input type="text" name="user" />
    <input type="text" name="email">
    <input type="submit" value="http://www.mamicode.com/提交">


</form>

<h1>数据展示</h1>

<table border="1">
    {% for line in data %}
        <tr>
            <td>{{ line.user }}</td>
            <td>{{ line.email }}</td>
        </tr>
    {% endfor %}
</table>

 

Django 项目创建方法