How to get the latest data from the database in django

advertisements

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 %}


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)