Login

Snippets by jmrbcu

Snippet List

Create new variables in templates

Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that. Syntax:: {% assign [name] [value] %} This will create a context variable named [name] with a value of [value] [name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered. Example:: {% assign count 0 %} {% assign str "an string" %} {% assign number 10 %} {% assign list entry.get_related %} {% assign other_str "another"|capfirst %} {% ifequal count 0 %} ... {% endifequal %} {% ifequal str "an string" %} ... {% endifequal %} {% if list %} {% for item in list %} ... {% endfor %} {% endif %}

  • template
  • variable
  • assign
Read More

DRY with common model fields (another way)

Some time you want to add some common fields to a group of models, for example, in a **Generalization/Specialization** relationship. One could have a base model as the generalization class and specialized models with a foreign key to that base model with an unique attribute but I don't like it that way so, I just do this code to add some commons attributes to a lot of models. If you have many models that all share the same fields, this might be an option. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your **python** code. This code is a cleaner way(I think!!!) to do it and will do the same that [this one](http://www.djangosnippets.org/snippets/317/). I hope this piece of code will be useful for you.

  • models
  • model
  • dry
  • common
Read More

jmrbcu has posted 2 snippets.