Reputation: 458
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
Upvotes: 2
Views: 4513
Reputation: 39689
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 %}
Upvotes: 6