Homer
Homer

Reputation: 3

Django: An Error of Getting Templates

I am a beginner of Django. Now, I have a problem of getting templates. The context of my webpage contains just messy code...

Here is photo/views.py:

from django.template import loader, Context
from django.http import HttpResponse
from final.photo.models import Image, Audio

def List(request):
    posts = Image.objects.all()
    t = loader.get_template("list.html")
    return HttpResponse(t, { 'posts': posts })

Here is photo/urls.py:

from django.conf.urls.defaults import *
from final.photo.views import List

urlpatterns = patterns('',
    url(r'^$', List),
)

Here is list.html: (some of the code cannot be seen on the webpage)

<pre>

<title>So Easy! - Scene List</title>

<h1>So Easy! Learn Chinese</h1>

{% block content %}
{% endblock %}

I hope someone can help me solve it! Thanks!

Upvotes: 0

Views: 82

Answers (2)

Robson Fran&#231;a
Robson Fran&#231;a

Reputation: 661

First of all: which version of django are you using? Django 1.3 added View Classes, which make things a lot easier.

Considering you're still on Django 1.2:

  1. You must set the template folder at settings.py:

    TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. "/absolute/path/to/your/template/folder", )

  2. Also you need to add a code snippet inside list.html:

    {% block content %}

    {% for item in posts %} {% endfor %} {% endblock %}

  3. It's advised to create a base.html for your templates. After you do this, add {% extends "base.html" %} as the first line of your list.html

  4. The return line of your view function should be: return render_to_response('list.html', { 'posts' : posts })

Upvotes: 0

BluesRockAddict
BluesRockAddict

Reputation: 15683

Try changing your view to the following:

def List(request):
    posts = Image.objects.all()

    context = RequestContext(request, {
         'posts': posts,
    })

    return render_to_response('list.html', context)

Also, check that your settings.py has the following:

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

Finally, you'll also need to change your list.html template to make use of posts variable you're passing by using {{ posts.some_image_attribute }} in your template.

Upvotes: 1

Related Questions