2

I'm new to django and I'm having a little difficulty getting my database data to print onto my page. I'd appreciate help - and I know I'm doing something silly but I've kinda hit the wall.

I have the DB set up and I can access the data in it without any issues:

python manage.py shell

>>> from homepage.models import User, Oncall
>>> user_data = User.objects.all()
>>> names = []
>>> for x in user_data:
...  names.append(x.first_name + ' ' + x.last_name)
>>> names
[u'Arthur Mencke', u'John Doe']

So then in my views.py I have:

from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404, render_to_response
from django.utils import timezone
import datetime
from homepage.models import User, Oncall
from django.template import RequestContext, loader
from django.template import Template, Context
from django.template.defaulttags import register

def index(request):
        now = timezone.now()
        users = User.objects.all()
        return render(request, 'homepage/index.html')

def getUsers(request):
        users = User.objects.all()
        name_list = []
        for x in users:
                name_list.append(x.first_name + ' ' + x.last_name)
        return name_list

And in my index.html file:

{% if name_list %}
        {% for x in name_list %}
                {{ name_list.x }}
        {% endfor %}
{% else %}
        <b>no users</b>
{% endif %}

{{name_list|length}}

This will always show up in the browser with:

no users 0

I've also tried name_list[x] and mucked around with it quite a bit with no luck

Any ideas?

Cheers, Arthur

1
  • You need to pass the context of users or name_list to the template Commented Apr 14, 2015 at 14:22

1 Answer 1

6

You are doing it wrong, you are not passing the context in index view, take this example:

def index(request):
    users = User.objects.all()
    return render(request, 'homepage/index.html', {'users': users}) # notice here we are adding our context to be used in template, you need pass it explicitly

Then in index.html:

{% for user in users %}
    <span>{{ user.first_name }} {{ user.last_name }}</span>
{% endfor %}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Aamir! That did the trick. It seems quite simple in hindsight but the django template language and relationships between files takes a little getting used to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.