Print Django Model as a Table

I have a view definition that (tries) displays the model in a table. This is what I have so far:

def output_table(request):
    output = My_Model()
    return render_to_response('outputtable.html', {'output': output})

Here is the HTML for outputtable.html:

<html>
<table>
    {{ output.as_table }}
</table>
</html>

What am I doing wrong? This does not work. Now it passes the model correctly, because if I change My_Model () to My_Model.objects.all () and then output it as just {{output}}, then it will show me what I will see in the Django shell.

+5
source share
6 answers

So you need to do the following:

1) add

from django.forms import ModelForm to your models.py

2) add

class My_Model_Form(ModelForm):  
           class Meta:  
               model = My_Model 

3) in your views.py, change output = My_Model()tooutput = My_Model_Form()

. , , .

+2

models.Model as_table(), forms.ModelForm.

. .

myapp/templatetags/model_helpers.py

from django import template
register = template.Library()


@register.inclusion_tag('myapp/model_table.html', takes_context=True)
def model_as_table(context, model_key=None, model_table_attrs_key=None):

    if model_key is None:
        model_key = 'object'

    if model_table_attrs_key is None:
        model_table_attrs_key = 'model_table_attrs'

    try:
        attrs = context[model_table_attrs_key]
    except KeyError:
        attrs = context[model_key]._meta.get_all_field_names()

    table_context = {'rows': []}
    for attr in attrs:
        try:
            value = str(getattr(context[model_key], attr))
            if value:
                table_context['rows'].append({'attr': attr,
                                              'value': context[model_key][attr]})
        except AttributeError:
            pass
        # Needs a way to display many_to_many fields.
        except StopIteration:
            pass

    return table_context

myapp/templates/myapp/model_table.html

{% for row in rows %}
    <tr>
        <td class="name">{{ row.attr }}</td>
        <td class="field">{{ row.value }}</td>
    </tr>
{% endfor %}

myapp/templates/myapp/outputtable.html

{% load model_helpers %}

<table>
    {% model_as_table %}
</table>

, .

myapp/views.py

def output_table(request):
    output = My_Model()
    return render_to_response('outputtable.html',
                              {'output': output, 'model_table_attrs': ['attr1', 'attr2']})

html python.

+1

as_table (MyModel()) Querysets (MyModel.objects.all()). , as_table as_table. .

/ , .

0

, -

<tr>
  <td>Name:</td>
  <td>{{ output.name}}</td>
</tr>

, . , , snippet. , .

0

OMG , Generic Views, -, , . .:)

0

, , . templatetags/your_tags_file.py ( __init__.py templatetags):

from django import template
register = template.Library()

@register.filter()
def as_table(model):
    ret = ""
    for name in model._meta.get_all_field_names():
        try:
            field = str(getattr(model, name))
            if field:
                ret += '<tr><td class="name">'+name+'</td><td class="field">'+field+'</td></td>'
        except AttributeError:
            pass
    return ret

:

{% load your_tags_file %}
<table>
    {{output|as_table|safe}}
</table>

This will make the model in a simple table for you. You can easily add any desired logic theadand tbody, as you see fit, changing the logic of creation ret. Hope this helps someone.

0
source

All Articles