Thursday, January 24, 2013

404 on your Home Index.html?

Since I setup django I have had a 404 error on the index page.  Not good.  I did attempt to fix it one evening and didn't have any luck.  At that point I decided I would finish the tutorial and then try to fix it.  Well, I have finished the tutorial and now have a better understanding of some of the basics.  I was able to get my index.html back up and working in rather quickly.

Here are the steps I took:

Navigated to myTemplates and created a directory within it named main.  I copied over the index.html page into the new main directory (home/rsnyder/mytemplates/main/index.html)

I created a views.py (~/first_django/myfirst/myfirst) in the same directory as the base urls.py (the first urls.py looked at).  That file contained:


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template import Context, loader
#quick fix to get index back up and going
def index(request):
    template = loader.get_template('main/index.html')
    #context isn't used but it appears I need to pass something
    context = Context({'name': ['Ronald', 'D', 'Snyder']})
    return HttpResponse(template.render(context))

In the same directory there were two changes that were need in the urls.py.  You need add this the imports:


import views


And this as the first search in urlpatterns:

url(r'^$', views.index, name='index'),

That was it.  I bet that there is a better and more conventional way to do this.  This was the way I came up with having only a week of Django experience and my plan is to make the main page more dynamic and interesting soon.




No comments:

Post a Comment