Reputation: 3
I'm new to Django so I'm just building a few simple apps to increase my knowledge. I am trying to display a concatenated list, however when I display the list it shows the model names like so:
[<FamousQuote: Be yourself; everyone else is already taken>][<InfamousQuote: . I dunno. Either way. >]
This is my views.py file:
def index(request):
famous_quote = FamousQuote.objects.all().order_by('?')[:1]
infamous_quote = InfamousQuote.objects.all().order_by('?')[:1]
compiled = [famous_quote, infamous_quote]
return render(request, 'funnyquotes/index.html', {'compiled': compiled})
and my index.html file:
{% if compiled %}
{{ compiled|join:"" }}
{% else %}
<p>No quotes for you.</p>
{% endif %}
Is there something I'm doing wrong, or a better way I could do this?
Upvotes: 0
Views: 34
Reputation: 118458
You have a list of lists, so the unicode representation of the list contains the <ObjectName:string>
, where if you had a list of model objects, you'd get a proper __unicode__
representation of your objects.
Ultimately, the template is automatically trying to convert python objects into its string representations, which in the case of the QuerySet
is [<object: instance.__unicode__()>]
.
You have clearly already defined your desired string representation for object instances - you just need to make sure the template engine receives those instances - not other classes.
Look at the difference in output in a shell.
print(FamousQuote.objects.all().order_by('?')[:1]) # calls str(QuerySet)
# vs
print(FamousQuote.objects.order_by('?')[0]) # calls str(FamousQuote)
Either update your view
compiled = [famous_quote[0], infamous_quote[0]]
Or your template
{% for quotes in compiled %}{{ quotes|join:"" }}{% endfor %}
You have lists of lists so you are joining the string representation of the lists, not the instances.
Upvotes: 1