Python Django Framework Note (iii): A simple description of how Django works and the creation of a user interface

Source: Internet
Author: User

(i) Description

A brief description of how Django works, with 2 examples.

(ii) How Django works

Suppose we have the following files, here in the first 2 articles based on the addition of the templates directory (storing HTML files) and static directory (storage image JS, CSS, etc.)

(iii) Implementation of a complete user interface

# Suppose you've created a project and an app. The following urlconf and view functions have no relationship, according to their preferences, you can write the view function first, you can also define the urlconf.

There are several steps below

(1) Creating a model

(2) Define the project's urlconf (mysite/mysite/urls.py file) This part of an application is only defined once.

(3) Define the urlconf of the application (mysite/blog/urls.py)

(4) Implement urlconf corresponding view function (at the same time in the creation of template file (Mysite/blog/templates directory, is actually HTML file, but is to use the Django template language to write it, of course, there can be pure HTML code, Django templates are often used to automatically generate HTML code)

(iv) Example: implementation Code (blog home page)

(1) Create Model blog/models.py (after creating the model, it is definitely to create a table structure, this will not say, do not know to see my Django notes on the previous article)

1  from Import Models 2 # Create your models here. 3 # Model (blog information model, similar to blog Park essay, including title, body content and creation time) 4 class blogpost (models. Model):5     title = models. Charfield (max_length=150)6     BODY = models. TextField ()7     timestamp = models. Datetimefield ()

(2) Define the project's urlconf (mysite/mysite/urls.py file) This part of an application is only defined once.

 fromDjango.contribImportAdmin fromDjango.urlsImportPath,include,re_pathurlpatterns= [    #What is the first parameter when using path, what is actually, and the second parameter is the same as the Re_pathPath'admin/', Admin.site.urls),#when using Re_path, the first parameter is a regular expression object, the second argument is either the view function that matches the URL pattern, or the include () point to another urlconf    #when using include, such as http://localhost:8000/blog/login/, the function will remove ... blog/, then pass the login/to the application's urls.py file.Re_path (R'^blog/', Include ('Blog.urls')),]

(3) Define the urlconf of the application (mysite/blog/urls.py)

# urls.py  from Import Path,re_path  from Import  = [    # Blog Main Page, this can be understood as a point to http://localhost:8000/blog/request, all by views.py's archive function processing     Re_path (R'^$', views.archive),]

(4) Implement urlconf corresponding view function mysite/blog/views.py (at the same time in the creation of template file (Mysite/blog/templates directory, is actually HTML file, but is to use the Django template language to write it, of course, There can also be plain HTML code, and Django templates are often used to automatically generate HTML code).

1  fromDjango.shortcutsImportRender2  fromBlog.modelsImportblogpost3 #Get blog information and render it to the page4 defArchive (Request):5     #get all data for blogpost and sort in reverse order timestamp6Posts = BlogPost.objects.all (). Order_by ('-timestamp') [: 10]7     #return Render_to_response (' archive.html ', {' posts ': Posts, ' form ': Blogpostform},requestcontext (Request))8     returnRender (Request,'archive.html',{'posts': Posts,})

(5) Create a template file mysite/blog/templates directory to create HTML files (files can be created before creating a view function, and so on when the view function is written and then implemented). To facilitate reading, I removed all the pure HTML code, and base.html inheritance, all only with the following, see the interface and my affirmation is not the same. (On the inheritance of base.html here is not to explain, or a bit confusing)

The simple explanation below 1, {percent percent} is the template tag, used to write for if, else and so on (the following for, and the pure Python for is the same), this tag a lot, here first about the line

2, {{}} is a variable, meaning that the value of this variable is inserted here

3, it is not difficult to find posts is actually the views.py archive function in the third parameter of the key value (Conetext, similar to a dictionary)

1 {% for post in posts%}2      <ahref=""><H2>{{Post.title}}</H2></a>3       <P>{{Post.body}}</P>4       <P>{{Post.timestamp}}</P>5        <HR>6 {% ENDFOR%}

Login, New button on the far right, this is not fully displayed

(v) Login page and login verification implementation code (steps are the same)

#UTLconf的配置这里就略过了

(1) Model blog/models.py. Compared to the above, there is a form loginpostform, used to automatically generate HTML code. Can be tested in the Python manage.py shell, using the instructions in https://docs.djangoproject.com/en/dev/intro/tutorial02/

1  fromDjango.dbImportModels2  fromDjangoImportForms3 #Create your models here.4 5 #Model (Login page model, including account, password)6 classLoginpost (models. Model):7User_account=models. Charfield (max_length=150)8User_password=models. Charfield (max_length=150)9 #form (Login page form, Django automatically generates HTML code based on the model)Ten classLoginpostform (forms. Modelform): One     classMeta: AModel=Loginpost -Fields ="__all__" -labels={ the             'User_account':'Account', -             'User_password':'Password' -}

(2) Implement the View function.

 fromDjango.shortcutsImportRender fromDatetimeImportdatetime fromBlog.modelsImportBlogpost,blogpostform,loginpost,loginpostform fromDjango.httpImportHttpresponseredirect#Render Login PagedefLogin (Request):returnRender (Request,'login.html',{'form': Loginpostform,})#login verification, user name, password is correct redirect to the blog pagedeflogin_verification (Request):ifRequest.method = ='POST':        #get user-submitted account and password informationUser_account = Request. Post.get ('User_account') User_password= Request. Post.get ('User_password')        #compares the account and password to the data in the database, and true redirects to the blog page         forLinchLoginPost.objects.all ():ifUser_account ==l.user_account anduser_password==L.user_password:returnHttpresponseredirect ('/blog/')

(3) model (also removed part of the code here), the following fourth line {{form}}, is actually a view function login () render the third parameter of the key value (Loginpostform will automatically generate HTML code)

1<form action="/blog/check/"Method="Post">{% Csrf_token%}2<table align="Center">3<tr >4&LT;TD style="width:20px;height:300px">{{form}}</td>5&LT;TD >6<input Type=submit value="Login">7</td>8&LT;TD >9<input Type=button value="Register">Ten</td> One</tr> A</table> -</form> -

(vi) share a simple code (interested can refer to the above template is not posted out of the section, there are)

Https://pan.baidu.com/s/1yIT7gRfFFWZhNRxL_qQaMw

The main implementation of the following 3 features:

(1) The main page showing the blog information

(2) Implement login verification (registration function is not implemented, so directly plug in the data into the database)

(3) Create a blog and submit it to the database

(vii) Oracle's stored procedures (BULK insert data to see the effect.) Of course, you can also use other methods, such as Python manage.py Shell to create specific objects to insert, or directly connected to the database, with a for loop to insert, etc.)

1 Create or Replace procedureAdd_data2  as3The_num Number( One);4Titlevarchar(255);5 BD CLOB;6 begin7Title:= 'Web development can also be developed on the basis of others, in addition to all new writes';8BD:='Web Development, in addition to all new writing, can also be developed on the basis of other people, simplifying the development process. These web development environments are collectively referred to as Web frameworks, and the goal is to help developers streamline their work, such as providing functionality to accomplish some common tasks, or providing resources to reduce the effort to create, update, execute, or scale applications. 9 The Python Web framework can be a single or multiple sub-component, or it can be a full-stack system. The term "full stack" means that you can develop code for all stages and levels of a Web application. The framework can provide all related services, such as Web servers, database ORM, templates, and all required middleware hooks. Some also provide a JavaScript library. Django is one of the most well-known web frameworks in the range. ';Ten    forIinch 1.. -Loop OneThe_num:=i; A     Insert  intoBlog_blogpostValues(The_num,title||To_char (the_num), BD||To_char (the_num), sysdate); -   EndLoop; -   Commit; the End;

Once the stored procedure is created, use the following execution.

1 begin 2   add_data (); 3 End;

Python Django Framework Note (iii): A simple description of how Django works and the creation of a user interface

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.