Practical drills on efficient Python development-basic view 3
After the establishment of the Django project and application, you can start to write the website application code. Here, a welcome title is displayed for the registration page to demonstrate the Django routing ing function.
1) First, create a routing Response Function in djangosite/app/views. py:
from django.http import HttpResponse def welcome(request): returnHttpResponse("
This Code defines a function, welcome (), which returns a message encapsulated by HttpResponse.
2) then, bind the user's http access to the function through URL ing.
Create a new urls. py file in the djangosite/app/directory to manage all URL mappings in the app. The file content is:
from django.conf.urls import urlfrom . import views urlpatterns = [ url(r'',views.welcome),]
In row 1st, the url () function in django. conf. urls is introduced. All route mappings in Django are generated by this function. The 2nd line of code introduces the djangosite/app/views. py module. Then the key variable urlpatterns is defined, which is a list that stores all route mappings generated by the url () function. In this Code, only one ing is set and all routes are mapped to the welcome function in view. py.
3) add an item in the urlpatterns of the project URL File djangosite/urls. py to declare reference to the urls. py file in the application app. The Code is as follows:
From django. conf. urls import urlfrom django. contrib import adminfrom django. conf. urls import include # urlpatterns = [url (r '^ app/', include ('app. urls '), # Add url (R' ^ admin/', admin. site. urls),]
First, introduce django through the import Statement. conf. urls. include () function, and then add a path 'app/'in the urlpatterns list to transfer it to the app. urls package, that is, djangosite/app/urls. py file. In this way, the two urlpatterns are connected through the include () function.
Note: The 1st parameters of the url () function use regular expressions to express URL routing. In this example, '^ app/' indicates "all routes starting with app ".
Interested readers can look at the structure of this book "efficient Python development practices"