Search code examples
pythondjangodjango-modelsdjango-viewsdjango-templates

Is there a good way to access the "model" attribute for a ListView in Django so that it can be used in a template?


thanks in advance for the help. Long story short, I'm attempting to build a CRM-type application in Django (think of it as a Salesforce clone, if you're familiar). I want to be able to access the model attribute that I'm providing to my ExampleListView class. I'm reading through the docs on the ListView class but either can't find how to do it, or I'm just missing the connection.

For context here's some example code (what I've got so far isn't far off of the boilerplate from the docs):

views.py:

class ExampleListView(ListView):
    model = Example

app/templates/app/example_list.html:

{% block content %}
<h2>Examples</h2> <!-- Ideally, I'd love to be able to create this dynamically -->
<table>
    <thead>
      <tr>
         {% for header in ???? %} <!-- Here's what I can't figure out -->
             <th>{{header}}</th>
         {% endfor %}
      </tr>
    </thead>
    <tbody>
        <tr>
           {% for example in object_list %}
               --- Display record data here ---
           {% endfor %}
        </tr>
    </tbody>
</table>
{% endblock %}

I've thought about the idea of trying to add the model attribute to the context dictionary, but I'm unsure how to go about it. Am I on the right track?


Solution

  • Even you can add this in your model, may be this is helpful.

    class ExampleListView(ListView):
        model = Example
        
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['model'] = Example
    

    please revert if it is not helpful I will update the answer accordingly.