In fact, it takes only three steps to implement a function in Django, and I'll call it a trilogy.
This trilogy is:
- Defining the URLs Map
- Define Views
- Define Templates
What is a URL?
URL even if a Web address, you enter this address in the browser, and then the browser back to the corresponding page to you. For example http://djangogirls.com is a URL, and 127.0.0.1:8000 is also a URL, the default is the HTTP protocol.
How URLs work in Django
We opened the mysite/urls.py file and found something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
from django.conf.urls Import patterns, include, url from Django.contrib import admin admin.autodiscover () urlpatterns = Patterns ( # Examples: # url (r ' ^$ ', ' mysite.views.home ', Name= ' home '), # url (r ' ^blog/', include (' Blog.urls ')), URL (r ' ^admin/', include (Admin.site.urls)), Span class= "line") |
The above two lines of comments do not tube, this will be used later. Django has added the admin URL configuration for us by default. When Django encounters a URL that starts with admin/, it goes to Admin.site.urls to find a match. All admin-related URLs are written in a single file, which makes it easy to manage.
Regular expressions
You can see that the URL above uses a regular expression, such as ' ^admin/', ' ^$ ', and so on, and Django is using regular to match the URL. About the regular style here do not want to expand too much. You can refer to the relevant data and tutorials.
First Django URL configuration
Now we're going to map the Http://127.0.0.1:8000/home address to a page that shows a list of the latest articles. The General Blog Home page is basically the case.
To keep an introduction to the mysite/urls.py profile, we'd better put the URL configuration of the blog in a separate file. In the mysite/urls.py to the introduction of it can be.
Then your mysite/urls.py file is now similar to this:
1 2 3 4 5 6 7 8 9
|
Import patterns, include, url
Import Admin Admin.autodiscover ()
Urlpatterns = Patterns ("', URL (R ' ^admin/', include (Admin.site.urls)), URL (R ', include (' Blog.urls ')), )
|
Blog.urls
Create the file blog/urls.py, and then add the following:
1 2 3 4 5 6
|
Import patterns, include, url Import views
Urlpatterns = Patterns ("', URL (R ' ^$ ', views.post_list), )
|
Now we map the URL of R ' ^$ ' to the view views.post_list.
But if you visit the homepage http://127.0.0.1:8000/now, you will get an error.
Why, because your view views.post_list is not implemented now Ah, can't find this method!
Then we will explain the implementation of the view.
What is view?
View is also called views, and in Django it holds the actual business logic. This is not the same as what we usually call the view in MVC.
Django's MTV Model
Here I'll explain a little bit about the Django structure, which we call the MTV mode:
- M represents the model, which is the data access layer. This layer handles all the transactions related to the data: how to access it, how to validate it, what behavior it contains, and the relationship between the data.
- T stands for template, which is the presentation layer. This layer handles performance-related decisions: How to display in a page or other type of document.
- V represents the view, which is the business logic layer. This layer contains the relevant logic for accessing the model and tuning the appropriate template. You can think of it as a bridge between the model and the template.
So the usual meaning of controller controllers where to go, the careful children's shoes should be guessed, that is what we said in the previous section of the urls.py configuration file.
In a nutshell: Urlconf+mtv constitutes Django's overall architecture.
blog/views.py
The initial content of this file is this:
1 2 3
|
Import Render
# Create your views here.
|
Add one of the simplest views:
1 2 3
|
Post_list(Request):
' blog/post_list.html ', {})
|
We define a method, Post_list, whose parameters are request, using the Render function to return an HTML template blog/post_list.html.
Next we visited the Ere page, OMG, and made a mistake:
The error of this report is that the template blog/post_list.html cannot be found. This is obvious because we haven't defined this HTML template at all.
Don't worry, go ahead and look down on the tutorials ...
What is a template?
A template is a reusable file that renders dynamic content using a fixed format. For example, you can use a template to write messages, each message may have different content, sent to different people, but their format is the same.
Django template using HTML files, as for God Horse is HTML, this to reference under the Web or Google, but if the people do not understand HTML, please do not tell others I know you. ^_^
First template
Creating a template is creating an HTML file. Template files are stored under the Blog/templates/blog directory, the first in the blog directory to create the templates directory, and then in the Templates directory to create a blog directory, as for why to do so, do not tube, Django is a lot of directories are agreed, this is the same as MAVEN, the contract is higher than the configuration. So you just do it. The directory structure is as follows:
Blog └───templates └───blog
|
Then create a post_list.html file in the Blog/templates/blog directory, and now there is no content.
This time visit the homepage again, the effect is as follows:
A blank, but no error.
Add something to the post_list.html:
1 2 3 4
|
<html> <P>hi there! </p> <p>it works! </p> </html>
|
Visit Http://192.168.203.95:8000/again:
Dynamic templates
But so far we can only display static pages. How to display the list of articles on the homepage?
We already have the model post, with the template post_list.html, how to make the model data appear in the template, this is the function of the view, in fact, the role of the Django view is to connect the model and template bridge. In the view, the data in the database is retrieved by Queryset and then passed to the template, which is responsible for displaying the template.
First open the blog/views.py, and its current content is this:
1 2 3 4
|
Import Render
Post_list(Request): ' blog/post_list.html ', {})
|
In this time we import the post model
1 2
|
Import Render Import Post
|
Note that we still use relative imports, which is a powerful feature of Python3.
QuerySet
It's time to call out the Queryset, which we've already covered in the model and ORM subsections.
Now we want to retrieve the articles in the database and sort them in reverse by the release date, so that the latest articles are put forward.
1 2 3 4 5 6
|
Import Render Import Post
Post_list(Request): Posts = Post.objects.filter (published_date__isnull=False). order_by ('-published_date ') ' blog/post_list.html ', {' posts ': posts})
|
Note the last parameter in the render function {' posts ': posts}, which is used to pass data to the template.
Template label
HTML pages only recognize HTML tags, so how do you make dynamic content? The answer is to use Django's own template tags, including the syntax of judgment, looping, piping, and so on. Now that we have a list of the articles, we can use the For loop to generate the corresponding HTML page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
<Html> <Head> <Title>django Girls Blog</Title> </Head> <Body> <Div> <H1><Ahref="/" >django Girls Blog</A></H1> </Div> {% for post in posts%} <Div> <p>published: {{post.published_date}}</P> Span class= "line" > <h1><a Span class= "attr" >href= ">{{post.title}}</a> </H1> < p>{{post.text|linebreaks}}</P> </DIV> {% ENDFOR%} </body>, </< Span class= "name" >HTML> |
{% for %}
{% endfor %}
Each post is looped between and, and then a period of time is generated
Now visit the homepage again, the effect is as follows:
Don't forget something.
Don't forget to push it to the top of the pythonanywhere.
git Add. Git commit-m ' dynamic article List home ' Git push Origin Master
|
Congratulations, so far the basic whole process has been through. Open the admin after adding a few articles, remember to fill in the release date, and then refresh the Ere page, to see if it will be displayed.
Well, at this time you can go out and turn left to the kiosk to buy yourself some lollipop reward yourself!
Django Development Blog-Trilogy