2012年10月16日 星期二

GAE - Use Django Framework - from scratch 2

Continue GAE - Using Django Framework - from scratch 1

Use View to say 'Hello World!'

  1. Modify urls.py, add a line to urlpatterns, like below:
    urlpatterns = patterns('',
        url(r'^$', 'views.sayhello')
    )
  2. Add a new python module views.py under project root, and with following content :
    from django.http import HttpResponse
    def sayhello(request):
        return HttpResponse("Hello world !")

Add Hello App of Django and handle by template

  1. Under project root, gdjtest, run : manage.py startapp hello
  2. Modify urls.py, add a line to urlpatterns, like below:
    urlpatterns = patterns('',
        url(r'^$', 'views.sayhello')
        url(r'^hello/(?P[a-zA-Z0-9_.-]+)/$', 'hello.views.sayhello')
    )
  3. New a folder under project root, named 'templates', for template files storage, and modify setting.py for template storage setting as below:
    TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates') )
  4. New a html template file under folder templates, named hello.html and add line inside html >body< block : 
    Hello {{name}}!
  5. New a python module, views.py, under the new app, hello, folder, and add code as below:
    from django.shortcuts import render_to_response
        def sayhello(request, name):
        return render_to_response('hello.html', {'name':name})
  6. Test : use browser to access 'http://localhost:8080/hello/sunnylin/', and you will get response :
    Hello sunnylin!

Reference :

沒有留言: