[S] claims to know the most concise and practical tutorial to get started Django

https://www.cnblogs.com/baiboy/p/django1.html

 

Summary: Django's tutorial is categorized, different forms. Or more official document system, or free style blog document, or tend to parse the document instance. Even official documents, chapters are more elaborate text cumbersome, and sometimes we just focus on a feature usage only, but the biggest problem free Bowen is copying each other, confusing structure, covering facet and errors are obvious. Thus, this paper sort data and project development experience during their studies, finishing up a more common and practical articles. Apply to (1) Getting Started, both C #, C, java, Python , R , etc. have any programming language can base; (2) want a quick overview of Django's get started and can quickly develop. (3) applies to a query as an information technology point of reference. ( This article original edited, reproduced indicate the source : known as the most simple and practical to use Django tutorial )

A few basic concepts 


 Preconditions : assumes a basic Python language-based, or have the basis for a programming language. You also familiar with web development environment, understand some css, js, db and so on.

What Django that?

Django Web application framework is an open source, written in Python. Software using MVC design pattern, i.e. the model M, and a controller C. view V It was originally developed to manage Lawrence Publishing Group's news to some of the content-based sites. It was released in July 2005 under the BSD license. This framework is based on the Belgian gypsy jazz guitarist Django Reinhardt named. Django's main goal is to make the development of complex, database-driven Web site easier. Django focus on reusability and "pluggable" components, agile development and law DRY (Do not Repeat Yourself). It is commonly used in Django Python, even including configuration files and data models.

-----Wikipedia

Django Web application framework is an open source, written in Python. MVC pattern using the frame, i.e. the model M, and a controller C. view V It was originally developed to manage Lawrence Publishing Group's news to some of the content-based website that is CMS (Content Management System) software. It was released in July 2005 under the BSD license. This framework is based on the Belgian gypsy jazz guitarist Django Reinhardt named.

----Baidu Encyclopedia

MTV development model?

Django is a framework based on MVC structure. However, in Django, the controller accepts user input portion discretion of the frame, so there is more concerned Django model (the Model), the template (Template) and view (the Views), called MTV mode. Their respective responsibilities are as follows:

(1) Model (the Model), i.e., the data access layer handles all matters related to the data: how to access and how to verify the validity of the relationship between the behavior and data which comprise the like.

(2) View (View), namely the presentation layer processing performance-related decisions: how to display the page or other types of documents.

(3) the template (Template), i.e. business logic and access the associated logic model retrieval of appropriate templates. Bridge model and template.

Django's architecture?

Let us glance Django whole picture:

urls.py inlet URL, corresponding to a function associated with the views.py (or generic class), access URL corresponding to a function.

views.py processing request issued by the user, from the corresponding urls.py over by the page rendering templates can display the content such as the login user name, user requested data, is output to the page.

models.py related to database operations, use this time to read data stored or, of course, when not using the database you can not use.

forms.py form, the user enters the data submitted in the browser, as well as verification of data generated input box and so on, of course, you can not use.

Function templates folder views.py in rendering templates in Html template, get dynamic content pages, can of course use caching to improve speed.

admin.py the background, you can use a small amount of code has a strong background.

settings.py Django setup, configuration files, such DEBUG switch, static files location.

The above py file does not understand it does not matter, will be detailed later. A picture is worth a thousand words, architecture picture of the working mechanism is as follows:

 

Django commercial sites everyone used

Sohu mailbox, shell network, watercress, love research, and easy of online cloud office, Yourong network, fast game play, ninety room, loans to help network, net interest odd, know almost, stylish and space, travel hee board: YxPad webpy, DNSPod international version, the kitchen, Betty's kitchen, Wopus questions and answers, plump net, scallop network, webmaster tools, easy of document management systems, personal rent, online document viewing - Easy degree cloud view, FIFA310 football data analysis expert, Sohu carry look like.

2 Django Prerequisites


 Preconditions: pip, python, sublime, anaconda environment is installed.

Kisaki置 conditions:

1
pip install django

Check whether the installation was successful:

 

xxx statistical analysis (decision) platform

System Environment: WIN10 64bit
development environment: sublime + Anaconda
database: Mysql 5.6.17
Language: python3.5
framework: django1.11 + Bootstrap
visualization tools: Highchart | Echarts | plotly | Bokeh ( using Echarts)

Basic Configuration 3 Django installation


 1 Create a project, the project decision analysis: xmjc_analysis

Xmjc_analysis created in the root directory of E:

1
django-admin startproject xmjc_analysis

effect:

settings.py project settings file
urls.py total urls profile
wsgi.py deploy server file
__init__.py directory structure python package of necessary and relevant calls.

2 Create App called analysis

1
django-admin startapp analysis

effect:

3 app settings.py new definition is added in the INSTALL_APPS

4 视图和网址创建第一个页面

(1)我们在analysis这个目录中,把views.py打开,修改其中的源代码:

1
2
3
4
5
6
7
8
9
10
'' '
第一个页面
author:白宁超
site:http: //www.cnblogs.com/baiboy/
'' '
#coding:utf-8
from  django.shortcuts import render
from  django.http import HttpResponse
def index(request):
     return  HttpResponse(u "欢迎进入第一个Django页面!" )

第一行是声明编码为utf-8, 因为我们在代码中用到了中文,如果不声明就报错.

第二行引入HttpResponse,它是用来向网页返回内容的,就像Python中的 print 一样,只不过 HttpResponse 是把内容显示到网页上。

我们定义了一个index()函数,第一个参数必须是 request,与网页发来的请求有关,request 变量里面包含get或post的内容。

(2)我们打开 xmjc_analysis/xmjc_analysis/urls.py 这个文件, 修改其中的代码:

1
2
3
4
5
6
7
8
9
10
from  django.conf.urls import url
from  django.contrib import admin
 
from  analysis import views  as  analysis_views
 
urlpatterns = [
     url(r '^admin/' , admin.site.urls),
 
     url(r '^index/$' , analysis_views.index,name= 'index' ),# 首页
]

(3)本地运行服务器测试

注意在项目根目录xmjc_analysis运行结果如下:

(4)页面传参数,显示欢迎‘admin’字样

修改view.py源码:

通过get方式接受页面参数,当然也可以采用post,结合form实现。效果如下

5 配置简单数据库操作,默认sqlite,咱们指定mysql数据库

(1)在xmjc_analysis/settings.py文件下修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'' '
配置Mysql数据库
2017年7月26日16:40:38
白宁超
'' '
DATABASES = {
     'default' : {
         'ENGINE' 'django.db.backends.mysql' ,
         'NAME' 'test' ,
         'USER' 'test' ,
         'PASSWORD' 'test123' ,
         'HOST' : 'localhost' ,
         'PORT' : '3306' ,
     },
}

xmjc_analysis/__init__.py下修改:

1
2
import pymysql
pymysql.install_as_MySQLdb()

(2)在analysis/models.py下设计数据库表,采用ORM方式

1
2
3
4
5
6
7
8
9
10
11
from  django.db import models
 
# Create your models here.
class  User(models.Model):
     username = models.CharField( '用户名' , max_length=30)
     userpass = models.CharField( '密码' ,max_length=30)
     useremail = models.EmailField( '邮箱' ,max_length=30)
     usertype = models.CharField( '用户类型' ,max_length=30)
 
     def __str__(self):
         return  self.username

(3) 在analysis/admin.py中定义显示数据

1
2
3
4
5
6
7
from  django.contrib import admin
from  .models import User
 
class  UserAdmin(admin.ModelAdmin):
     list_display = ( 'username' , 'userpass' , 'useremail' ) # 自定义显示字段
 
admin.site.register(User,UserAdmin)

(4)创建更改的文件,将生成的py文件应用到数据库

1
2
python manage.py makemigrations
python manage.py migrate

(5)创建超级管理员:用户名,test;密码密码:test123456

1
python manage.py createsuperuser

(6)登录后台查看信息

运行服务器:python manage.py runserver

 

可以看到后台信息,并对数据表进行增删改查操作,但是后台全部英文,可以改为中文显示?

后台管理设置为中文显示,xmjc_analysis/settings.py下修改代码:

1
LANGUAGE_CODE =  'zh-Hans'  # 中文显示

再去查看:

(7) Django 提供的 QuerySet API,shell玩转MySql

在xmjc_analysis下输入【 python manage.py shell】,然后查询数据表。

创建一条用户信息:

1
User.objects.create(username= "李白" , userpass= "libai123" ,useremail= "[email protected]" ,usertype= "超级管理员" )

后台查看:

其他操作方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 方法 1
User.objects.create(username= "李白" , userpass= "libai123" ,useremail= "[email protected]" ,usertype= "超级管理员" )
# 方法 2
twz =User(username= "李白" , userpass= "libai123" ,useremail= "[email protected]" ,usertype= "超级管理员" )
twz.save()
# 获取对象:
Person.objects.all()
# 满足条件查询
User.objects.filter(username= "李白" )
# 迭代查询:
es = Entry.objects.all()
for  in  es:
     print(e.headline)
# 查询排序:
User.objects.all().order_by( 'username' )
# 链式查询:
User.objects.filter(name__contains= "WeizhongTu" ).filter(email= "[email protected]" )
# 去重查询:
qs = qs.distinct()
# 删除操作:
User.objects.all().delete()
1
2
# 更新操作:
Person.objects.filter(name__contains= "abc" ).update(name= 'xxx' )
1
2
3
数据的导出:
python manage.py dumpdata [appname] > appname_data.json
python manage.py dumpdata blog > blog_dump.json
1
2
导出用户数据
python manage.py dumpdata auth > auth.json # 导出用户数据

(8)批量向数据表导入数据

将name.txt导入数据库:

数据导入源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
#coding:utf-8
#
 
 
from  django.core import serializers
import json
import os
os.environ.setdefault( "DJANGO_SETTINGS_MODULE" "xmjc_analysis.settings" )
 
 
'' '
Django 版本大于等于1.7的时候,需要加上下面两句
import django
django.setup()
否则会抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
'' '
 
import django
import json
if  django.VERSION >= (1, 7):#自动判断版本
     django.setup()
 
 
def main():
     from  analysis.models import User
     f = open( './readme/files/name.txt' ,encoding= 'utf-8' )
     for  line  in  f:
         name,pwd,email,type = line.split( '|' )
         User.objects.create(username=name,userpass=pwd,useremail=email,usertype=type)
     f.close()
 
def jsondb():
     from  analysis.models import User
     data = eval(serializers.serialize( "json" , User.objects.all())) # json
     userdata = json.dumps(data)
     print(type(userdata))
 
 
if  __name__ ==  "__main__" :
     main()
     # jsondb()
     print( '插入完毕!' )

查看结果:

 

>>   至此,基本熟悉上手了。深入学习待续...

Guess you like

Origin www.cnblogs.com/Ryan-Yuan/p/11545023.html