django URL

 URL To configure (URLconf) It's like Django Directory of supported sites . The essence of it is URL The pattern as well should be URL Map tables between view functions invoked by the schema ; That's how you tell it Django, For this URL transfer

Use this code , For the URL Call that code .

stay url.py There is only one tuple in , Need to add URL Just unload the tuple .

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cur_time',views.current_time),
url(r'^user_info',views.user_info),
url(r'^article/(?P<year>[0-9]{4})/(?P<month>[0-9] {2})/$',views.yeartest),
url(r'^login$',views.login,name="denglu"),
url(r'^home$',views.home)
]

Parameter description :

  • A regular expression string
  • A callable object , Usually a view function or a string specifying the path of the view function
  • Optional default arguments to pass to the view function ( The dictionary form )
  • An optional one name Parameters

It should be noted that :utl Maps are sequential and match only once

url(r'^article/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',views.yeartest)

1 among ?P It's a keyword grouped and named in regular , There are brackets on the outside , So it will be sent to yeartest This function has two arguments .

2 url(r'^user_info',views.user_info,{"name":"alex"}), Equivalent to the default parameter

3 url(r'^user_info',views.user_info,name="alex") url Another name for form Medium action Use template language instead of by {% url alex %}, The purpose of this is to prevent changes in the back end from affecting the front end .

4 Use include: It's very detailed in the English explanation of the document :

1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))

And then in your own app Create a urls Of py file . It's consistent, but ,url There's more blog The first one will be sorted to another file to match .

Django Views

Look at the knowledge points through examples :

def login(request):
if request.method=="POST":
username = request.POST.get("username")
pwd = request.POST.get("pwd")
if username == "ccc"and pwd == "":
return redirect("/home") # Return to one home page perform home Functional
return render(request,"login.html") #

Knowledge points involved :

  • render and Httpresponse want import To come over .
  • render Inside is also through Httpresponse Send and render well HTML To the browser .
  • request yes django Automatically transmitted parameters must be received , It can be custom .
  • .menthod It's in the form of form sending . Capitalization post.
  • post It's a dictionary , Traversable . Use get Better way .
  • redirect It's back to this URL( useless render), Not return to this function or HTML. If you go back to the function home Or directly homeHTML It can lead to home Some of the data is not loaded . And the page also       Is to stay login page , After refreshing, I have to log in again .
  • render The first parameter after must be request, The second is HTML, After that are the parameters . Sometimes for having local.() It means to make all local variables into dictionaries and send them to HTML. When it comes to template languages .

request Other attributes in :

# path: The full path of the request page , Excluding domain names 
#
# method: Used in the request HTTP String representation of method . All capitals mean . for example
#
# if req.method=="GET":
#
# do_something()
#
# elseif req.method=="POST":
#
# do_something_else()
#
# GET: Contains all the HTTP GET Class dictionary object for parameter
#
# POST: Contains all the HTTP POST Class dictionary object for parameter
#
# The server received an empty POST It's also possible to ask for , in other words , Forms form adopt
# HTTP POST Method submit request , But there may not be data in the form , So it can't be used
# if req.POST To determine whether or not HTTP POST Method ; You should use if req.method=="POST"
#
#
#
# COOKIES: Contains all the cookies Standards for Python A dictionary object ;keys and values All strings .
#
# FILES: Class dictionary object containing all uploaded files ;FILES Each of them Key All are <input type="file" name="" /> In the label name The value of the property ,FILES Each of them value It's also a standard python A dictionary object , Including the following three Keys:
#
# filename: Upload file name , Represented by string
# content_type: Of uploaded files Content Type
# content: Upload the original content of the file
#
#
# user: It's a django.contrib.auth.models.User object , Represents the currently logged in user . If the access user is currently
# No landing ,user Will be initialized to django.contrib.auth.models.AnonymousUser Example . you
# Can pass user Of is_authenticated() Method to identify whether users log in or not :
# if req.user.is_authenticated(); Only activation Django Medium AuthenticationMiddleware
# This property is only available when
#
# session: Unique read-write properties , Dictionary object representing the current session ; I have activation Django Medium session Only available when supported . # Method
get_full_path(), such as :http://127.0.0.1:8000/index33/?name=123 ,req.get_full_path() The result is /index33/?name=123
req.path:/index33

Template Basics

Although in the view, you can directly returnHTML Code , But out of efficiency , beautiful , Division of labor , And maintenance and so on. Generally speaking, it's well written HTML Page to HTML The suffix is saved in template in . It's called a template .

The composition of the template

HTML Code and logic control code .

Template language

The front-end web page should produce different pages according to different information of each user , So despite the fact that js To make a page move, you need to transfer data from the back end to the web page .

{{ name }}

>>> python manange.py shell
>>> from django.template import Context, Template
>>> t = Template('My name is {{ name }}.')
>>> c = Context({'name': 'Stephane'})
>>> t.render(c)
'My name is Stephane.'

The above code is in manage shell The rendering process executed in the command . This process moves to HTML The exchange of page data is realized in . This is also in the last section render The reason for passing in the last parameter .

Everything (.)

If you want to send it in a dictionary , Then you can retrieve the dictionary by clicking .

>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': ''}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
'Sally is 43 years old.'

Empathy , list , Tuples , Object properties , Methods and so on can be found through the point .

Filter of variables filter and tag

  {{obj|filter:param}}

Other methods :

 # 1 add : Add the corresponding value to the variable 
#
# 2 addslashes : Slash the quotes in the variable
#
# 3 capfirst : title case
#
# 4 cut : Removes the specified character from the string
#
# 5 date : Format date string
#
# 6 default : If the value is False, Replace with the default value set , Otherwise you're just using the original value
#
# 7 default_if_none: If the value is None, Replace with the default value set , Otherwise, use the original value

  {% tags %}

tag It means label , And filter It's different. It's a percent sign in the middle . And the middle is usually a special statement .

if sentence

 {% if num >= 100 and 8 %}
{% if num > 200 %}
<p>num Greater than 200</p>
{% else %}
<p>num Greater than 100 Less than 200</p>
{% endif %} {% elif num < 100%}
<p>num Less than 100</p> {% else %}
<p>num be equal to 100</p> {% endif %} {% if %} Label acceptance and,or perhaps not To test multiple variable values or to negate a given variable
{% if %} Tags are not allowed to appear in the same tag at the same time and and or, Otherwise logic is prone to ambiguity , For example, the label below is illegal : {% if obj1 and obj2 or obj3 %}

if

for sentence

 {% if num >= 100 and 8 %}
{% if num > 200 %}
<p>num Greater than 200</p>
{% else %}
<p>num Greater than 100 Less than 200</p>
{% endif %} {% elif num < 100%}
<p>num Less than 100</p> {% else %}
<p>num be equal to 100</p> {% endif %} {% if %} Label acceptance and,or perhaps not To test multiple variable values or to negate a given variable
{% if %} Tags are not allowed to appear in the same tag at the same time and and or, Otherwise logic is prone to ambiguity , For example, the label below is illegal : {% if obj1 and obj2 or obj3 %}

for

{%csrf_token%}:csrf_token label

This label will be written on input Back , namely form At the end of the form . The function is to prevent cross site attack verification , A complex string will be randomly generated and sent along with the data of the form .

In the use of render_to_response It doesn't work when it's time .

{% url %}

<form action="{% url "bieming"%}" >
<input type="text">
<input type="submit"value=" Submit ">
{%csrf_token%}
</form>

stay URL The parameter says , It's cooperation name With .

{% with %}: Replace complex variable names with simpler ones

1
{% with total=fhjsaldfhjsdfhlasdfhljsdal %} {{ total }} {% endwith %}

{% verbatim %}: prohibit render

1
2
3
{% verbatim %}
          {{ hello }}
{% endverbatim %}

Self defined filter and tag( Need to restart )

1. stay app Created in templatetags Templates , Name cannot be changed .

2. Create your own tag Of py file . The contents of the document :

 from django import template
from django.utils.safestring import mark_safe register = template.Library() #register The name is fixed , It can't be changed @register.filter
def filter_multi(v1,v2):
return v1 * v2 @register.simple_tag
def simple_tag_multi(v1,v2):
return v1 * v2 @register.simple_tag
def my_input(id,arg):
result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
return mark_safe(result)

3. Before use HTML Introduce... At the beginning of the file :{% load my_tags %}

4. Like other filter and tag Just call . It should be noted that filter Yes, the filter can only have two parameters . The usage is in filter Follow closely behind : And variables

extend Inherit

In the actual operation of the whole project, there will be the same modules such as the title , You can't let the programmer write the page again every time the user clicks on it . What's used here is extend Inheritance Tags .

To put it bluntly , When the contents of multiple pages are roughly the same , Write the same part into a base.html The clock , When other pages use this part, just inherit it and use it .

So the following statement appears in some files :

 {% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

extend Indicates that other content inherits from base, But in base Medium block title Replace the information in with this block in , Empathy content.

django-- More related articles in the main part

  1. Asynchronous task queue Celery stay Django The use of

    Some time ago Django Web Platform development , Some requests take a long time to execute ( A few minutes ), To speed up user response time , So we decided to execute these tasks asynchronously in the background . Under the guidance of colleagues, I contacted Celery This asynchronous task force ...

  2. 《Django By Example》 Chapter four chinese translate ( Personal learning , Dregs turning )

    Books come from :https://www.packtpub.com/web-development/django-example The original author :Antonio Melé ( translator's note : Happy new year to you all , This time it brings <D ...

  3. django server Through between remote user Mutual invocation

    First , The scene is like this : There are two django web application , And there is a certain connection between the two applications . In some cases, they need to get each other's data . But our applications will have corresponding authentication mechanisms . You won't let people visit you casually, will you . It's like getting on the bus ...

  4. Mysql Business exploration and its application in Django Practice in ( Two )

    Following last article <Mysql Business exploration and its application in Django Practice in ( One )> Explain the background and Mysql After the transaction basis , This article mainly wants to introduce the transaction in Django And the efficiency improvement brought to us by the use of and practical application . First ...

  5. Mysql Business exploration and its application in Django Practice in ( One )

    Preface I've been thinking about blogging for a long time , On the one hand, it is a summary of my recent knowledge . precipitation , It is convenient to sort out the past knowledge in the future . trace , On the one hand, I also hope to know more friends in the same technology circle through blog . Fortunately, the blog Park recently passed the application , So today, ...

  6. 《Django By Example》 The third chapter chinese translate ( Personal learning , Dregs turning )

    Books come from :https://www.packtpub.com/web-development/django-example The original author :Antonio Melé ( translator's note : Chapter three scalding out of the oven , Please do not make complaints about the text ...

  7. 《Django By Example》 Chapter two chinese translate ( Personal learning , Dregs turning )

    Books come from :https://www.packtpub.com/web-development/django-example The original author :Antonio Melé ( translator's note : After translating the first chapter , Find the speed of translating chapter two ...

  8. 《Django By Example》 Chapter one chinese translate ( Personal learning , Dregs turning )

    Books come from :https://www.packtpub.com/web-development/django-example The original author :Antonio Melé ( translator's note : I am currently working in an Internet company in Hangzhou , ...

  9. Django

    One .Django brief introduction Django It's a by Python Written in open source Web Application framework . It was originally developed to manage news content based websites owned by Lawrence publishing group , That is CMS( Content management system ) ...

  10. Django admin Customized ,User Field extension [ original ]

    Preface Refer to the last post , We used OneToOneField The way to use django Self contained user,http://www.cnblogs.com/caseast/p/5909248.html , But it works like this ...

Random recommendation

  1. ActiveMQ 5 introduction

    apache-activemq-5.13.2 ActiveMQ Use JAAS How authorization is configured <plugins> <!– Use login.config Configure authorized users --> < ...

  2. spark Automatic partition inference of data source

    stay hadoop Create directory on /spark-study/users/gender=male/country=US/users.parquet( And put the file put Up ) code: package cn.spa ...

  3. Serialize magic functions __sleep() And deserializing magic functions __wakeup()

    1.string serialize ( mixed $value )— Produce a representation of a storable value serialize() Return string , This string contains the representation value The byte stream of , It can be stored anywhere . ...

  4. codeforces 277.5 div2 F: Combined count class dp

    The main idea of the topic : Ask for one n*n Of (0,1) matrix , There are only two in each row and column 1 Number of alternatives And the front of the matrix m The line is known analysis : This question is similar to that of Mudanjiang regional competition D The questions are similar , It's all about the coverage of the rows and columns of a matrix Mudanjiang D It's about probability , The question is ...

  5. POJ 1330 Nearest Common Ancestors(Tarjan offline LCA)

    Description A rooted tree is a well-known data structure in computer science and engineering. An exa ...

  6. Spring Source code analysis :Spring IOC Container initialization

    summary : Spring about Java development , And a very basic and core framework , After having some development experience , Reading the source code can better improve our coding ability and make us understand it better . As the saying goes, know yourself and know your enemy , you can fight a hundred battles with no danger of defeat . When you are right Spri ...

  7. GWAS Literature reading :The stability of educational achievement across school years is largely explained by genetic factors

    Method from NPD( UK database , Collect data on students' academic performance in the academic year ) and TEDS( National curriculum guide report score database , Standardized core academic courses are developed by the national education research foundation and the qualifications and curriculum administration ) The database gets the twins' academic performance data ...

  8. The simplest C#UDP Examples of Communications

    Reference resources :https://www.cnblogs.com/zxyc2000/articles/2846662.html and https://www.cnblogs.com/mq0036/p/7302605 ...

  9. I'm right Java A little bit of my opinion

    As a more theoretical student , Let's talk about this period of time java And the understanding of programming java There are several characteristics relative to other languages , One is object-oriented , One is the strong type            Let's start with object-oriented , About classes and objects , This must be ...

  10. Ubuntu 18.04 install Virtual Box or VMWare workstation Pro 14

    Linux Relevant knowledge :https://www.cnblogs.com/dunitian/p/4822808.html#linux Virtual Box:sudo apt-get install vi ...