Summary of Python+django knowledge points

Source: Internet
Author: User
Tags django server

Here are some of their own learning process of knowledge points, need to see, I am still a small rookie, because need to learn to use the Django Framework also write a Web try:

1: Run server: Python manage.py runserver 8080 (can specify port also can use default 8000, do not write)

2: Migrating the database: Python manage.py makemigrations
3: Implement database Migration: Python manage.py Migrate
4: Enter shell module: Python manage.py Shell
5: Create Django Management module: Python manage.py createsuperuser

6: Register the Django Model with admin (set in the admin.py file in the project):

From mydjango.models Import *

Admin.site.register (BookInfo)
7: Set the field to display in the background (set in the admin.py file):
Class Bookinfoadmin (admin. Modeladmin):

List_display = [This writes the name of the field to be displayed], such as List_display = [' id ', ' btitle ', ' bpub_date ']; #在admin显示的字段名

List_filter = [' Btitle '] #设置个过滤器, that is, to display to the right of the page, to search for

List_per_page = Ten #设置每个页面显示的数据的条数

Search_fields = [' Btitle '] #设置搜索框的列表

Then register this list in 6: Admin.site.register (BookInfo, Bookinfoadmin)

Or you can do it with an adorner, and write @admin.register (BookInfo) in front of the class.

Set the admin site to display as Chinese and time zone (in setting.py) set to: Language_code= ' Zh-hans ' and time_zone= ' Asia/shanghai '

Set the inline class (or add the contents of the inline class when you add a table of data):

For example: Class Neiqian (admin. Tabularinline):

Model = Scord #对应要内嵌的数据库表

Class Studentadmin (admin. Modeladmin):

Inlines = [Neiqian] #对应要内嵌的类

8: Installing MySQL driver: Python install mysqlclient
9: Use MySQL to set up in Django setting.py:
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': ' Djangodb ',
' USER ': ' Root ',
' PASSWORD ': ' mao15897610067 ',
' HOST ': ' localhost ',
' PORT ': ' 3306 ',
}
}
10: Enter Python's shell control to write the code:
Python manege.py Shell
11:url Regular Expression matches:
(1): Match number: [0-9] or \d
(2): Match multiple numbers: [0-9]+ or \d+
12: Store session (set in setting.py file)
(1) settings stored in the database: session_engine= ' django.contrib.sessions.backends.db '
(2) settings stored in memory: session_engine= ' Django.contrib.sessions.backends.cache '
(3) settings stored in memory and database: session_engine= ' Django.contrib.sessions.backends.db_cache '
13: In the view.py file,
(1) Reference HTTP Module: from Django HTTP import *;
(2) Reference Modele module: from. Modele import *;
14: Configure CSRF Validation in form: {% Csrf_token%}
15: Configure the storage of the static files (under the setting.py file):
Static_url = '/static/' (this will usually be written by default.)
Staticfiles_dirs=[os.path.join (Base_dir, ' static ')]
The name of the word, is generally called "static", of course, you can make changes, just create the name and this corresponds to it, the default is generally used with this name is better. Then create the corresponding static folder under the directory, and then create the same folder as the application (of course, for different static files, but also in the directory can also create sub-directories for easy management, such as JS, CSS, IMG, etc.).
16: Refer to the picture below the static file in the template
(1) method one: Use absolute path, for example:
(2) Method Two: Use the dynamic way to use: for example
Which, above the Mydjango is the name of my application
The advantage of method Two is that this address will not be found at random, and it is not easy to have an impact with the name of the setting, which is dynamic.
The point of note for method two is to quote the following sentence at the beginning of the template:
<% load static from Staticfiles%>
17: Using the middleware in Django:
Function: A request to interfere with the entire URL (a slice-oriented idea, similar to the IOC and Di (inversion of Control) in spring):
How to use: Add settings to the location of the middleware in setting.py, such as:
(1) Create a. Py class in the app directory, such as creating a myexception.py
(2) Create a class, such as
From Django.http Improt *
Class Myexceptionhappend ():
def process_exception (Request, Response, exception):
return HttpResponse (Exception.Message);
Here is a simple way to do a demonstration, the role of which is when the access view occurs when an exception, the exception to print out
(3) Add settings in setting.py, i.e. middleware_classes= (' mydjango/exception.myexceptionhappend ')
Remember: Only the following five methods in the middleware can be used
(1) before interfering with URLs: using the Process_request () method
(2) before interfering with view: Using the Process_view () method
(3) After the interference view is executed, that is, before Templete: Using Process_template_resonce ()
(4) When an exception occurs in the execution view: using the Process_exception () method
(5) After templlate: Use the Process_response () method

18: Upload Picture (file) Step:
(1) First, you need to set the corresponding Picture property in the Models class field, such as Myimg = models. Imgfield (upload_to= ' cars/')
In the above, set up, uploaded images will be uploaded to the cars/directory (you can set it yourself)
(2) If you have not downloaded this Pillow in Django, you need to download it first, in cmd, pip install pillow==3.4.1
The version must be at least 3.4.1 or more, since there is no storage that supports pictures
(3) Because the uploaded image will be configured in the server directory under the STAITC directory of media, this directory is used specifically for the upload of resources to manage,
So you need to set one in setting.py: Media_root = Os.path.join (Base_dir, "static/media/")
(4) Under Static, create a media directory, which is the default storage for uploaded files
Note: The type is file in the Input tab of the HTML that submits the picture or file, and the from form must have Enctyoe = "Multipart/from-data" attribute
For example: <from action= "" method= "post" Enctyoe = "Multipart/from-data" > otherwise cannot commit to the server accept
Example: (1) HTML for uploading images
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title> upload images or files </title>
<body>
<form action= "/index/picturehandle/" method= "post" enctype= "Multipart/form-data" >
{% Csrf_token%}
<lab> Select the file you want to upload </lab>
<input type= "file" name = ' picl ' ><br>
<input type= "Submit" value= "upload" name= "submit" >
</form>
</body>
(2) The view method for downloading the transferred content:
#测试文件上传之后的处理
def picturehandle (Request):
#拿到上传过来的文件
Picture = Request. files[' picl '];
#拼凑保存到服务器中文件的名字
filename = os.path.join (settings. Media_root, Picture.name)
#解析传过来的图片并且写到服务器对应的目录media下
with open (filename, ' wb+ ') as readcontent: #注意这里的读取方式要为 ' wb+ ', otherwise there will be a problem
For-Con in Picture.chunks (): #这是读取的方式
Readcontent.write (con);
#将服务器中存储的图片进行显示
Return HttpResponse (' '%picture.name ');

19:template Inheritance:

(1) Define what needs to be populated: {% block content%} {% Endblock content%} #这样的话, the contents of this content will be replaced with the corresponding content when the inherited page is populated directly

(2) You need to write the inherited page at the beginning of the template: {% extends ' myhtml/base.html '%}

20: Paging Content

Objects: Paginator, how many pages are the management data divided into?

Objects: page, managing the contents of a page

Examples of usage:

(1) in view.py

1 #Testing the paging operation2 #Python Learning Exchange Group: 5483778753 defshowdblist (Request):4      #get the data to display5List =BookInfo.objects.all ();6      #gets the paged object, and divides the queried data into 4 pages7Paginator = Paginator (list, 4);8      #get the number of pages to display9index = Request. Get.get ('pagenumber');Ten      #determine if there is a number of pages passed in the request, if not the first access, that is, the default access to the first page One      ifindex = =None: Aindex = 1; -      #get the object that manages each page pages -page =paginator.page (Index) theContext ={'page': page}; -      returnRender (Request,'mydjango/showlistdate.html', context);

(2) in urls.py

1  URL (r'^showdblist' , views.showdblist),

(3) in templates

1<! DOCTYPE html>2"en">34<meta charset="UTF-8">5<title> Show Paging Content </title>67<body>8<center>9<ul>Ten<!--get each data object in the corresponding page-- One{% forEverypageinchPage%} A<li> {{Everypage.btitle}}</li> -{% ENDFOR%} -</ul> the -<!--display the corresponding page number- -{% forIndexinchPage.paginator.page_range%} -<!--If the content of the current page number is displayed, color the page number-- +{%ifindex = = page.number%} -<a style="color:red">{{Index}} </a>   +{%Else%} A<!--to pass the clicked page number to the past for easy display of the corresponding content-- at<a href="/index/showdblist?pagenumber={{Index}}"style="Color:green">{{Index}}</a>   -{% ENDIF%} -{% ENDFOR%} -   -</center> -</body> in

Python read and Write Data excl table

1 defreaduserinfomationfile (Request, filename):2     #write the file path that the server uploads over3Webfilename = Os.path.join (settings. Media_root, filename)//This is a excl path that you read in the Django server4     #Open File5Workbook = Xlrd.open_workbook (r"'+webfilename)//If you want to read the local excl, then the path can be written, for example: (r'F:\demo.xlsx')6     #Get all sheet7     #workbook.sheet_names ()8     #get the first sheet name9Sheet2_name =workbook.sheet_names () [0]Ten     #get sheet content based on sheet index or name OneSheet2 = Workbook.sheet_by_index (0)#Sheet Index starting from 0, the first sheet is 0 because there can be more than one sheet in a excl table A     #Sheet2 = workbook.sheet_by_name (' Sheet2 ') #这是直接通过名字进行获取 -   -     #sheet name, number of rows, number of columns the     Print(Sheet2.name, Sheet2.nrows, Sheet2.ncols) -   -     #gets the value of the specified entire row and column (the array type is returned) -rows = Sheet2.row_values (3)#get the fourth line of content +cols = Sheet2.col_values (2)#get third column content -     Print(rows) +     Print(cols) A   at     #gets the contents of the specified cell (three methods) -     Print(Sheet2.cell (1, 0). Value) -     Print(Sheet2.cell_value (1, 0)) -     Print(Sheet2.row (1) [0].value] -     #gets the data type of the cell contents -     #ctype:0 empty,1 String, 2 number, 3 date, 4 Boolean, 5 error in     Print(Sheet2.cell (1,0). CType)

Reprinted: 75267823

Summary of Python+django knowledge points

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.