Receive our weekly advanced programming tips for FREE
How to use urls pattern and views
| 0 votes
Autor: bookkeeper
Chapter: Django
You created your first django application. Now we need to fill it logic. Every app has files: and They hold the app specific logic.

1. First we change into an app folder.

2. Create a file and edit it.

3. Create our urls logic.

from django.conf.urls.defaults import *
urlpatterns = patterns('',
 (r'^$', 'blog.apps.homepage.views.index'),

Every file must have a variable called "urlpatterns", the django function patterns will create a django url pattern. First argument is a prefix, for now we leave it empty. After are the url patterns, first a regex expression, second the python notation to the view. The view is responsible to render a page.

4. Create a file and edit it.

from django.http import HttpResponse
def index(request):
    return HttpResponse("Index Page")

Import the HttpResponse class. Create a function index, that is your view that will render the index page. First argument is always the request object, which contains the necessary information, like cookies, post and get data etc.

5. Open the global file

from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    (r'^', include('blog.apps.homepage.urls')),
    # Example:
    # (r'^blog/', include('')),
    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    # (r'^admin/', include(,

And add the url pattern which will include the homepage urls and pass with r'^' the path to homepage

6. Start the dev server: python runserver

Your first django view and url pattern!