Python Django Tutorial: Views and URL Handling - Part Three

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 django project with django app.

  2. Now run django project using open command prompt in 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 django app folder.

  5. Write code in views.py as below

    from django.http import HttpResponse,

    # Create your views here.

    def firstView(request):
    data = "<html><body>Hello is new view of django<body></html>"
    return HttpResponse(data)

  6. Now open urls.py in django project root folder.

  7. Write code as below.

    from django.conf.urls import url

    urlpatterns = [
    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 browser.

  10. HttpResponce is used for returning to page. When you want see results in any page use any function that must return the type of response.

  11. In URLS.py file code define some part like: urlpattern is use for write URL handling in this array. This is use for store web page URL.

  12. URL method contains first parameter that defines web page URL which works as regular expression.

  13. Second parameter ‘main.views.firstView’ is use for locating fisrtView method that we will use when this url hits on browser and last parameter is used for giving unique name for identifying particular url and you can use this in view file.

  14. Now I will show another example of handling url and views.

  15. Now make another method in views.py as below.

    from django.conf.urls import url

    urlpatterns = [
    url(r'^$', 'main.views.firstView', name='home'),
    url(r'^name/$', 'main.views.askName', name='name').
    ]


  16. Write code in urls.py as below,

    from django.conf.urls import url

    urlpatterns = [
    url(r'^$', 'main.views.firstView', name='home'),
    url(r'^name/$', 'main.views.askName', name='name'),
    ]

  17. Now open browser and go to URL http://127.0.0.1:8000/name/

  18. You will see output as below image:

    application
    Django framework provides many features for handling url and view as dynamic.

    Django most important feature is that django also has tag for using in html page as angularJs.But its tag only runs only once when page is loading.