'#DJANGO - I need to display two (or more) rows of a table in my view, currently I can only display one of the rows
Hello people I am working with ticket creation and there is a 1-N relationship, (a ticket can have multiple messages)
I have a view that creates a ticket, in the creation process a message is added - All right here
I have a view that adds a new message to the ticket(s), thus 'activating' the 1-N - All right here
I have a ticket detail view view (code below) - Here starts my difficulty
def ticket_by_id(request, ticket_id, message_id):
mesTicket = MessageTicket.objects.get(pk=message_id)
ticket = Ticket.objects.get(pk=ticket_id)
return render(request, 'support/ticket_by_id.html', {'ticket': ticket, 'messageticket': mesTicket})
the code view above works when the ticket has only one message, but how can I display the multiple messages in this view?
For example in the image below there is my database, highlighting two lines that are linked to ticket 9
database, highlighted in ticket messages 9
Below is an image of my ticket detail view
How should I display in the view the two messages (or 3, or 4, anyway... more than one) that are related to the ticket, as I would show in my view (image 2) lines 9 and 12 (currently it is only displaying the first registered line linked to the ticket, in this case line 9 of the table) of the my table which are the ones that make up the 1-N with the ticket 9 (image 1)
my html page:
{% extends 'web/base.html' %}
{% block title %} Ticket #{{ticket.id}} {% endblock %}
{% block content %}
<div class="ticket">
<table class="styled-table">
<h2> Ticket #{{ticket.id}}</h2>
<style>
td {
padding: 15px;
}
</style>
<br>
<tbody>
<tr>
<td>ID: </td>
<td>{{ticket.id}}</td>
</tr>
<tr>
<td>Author: </td>
<td>{{messageticket.author_id}}</td>
</tr>
<tr >
<td>Status: </td>
<td>{{ticket.status}}</td>
</tr>
<tr>
<td>Content: </td>
<td>{{messageticket.content}}</td>
</tr>
<tr>
<td>Created At: </td>
<td>{{ticket.created_at}}</td>
</tr>
</tbody>
</table>
</div>
{% endblock %}
Solution 1:[1]
First of all, why does your message is not fetch with the id of your ticket, this would ease your work
Second to print multiple "messageticket" you should use something like:
{% for t in messageticket %}
<tr>
<td>Content: </td>
<td>{{ t.content }}</td>
</tr>
{% endfor %}
A loop is needed. As i don't know how messageTicket is done i can't really help you.
But if messageticket have a foreign_key to Ticket then you should be able to to acces it through ticket with ticket.messageticket_set (messageticket_set can be modified if "related_name=" is used in your foreign_key field) https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
and there you'll have all your messageticket
Hope it help =)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cyril Gainon |
