Django project creation process

1. Create a Django project root directory

  . a imperative to create a method: Django-ADMIN startproject Project Name

  b.pycharm create law: as shown below

 

2. Configure setting environment

  a. Configure a static file

    STATIC_URL = 'static' -> Alias ​​static folder

    STATICFILES_DIRS = [-> Folder real static position

      os.path.join(BASE_DIR, "static"),
    ]

  b. Note csrf statements (about 47 lines)

 

2.1 Creating APP (APP has been added and a case Django project)

  First of all: the need, through the cmd command or pycharm above terminal commands, go to the directory where the project

  Then (the command): Python manage.py startapp APP name

  Then again: must again setting file inside INSTALLED_APPS add APP environment in the newly created command is as follows "app01.apps.App01Config,":

 

3. Use the ORM database link (ask understandable create ORM)

  A. ORM can not create the database, so the need to manually create the database

    create database database name of the charset = utf;

  b. layout condition and then setting the connection to the database file    

  = {DATABASES 
  'default': {
   'ENGINE': 'django.db.backends.mysql', database connection type #
   'HOST': '127.0.0.1', connected to the address database #
   'PORT': 3306, # port
   'nAME': "day61", # database name
   'uSER': 'root', # user
   'pASSWORD': '123456' # password
   }
  }

  . c another project with __init__.py file directory added:

    import pymysql

    pymysql.install_as_MySQLdb()

   The purpose here is: instead of telling Django MySQLdb with pymysql module to connect MySQL database

  d. Create a data table class in app01 / models.py above

    from django.db import models

    class UserInfo (models.Model): Be sure to inherit models.Model

      id = models.AutoField(primary_key=Ture)

      name = models.CharFiel(max_length=30,null=False)

      ………………

    注意:这里创建得到的表名格式为:APP名称_表名(小写)。例如:app01_userinfo

  e.pycharm上面的terminal命令,进入到项目所在的目录 

    1. python3 manage.py makemigrations             //记录当前models文件中修改的内容,记录到app01下面的migration里
    2. python3 manage.py migrate //告诉数据库,models文件中针对数据库的修改。或者说,把Django里面的重新的定义的sql语句,翻译成为真正的sql语句,并告诉数据库

 4.ORM使用流程

  首先要学习Django开发的程序与浏览器的通讯流程:

    1.启动服务器(Django),等待客户端(浏览器)URL连接访问(请求:request);

    2.浏览器上输入URL地址,和服务器建立了连接,此时浏览器向服务器发送了请求

    3.服务器(Django)接收到请求消息后,解析消息,根据URL路径,知道该URL路径与函数的对应关系,进而找到对应的函数

    4.进入对应的函数, 打开HTML 文件,将数据库的数据替换到HTML对应的位置,得到一个最终需要的HTML文件内容

    5.Python服务器根据http协议,将所得到的HTML内容返回给浏览器(响应:response)

    6.浏览器收到服务器响应回来的HTML内容,根据CSS等文件对网页渲染,并展示给用户观看

    7.关闭连接

 例如:上面的建立的(app01_userinfo)表如下:

 

  4.1  查:把数据库的表的数据显示在网页上

    1.先假设预定的URL为  http://127.0.0.1:8000/user_list/,而/user_list/就是需要用到对应关系

 

    2.在urls.py文件上的urlpatterns加入对应关系           


  
    2.1 因为,Django上的所有函数(逻辑都是放在APP的views.py文件中的)
      所以上面需要导入viems.py文件
      所以,上面的代码应该变成

      from app01 import views
      urlpatterns = [
       url(r'^admin/', admin.site.urls),
       url(r'^user_list/',views.user_list),
      ]
    3.开始写user_list函数了(注意:是在app01里面的views.py文件里面写哦)
      这里需要导入两个模块(django.shortcuts和app01):

def user_list(request):
    ret = models.UserInfo.object.all()    # 获取表的所有记录
    return render(request, "user_list.html",("user_list":ret))        # 打开user_list.html文件,把找到的记录数据放到html对应的位置上

      4.开始写user_list.html文件咯

        注意html文件数据模板文件,所以他们全都放在templates文件夹中

        这里只写表格部分,其他的html代码不写了。        

<body>
<table border="1">
    <thead>
    <tr>
        <th>id值</th>
        <th>用户名</th>
    </tr>
    </thead>
    <tbody>
    {% for user in user_list %}    <!--这里的user_list对应user_list函数里面的“return render(request, "user_list.html",{"user_list": ret})”  中的  {"user_list": ret} 的 user_list  -->
        <tr>
            <td>{{ forloop.counter }}</td>    <!--自增序号-->
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>        


  4.2增。用网页添加数据到表app01_userinfo
    1.同理:预定URL。为/app_user/
    2.在urls.py文件添加URL与处理函数的对应关系。      
from app01 import views      #导入函数所在的模块
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^user_list/',views.user_list),
    url(r'^add_user/',views.add_user),
]

      3.进入views模块编辑add_user函数

        

def add_user(request):
    pass

      4.上面函数先不写,先写add_user.html模板

        在原先的user_list.html上添加一个进入add_user.html的a标签:<a href="/add_user/">添加用户</a>          

       

         开始写add_user.html模板了:          

<form action="/add_user/" method="post">        <!--   ”/add_user/“提交的时候,是提交到URL路径,然后再经过urls.py文件进入到对应的add_user函数。。。。。提交数据:method使用post方法   -->
    <p>用户名:
        <input type="text" name="username">      <!--  name属性是python获取html输入框中的数据的关键途径  -->
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
  <p style="color:red">{{ error }}</p>     <!-- 这里的error是因为下面再完善add_user函数中新添加的 -->
</form>

      5.完善views.py 文件中的add_user函数        

def add_user(request):
    error_ms = ""
    if request.method == "POST":
        new_name = request.POST.get("username", None)
        if new_name:
            models.UserInfo.object.create(name=new_name)
            return redirect("/user_list/")    
        else:
            erro_msg="输入框不能为空"
    return render("request","add_user.html",{"error":error})

 


    

 


        

 

Guess you like

Origin www.cnblogs.com/mashangsir/p/11415955.html