Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialWilliam Starzyk
14,577 PointsStuck 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?
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
Treehouse TeacherWilliam;
Have you tried using string formatting for the output? Like "I have {} apples.".format(len(apples)).
Post back if you are still stuck.
Ken
Dan Castanera
3,098 Pointsfrom .models import Article
def article_list(request):
return HttpResponse('There are ' + str(len(Article.objects.all())) + ' articles.')
MARCELLO BARROS FILHO
3,842 PointsI 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
74,902 Pointsalternatively 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.'])
William Starzyk
14,577 PointsThanks that worked
Andrew Winkler
37,739 PointsAndrew Winkler
37,739 PointsThis 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.