After I finished reading the First Steps tutorials on Django’s website, I realized that the documentation did not discuss how to set up a home page. Because Django projects are collection of configurations and apps, I decided that the best way to set up a home page was to create an app.
Create a Home Page App
If you followed my previous Django posts (Setting up Django with Apache and mod_wsgi on Ubuntu and Setting up sub-domain to serve static files), you know that I set up Django project under /srv/www/testsite. So I will create home app under this folder.
Open your Terminal App and navigate to your project location.
cd /srv/www/testsite python manage.py startapp home
Django’s Settings File
Now open your settings.py file and add the ‘home’ app to your list of installed apps.
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'home', 'django.contrib.admin', )
Now open your main urls.py file (testsite/urls.py) and add the following to your url configuration.
If you followed the tutorials on Django’s documentation site, your url patterns should look like the following:
urlpatterns = patterns('', url(r'^$', 'home.views.index'), url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), )
We are telling Django that if a user navigates to our home page, Django should look for the index function located in the home view. In order for Django to know that the view exists, add the following at the top of your urls.py file:
from testsite.home import views
Now open views.py file that was created under the home folder. Add the following:
from django.shortcuts import render_to_response from django.template import RequestContext def index(request): return render_to_response('home/index.html', context_instance=RequestContext(request))
RequestContext is used to pass information to your template. In my previous post), I noted that your view must be set up correctly in order for your template to be able to know the STATIC URL setting. If I did not want to pass this information to my template, then I would simply create the function as:
def index(request): return render_to_response('home/index.html')
Now let’s create the index template. Create a folder under your template directory named home. And then create a the index.html file under the home folder.
That’s it. Your Django project now has a home page.Tags: django, Home page app