Wednesday 1 January 2014

Django – 2 Basic View and URL configuration

Django – 2 Basic View and URL configuration.

this blog just gives a very small and simple hello world style webpage over Django framework.
 

Define a function called hello

And save it to the testproject folder as helloworld.py

from django.http import HttpResponse

def hello(request):
return HttpResponse("Hello world")

this is the business logic of your webpage output.

Change the urls.py and let it call hello function.


    from django.conf.urls import patterns, include, url

    # Uncomment the next two lines to enable the admin:
    # from django.contrib import admin
    # admin.autodiscover()

    from testproject.helloworld import hello

    urlpatterns = patterns('',
        url(r'^hello/$','testproject.helloworld.hello',name='hello'),
    )
         
The most import line is url(r'^hello/$','testproject.helloworld.hello',name='hello'),




  • r'^hello/$' is the regular expression when you try to access the page via the browser
  • 'testproject.helloworld.hello’ is the [project].[module].[function]
  • name='hello' is just to give a name to the view.


The urls.py plays a very import role in Django framework, it mapps the url to the python scripts that provides the logic.

So when you run the server by python manage.py runserver 0.0.0.0:8080
And access the page by http://192.168.56.112:8080/hello/

You will get the page look like


    

No comments:

Post a Comment