Search code examples
pythondjangodjango-tables2

How are django variable tags used within html templates?


When writing .html files the variable tags "{{" "}}" do not display any information when rendered. example:

//model.py

 class model_name(models.Model):
     name_id = models.CharField(max_length=20, name='Name')
     link_id = models.CharField(max_length=4, name='Link')

//tables.py

class model_name_table(tables.Table):
    column_name = tables.TemplateColumn('<a href="{{model_name.link_id}}">{{model_name.name_id}}text_for_example</a>')

    class Meta:
        model = model_name
        fields = ('column_name', 'Name')

This yields "text_for_example" when rendered but neither {{model_name.link_id}} or {{model_name.name_id}} display anything.

Simplifying to:

class model_name_table(tables.Table):
    column_name = tables.TemplateColumn('{{model_name.name_id}}')

    class Meta:
        model = model_name
        fields = ('column_name', 'Name')

Yields blank data within the column. How are variable tags supposed to be used to render data from models?

django-tables2 reference http://django-tables2.readthedocs.org/en/latest/index.html#templatecolumn

djagno template language reference https://docs.djangoproject.com/en/1.6/ref/templates/api/#django.template.Template


Solution

  • The django-tables2 documentation you link to show exactly where you're going wrong: the context item that contains the current row is called record, not model_name.

    column_name = tables.TemplateColumn('<a href="{{record.link_id}}">{{record.name_id}}text_for_example</a>')