Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Django Basics Model Administration First app view

William Starzyk
William Starzyk
14,577 Points

Stuck on Challenge Task 2 of 2 Django Basics

STUCK ON Challenge Task 2 of 2 (Django Basic)

Now, create a view named article_list that selects all Article instances and returns an HttpResponse like "There are 5 articles." Be sure to use the len() of the Article queryset to get the number of articles.

Any help in what I am doing wrong?

articles/views.py
from django.http import HttpResponse

# Write your views here

from .models import Article

def article_list(request):
  art = Article.objects.all()
  output = 'There are' + len(art) +'articles.'
  return HttpResponse(output)

5 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

William;

Have you tried using string formatting for the output? Like "I have {} apples.".format(len(apples)).

Post back if you are still stuck.

Ken

Andrew Winkler
Andrew Winkler
37,737 Points

This is the easiest method for me to understand. The .join() function gets me all confused in comparison because my mind jumps to SQL, not python's ORM.

def apple_count(apples):
    return "I have {} apples.".format(len(apples))
from .models import Article

def article_list(request):
    return HttpResponse('There are ' + str(len(Article.objects.all())) + ' articles.')
MARCELLO BARROS FILHO
MARCELLO BARROS FILHO
3,842 Points

I think this way the code is more legible:

from .models import Article

def article_list(request):
    articles = Article.objects.all()
    articles_len = str(len(articles))

    return HttpResponse('There are {} articles.'.format(articles_len))
Lewis Cowles
Lewis Cowles
74,902 Points

alternatively wrap len(art) like so str(len(art)). I think Ken's method is better, but I am sure I was super lazy on this challenge and did something similar or used ' '.join(['There are',str(len(art)),'articles.'])