Hello. I'm new to both django and python.
This in an example code i made up to illustrate my problem:
# Models
class Book(models.Model):
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='book_subby')
submitted_date = models.DateField(auto_now=True)
book_title = models.CharField(max_length=200)
book_publisher = models.ForeignKey(Publishers)
class Publishers(models.Model):
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='publisher_subby')
submitted_date = models.DateField(auto_now=True)
book_publisher = models.CharField(max_length=200)
# View
def book_list(request):
books = Book.objects.filter(submitted_by=request.user, submitted_date__lte=timezone.now()).order_by('submitted_date')
books_by_publisher =
return render(request, 'book/list_books.html', {
'books': books
})
# Template list_books.html
{% for book in books %}
<ul> {{ book.book_publisher }}
<li> {{book.book_title }} </li>
{% endfor %}
This displays:
Publisher X
* Book A
Publisher Y
* Book B
Publisher X
* Book C
Publisher Y
* Book D
I want to display:
Publisher X
* Book A
* Book C
Publisher Y
* Book B
* Book D
I tried doing multiple for loops in the template, but couldn't make it work.
I would appreciate it alot if someone could nudge me in the right direction on how to solve this.
Thanks, Andrea