Reputation: 123
The error i am getting is "'help' object is not iterable". How do i fetch the latest record from the db and get it displayed on my destination html page
My views.py is
def about_experiment(request,ex_link_name):
researcher = None
study = None
posts = None
if request.method == 'POST':
form = AboutHelp(request.POST)
posts = help.objects.filter().order_by('-date')[0]
#print(posts)
if form.is_valid():
obj = form.save(commit = False)
obj.save()
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'posts': posts})
my destination page about_experiment.html is
{% for help in posts %}
<h4><b>{{ help.study }}</b></h4>
<p>posted by {{ help.researcher }} on {{help.date}}</p>
{% endfor %}
Upvotes: 0
Views: 1548
Reputation: 28
To add to voodoo-burger's answer:
posts = help.objects.filter().order_by('_date')
Returns a queryset, which is an iterable. But then you add [0]
, so you only get one object from the queryset, and hence it will not be iterable.
In your template you therefore you can just use {{ posts.field_name }}
.
Because you only return one object, post
is a more logical and descriptive name then posts
(as mentioned by voodoo-burger)
Upvotes: 0
Reputation: 2153
{{ posts }}
in your template is a single object instance of your help
class, which is not an iterable so you can't use it in a for loop. Instead just use {{ posts.fieldname }}
.
Also consider changing posts
to a more logical name. You could use post
or even help
.
Upvotes: 0
Reputation: 197
How did you define the help model? If it is class Help
, you should change this:
posts = help.objects.filter().order_by('-date')[0]
To this:
posts = Help.objects.filter().order_by('-date')[0]
Upvotes: 1