Django basis of the first chapter

 table of Contents

  1.Django MTV framework Introduction

  2. Basic commands create a configuration description of the project

  3. The front and rear end interactive Case

  4. change search database for data interaction based deletions

Introduction to Django

     Django framework draws on MVC design patterns of thinking, and different points of MVC is that it split into three parts, namely: (Model) model, (Template) template, and (View) view

MTV MVC and knowledge to add: 

MVC is the first letter of the abbreviation of three words, they are the model Model, View, and Controller view control.

     1) top layer, is directly facing the "View layer" end user (View). It is provided to the user interface, is the shell.

     2) the bottom layer, is the core of the "data layer" (the Model), program information or data that is to be operated.

     3) an intermediate layer, that is, "control layer" (the Controller), which is responsible for the user instruction input from the "View layer" Select Data "data layer" in accordance with, and then subjected to the corresponding operation, to produce the final result.

 (Ps: three layers are closely linked, but are independent of each other and change each layer without affecting other layers inside of each layer provide external interfaces (Interface), calls for a layer above.)

 

  Django's MTV

    Model model: object is responsible for database objects (ORM)

   Template Template: Responsible for how to display a page to the user

   View View: responsible for business logic, and calls the Model and Template at the appropriate time

In addition, Django urls as well as a distributor, it is the role of a URL of a page request distributed to view different treatment, call the appropriate view in the Model and Template

   

  

Create a django project

1 . Create a project 
Django - ADMIN startproject mysite

 2 . After creating the project, you can view the current directory folder called mysite extra folder 
mysite / 
    manage.py 
    mysite /
         __init__ .py 
        settings.py 
        urls.py 
        wsgi.py 

3 starting the project
the p-
ython manage.py the runserver # default port 8000

specified port
python manage.py runserver 8888 # 8888 for the newly designated port
python manage.py runserver 127.0.0.1:8000 # You can also specify IP and port, separated by colons 

4. Create app
app01 / 
    Migrations 
        __init__.py 
    __init__.py 
    admin.py #admin configuration 
    apps.py # 
    models.py # interacts with the database when used orm 
    test # tests.py 
    views.py # write function with 

5. Database Migration
manage.py makemigrations Python 
Python manage.py the migrate 

6. Create a superuser
manage.py createsuperuser Python 


: principle
needs to be done in the appropriate configuration setting which later created the project, if the project is created by the command you need to create your own additional app (app is mainly used to write specific functions), and templates (stored template file)

the following is the login password after a successful jump to the success of small cases page:
1. create a Python manage.py startapp app01 app01 directory you've created will automatically generate the appropriate file
2. create templates directory
configuration settings and support app01 Template

= The INSTALLED_APPS [ 
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles' ,
'app01.apps.App01Config', # add this line can be directly introduced into the class
]

= TEMPLATES [ 
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join (base_dir, "Templates")], # add this line, if the project is created pycharm the default is ok.
'APP_DIRS': True,
'the 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',
],
},
},
]


Notes csrf middleware to support form submission (use test)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Adding mysql configuration with the second case, the first case do not interact with mysql so you can safely ignore
pymysql Import 
pymysql.install_as_MySQLdb () # init generally on the same level settings file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Day14',
'the HOST ': "127.0.0.1",
"PORT": 3306,
"the USER":' the root ',
"PASSWORD":' Wang ',
}
}

modify a static file stored, for later use standardized
STATIC_URL = '/ static /' # alias corresponds 
STATICFILES_DIRS = [
the os.path.join (base_dir, "static")
]
point to an end setting

Example: a simple case of interaction front and rear ends
modify url distributor, corresponding to the route, the user forwarding operations to be performed under the app01 views which, of course, a function of writing where all right but for the standardization of written views inside
from app01 import views import module views 

the urlpatterns = [
URL (R & lt 'ADMIN ^ /', admin.site.urls),
URL (R & lt 'Login ^ /', views.login),
URL (R & lt 'index ^ /', views .index) written on a particular function

]
logic code inside views
from django.shortcuts import render,redirect,HttpResponse

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


def login(request):
if request.method == 'POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == 'admin' and pwd == 'admin':
#用户登录成功
return redirect('/index/')
else:
return render(request, 'login.html',{"error":"用户名或密码错误"})
return render(request,'login.html')

模板文件
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="" method="post">
<p>
<label for="username">用户名</label>
<input type="text" id="username" name="user">
</p>
<p>
<label for="password">密码</label>
<input type="password" id="password" name="pwd">
</p>
<p>
{{error}}
</p>
<input type = "submit" value = " Login"> success.htmlAfter a successful login redirects to this directory</ HTML></ body>
</ form>




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
登录成功
</h1>
</body>
</html>


验证结果:

python manage.py runserver to start the project

 

Enter the correct user name and password

otherwise

 

After the operation of the database connection 

Django mysql database configuration using
     1 creates a database mysql.
     2 arranged in settings in the database:
     3 . Mysql database modules are connected using pymysql 
        __init__.py at the same level directory settings: 
        Import pymysql 
        pymysql.install_as_MySQLdb ()    
     . 4 . create a table, based on models.py written under the app:
             from django.db Import Models 


            # the Create your Models here Wallpaper. 
            class the UserInfo (models.Model): 
                username = models.CharField (MAX_LENGTH = 32)   # VARCHAR (32)     
                password models.CharField = (max_length = 32 ) # delete comments represent

    
     5 . command to perform a database migration
        manage.py makemigrations Python   # create the migration file is recorded on the recording models.py change the 
        Python manage.py the migrate           # perform database migration  

orm specific operation:
RET = models.Publisher.objects.all () # query list of all data objects
for I in RET:
Print (I, type (I)) # corresponding to the object database a data
print (i.name, i. id) # attribute value field

 
 

models.Publisher.objects.filter (name = publisher_name) is finding an empty list

 
 

models.Publisher.objects.create(name=publisher_name) 新增

 
 

models.Publisher.objects.filter(id=id).delete() 删除

 
 


Modify
publisher_name = request.POST.get ( 'publisher_name')
# edit
pub_obj.name = publisher_name # change only in memory
pub_obj.save () # save the changes to the database

 
 


模板
{% for pub in ret %}
<tr>
<td>{{ pub.id }}</td>
<td>{{ pub.name }}</td>
</tr>
{% endfor %}

 

Database search operation example of how excision Based

A query in a database and display the read data on the front file 


models.py configuration file 
from django.db Import Models 

class Pulisher (models.Model): 
    name = models.CharField (MAX_LENGTH = 32)   # create tables and fields 

python manage. makemigrations Py 
Python manage.py the migrate 
over which add their own table in order to show the effect of several records 

add functions performed in the url name dispenser 
rlpatterns = [ 
    url (R & lt ' ^ ADMIN / ' , admin.site.urls), 
    url (R & lt ' ^ Login / ' , views.login), 
    URL (R & lt ' ^ index / ' , views.index), 
    URL (R & lt 'be publisher_list ^ / ' , views.publisher_list)   # Name function name corresponding to views which 


functional logic inside views 
from app01 Import models   # need to import module models, based on this module to enable subsequent operation 
DEF be publisher_list (Request): 
    RET = models.Pulisher .objects.all ()
     # for I in RET: 
    #      Print (I, type (. 1)) 
    #      Print (i.name, i.id) 
    return the render (Request, ' publisher_list.html ' , { " RET " : RET }) 

publisher_list.html template configuration file
 <! DOCTYPE HTML> 
<HTML lang = "en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>出版社列表</h1>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>名称</th>
    </tr>
    </thead>
    <tbody>
    {% for pub in ret %}
        <tr>
            <td>
            {{pub.id}}
            </td>
            <td>
            {{pub.name}}
            </td>
        </ TR>

    { % Endfor% }
     </ tbody> 
</ Table> 
</ body> 
</ HTML> 

The results are shown:

ps: Since the construction of the table publisher_list when I wrote a few letters, so when the name of the module to import models, as otherwise it will error.

 

 2. Add instance

models add a table inside

Pulisher class (models.Model): 
name = models.CharField (MAX_LENGTH = 32)

URLs added function name
= the urlpatterns [ 
URL (R & lt 'ADMIN ^ /', admin.site.urls),
URL (R & lt 'Login ^ /', views.login),
URL (R & lt 'index ^ /', views.index),
URL (R & lt 'be publisher_list ^ /', views.publisher_list),
URL (R & lt 'add_publisher ^ /', views.add_publisher)
]

views written inside the detailed implementation logic, if the field is present prompts to add, if there is no add
def add_publisher(request):
if request.method == 'POST':
publisher_name = request.POST.get("publisher_name")
ret = models.Pulisher.objects.filter(name=publisher_name)
if ret:
return render(request, "add_publisher.html",{"error":"出版社名称已存在"})

models.Pulisher.objects.create(name=publisher_name)
return redirect("/publisher_list/")
return render(request,"add_publisher.html")

add_publisher.html 里面的代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<p>
<label for="">出版社名称</label>
<input type="text" name="publisher_name"><span>{{error}}</span>
</p>
<button>新增</button>
</form>
</body>
</html>

结果展示

添加不存在的直接添加并展示出添加后的结果

 

 

3.删除例子

urls添加函数名

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^publisher_list/', views.publisher_list),
url(r'^add_publisher/', views.add_publisher),
url(r'^del_publisher/', views.del_publisher)
]

views里面的函数逻辑
def del_publisher(request):
id = request.GET.get("id") #这里的GET是url携带的参数
models.Pulisher.objects.filter(id = id).delete()
return redirect("/publisher_list/")

publisher_list.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>出版社列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for pub in ret %}
<tr>
<td>
{{pub.id}}
</td>
<td>
{{pub.name}}
</td>
<td><a href="/del_publisher/?id={{pub.id}}">删除</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
验证结果:
访问地址直接点击删除即可。

4.修改操作


urls添加函数
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^publisher_list/', views.publisher_list),
url(r'^add_publisher/', views.add_publisher),
url(r'^del_publisher/', views.del_publisher),
url(r'^edit_publisher/', views.edit_publisher),
]

views里面函数逻辑
def edit_publisher(request):
id = request.GET.get("id")
pub_list = models.Pulisher.objects.filter(id=id)#拿到对象列表
print(pub_list)
pub_obj = pub_list[0]
print(pub_obj)

if request.method == "POST":
publisher_name = request.POST.get("publisher_name")
pub_obj.name = publisher_name
pub_obj.save() #保存修改到数据库
return redirect("/publisher_list/")
return render(request,"edit_publisher.html",{"pub_obj":pub_obj})

publisher_list原有的基础上添加:
<a href="/edit_publisher/?id={{pub.id}}">编辑</a></td>
edit_publisher.html文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<p>
<label for="">出版社名称</label>
<input type="text" name="publisher_name" value="{{pub.obj.name}}"><span>{{error}}</span>
</p>
<button>保存</button>
</form>
</body>
</html>

完成!

 

Guess you like

Origin www.cnblogs.com/guniang/p/11188675.html