Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing model data in Django template

I am using the below lines to pass data to my template index.html, model1 being the class in my models.py.

     data = model1.objects.all()
     return TemplateResponse(request, 'index.html', {'data': data})

I am able to access data on the front end by using a for loop as shown below

 {% for x in data %}
   <h3>{{x.name}}</h3>
   <h4>{{x.department}}</h4>
 {% endfor %}

Since there are mutliple objects in this data, my question is if I want to access only the department of particular object with certain name, how can I do that?

For example here I am using a for loop, consider there are two objects in the data. Then the output would be

name1
department1
name2
department2

So now if I need to access only name2 without any loop, how can i do that?

Updating the question: I am updating this question with html, so that the question looks clear.

table id="example" class="table table-striped" cellspacing="1" width="100%">
    <thead>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Department</th>
    <th>View/Edit</th>
  </tr>
</thead>
<tbody>
  {% for x in data %}
  <tr>
    <td>{{x.id}}</td>
    <td>{{x.name}}</td>
    <td>{{x.department}}</td>
    <td>View</td>
  <button type="button" class="btn-sm btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  view</button></td>
  </tr>
  {% endfor %}

</tbody>

This is how my html looks, I am using data-table here. So all the data is captured in a table automatically. As you can see every row has a view button that I would implement. Once the user clicks the view button, I should pop up a modal dialog to show all the other details like {{x.dateJoined}} etc which I don't show in the table. But if I use a separate view to pop this dialog, I should send a request to the view from my template saying which row(with some ID) the user has clicked. How can i achieve that? How can I bind the view button with respective rows here?

like image 586
kohl Avatar asked Dec 07 '25 13:12

kohl


1 Answers

You need to write custom template tag which will take the queryset and filtering parameters and returns you appropriate object, you can use simple_tag:

myapp/templatetags/myapp_tags.py

from django import template

register = template.Library()


@register.simple_tag
def get_model1_object(queryset, **filters):
    if not filters:
        raise template.TemplateSyntaxError('`get_model1_object` tag requires filters.')
    retrun queryset.filter(**filters).first()

Then in template:

{% load get_model1_object from myapp_tags %}

{% get_model1_object data name='blah' as obj %}

Note: Your filtering criteria might yield multiple results but in get_model1_object i am only returning the first object assuming your criteria will be strict, change it according to your needs.

like image 155
Aamir Rind Avatar answered Dec 09 '25 03:12

Aamir Rind