N
N
Nick V2016-02-10 01:09:27
Django
Nick V, 2016-02-10 01:09:27

How to pass variables through a Django filter?

Good day to all. Tell me something like this. There is a template in which variables are displayed in a loop. How to apply the default:'None' filter to each variable at a time.

models.py

class Faculty(models.Model):
    name = models.CharField(max_length=50, unique=True, null=True)
    slug = models.SlugField(max_length=50, primary_key=True, unique=True)
    dean_name = models.CharField(max_length=50, null=True, blank=True)
    address = models.CharField(max_length=150, null=True, blank=True)
    phone = models.CharField(max_length=50, null=True, blank=True)
    email = models.EmailField(max_length=50, null=True, blank=True)
    department_count = models.SmallIntegerField(null=True, default=0)
    group_count = models.SmallIntegerField(null=True, default=0)
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    modified_at = models.DateTimeField(auto_now_add=False, auto_now=True)

    def get_absolute_url(self):
        return reverse('webnav:facultet', args=[self.slug])

    def __str__(self):
        return self.name


views.py

class Faculties(generic.ListView):
    model = FacultyModel
    context_object_name = 'faculties'
    template_name = 'faculties.html'


template.html

{% for var in vars %}
<ul class="list-group m-l-1">
  <li class="list-group-item infoList">
  Имя: <span>{{ var.name|default:'Отсутствует' }}</span>
  </li>
  <li class="list-group-item infoList">
  Адрес: <span>{{ var.addr|default:'Отсутствует'  }}
  </li>
  <li class="list-group-item infoList">
  Телефоны: <span>{{ var.tel|default:'Отсутствует'  }}
  </li>
  <li class="list-group-item infoList">
  e-mail: <span>{{ var.mail|default:'Отсутствует'  }}
  </li>
</ul>
{% endfor %}


code as you want

{% for var in vars %}
<ul class="list-group m-l-1">
{% filter default:'None' %}
  <li class="list-group-item infoList">
    Имя: <span>{{ var.name }}</span>
  </li>
  <li class="list-group-item infoList">
  Адрес: <span>{{ var.addr  }}
  </li>
  <li class="list-group-item infoList">
  Телефоны: <span>{{ var.tel  }}
  </li>
  <li class="list-group-item infoList">
  e-mail: <span>{{ var.mail }}
  </li>
{% endfilter %}
</ul>
{% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Shatalov, 2016-02-11
@netpastor

Write a custom output tag

@register.simple_tag
def default_var(var):
    return var if var else u'Отсутствует'

In the view code, I would not sew it up.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question