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

1. First we change into an app folder.

2. Create a file urls.py and edit it.

3. Create our urls logic.

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

Every urls.py 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 views.py 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 urls.py 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('blog.foo.urls')),
    # 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(admin.site.urls)),
)

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

6. Start the dev server: python manage.py runserver


Your first django view and url pattern!