Python Django Tutorial: Views and URL Handling - Part Three

Introduction

 
Today, I will take a new part of Python Django from my tutorial series. In this part, you will learn the Database model features.
 
I already told you the following:
  1. Firstly create a Django project with the Django app.
     
  2. Now run the Django project using open command prompt in the root directory and write command: python manage.py runserver.
     
    cmd
     
    application
     
  3. You have successfully run your Django project.
     
  4. Now open views.py file in the Django app folder.
     
  5. Write code in views.py as below
    1. from django.http import HttpResponse,  
    2. # Create your views here.  
    3. def firstView(request):   
    4.     data = "<html><body>Hello is new view of django<body></html>"  
    5.     return HttpResponse(data)
  6. Now open urls.py in Django project root folder.
     
  7. Write code as below.
    1. from django.conf.urls import url  
    2. urlpatterns = [  
    3. url(r'^$''main.views.firstView', name='home'),  

  8. After this refresh browser then you will see as below:
     
    browser
     
  9. According to views, file code defines the method that has data variable content and some string that will convert by the browser.
     
  10. HttpResponce is used for returning to the page. When you want to see results on any page using any function that must return the type of response.
     
  11. In URLS.py file code define some part like urlpattern is used to write URL handling in this array. This is used for the store web page URL.
     
  12. URL method contains the first parameter that defines a web page URL which works as a regular expression.
     
  13. The second parameter ‘main.views.firstView’ is used for locating firstView method that we will use when this URL hits on the browser and the last parameter is used for giving a unique name for identifying a particular URL and you can use this in the view file.
     
  14. Now I will show another example of handling URLs and views.
     
  15. Now make another method in views.py as below.
    1. from django.conf.urls import url  
    2. urlpatterns = [  
    3. url(r'^$''main.views.firstView', name='home'),  
    4. url(r'^name/$''main.views.askName', name='name').  

  16. Write code in urls.py as below,
    1. from django.conf.urls import url  
    2. urlpatterns = [  
    3. url(r'^$''main.views.firstView', name='home'),  
    4. url(r'^name/$''main.views.askName', name='name'),  

  17. Now open the browser and go to URL http://127.0.0.1:8000/name/
     
  18. You will see the output as below image:
     
    application
     
    Django framework provides many features for handling URLs and views as dynamic.
     
    Django's most important feature is that Django also has a tag for using in the HTML page as angularJs.But its tag only runs only once when the page is loading.


Recommended Free Ebook
Similar Articles