Skip to main content

Django template tags to find out field type


Sometimes you have the task to decorate django form fields. In our case it was need to add different widget to form field depending on field type.
You can know your field type by refering to it's python class name, e.g.:
field.__class__.__name__


You will get wrong symbols error if you try to refer this python variable in templates directly. So you need a custom template tag to serve here. Decision was not to return variable for tag but to add context variable, cause I had need to perform exact actions on certain field types.

So tag example:
@register.simple_tag(takes_context=True)
def set_this_field_type(context, field):
    """
    Adds to context given field type variable
    variable named "this_field_type"
    """
    context["this_field_type"] = field.field.__class__.__name__
    return ''
Now you can add this variable to your if statements. E.g. usage:
{% load my_template_lib %}
{% for field in form %}
    {# Setting this field type in context #}
    {% set_this_field_type field %}
{% if not this_field_type = "DateField" %}
    {# Rendering specific for Date fields (With DatePicker widget) #}
    <div class="field-wrapper {{ this_field_type }}"
        <label class="control-label">{{ field.label }}</label>
        <input id="{{ field.id_for_label }}" class="datepicker-widget" type="text" name="{{ field.name }}">
    </div>
{% else %}
    {# Default field rendering #}
    <div class="field-wrapper {{ this_field_type }}"
         <label class="control-label">{{ field.label }}</label>
        {{ field }}
    </div>
{% endif %}
{% endfor %}
You will get your form fields rendered in custom manner. You will have the CSS class with field type for styling or you can use this variable in context to render various widgets for e.g.
Hope you've got the main concept here. Now this idea must be limited only by your imagination.

Including those "simple" approaches kindly suggested by guys at 'reddit.com' They are more simple and can play in your case maybe ;)
Using the filter: (Thanks to POTUS @reddit.com)

@register.filter()
def field_type(field):
    return field.field.__class__.__name__

{% if not field|field_type ="DateField" %}
    <span>Whatever</span>
{%endif%}


Using the widget: (Thanks to tgerdes @reddit.com)

from django import forms
class DateForm(forms.Form):
    date = forms.DateField(
      widget=forms.DateInput(attrs= {'class': 'datepicker-widget' } ))

form = DateForm()
print form.as_p()

outputs: <p><label for="id_date">Date:</label> <input id="id_date" type="text" class="datepicker-widget" name="date" /></p>

However this approach in not this topics main cause it concludes we only have to style input. But in some cases it may be quite enough...

Thanks guys for correction!

Please drop me a comment here if you've liked/used this decision(s).


Comments

  1. Thank you man, I really like this simple approach.

    To make it more complex is there possibility to do the same using 'with' tag?

    ReplyDelete
    Replies
    1. I think that answer is yes.
      You will get context variable "this_field_type" and can use this in whatever approach you are using. It will always be equal to string representation of field name. BTW... You can change context["this_field_type"] to context["whatever_name_you_like"] and do not use the "with" tag... Only if your logic is simple enough though...
      OR you can make simple tag return something and stick to that. In my case it had to create a variable for iteration usage...

      Delete

Post a Comment

Popular posts from this blog

Pretty git Log

SO you dislike git log output in console like me and do not use it... Because it looks like so: How about this one? It's quite easy... Just type: git log - - graph - - pretty = format : '%Cred%h%Creset -%C ( yellow ) %d%Creset %s %Cgreen ( %cr) %C ( bold blue ) <%an>%Creset' - - abbrev - commit - - It may be hard to enter such an easy command every time. Let's make an alias instead... Copypaste this to your terminal: git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --" And use simple command to see this pretty log instead: git lg Now in case you want to see lines that changed use: git lg - p In order for this command to work remove  the -- from the end of the alias. May the code be with you! NOTE: this article is a rewritten copy of  http://coderwall.com/p/euwpig?i=3&p=1&t=git   and have b...

Django: Resetting Passwords (with internal tools)

I have had a task recently. It was about adding a forms/mechanism for resetting a password in our Django based project. We have had our own registration system ongoing... It's a corporate sector project. So you can not go and register yourself. Admins (probably via LDAP sync) will register your email/login in system. So you have to go there and only set yourself a password. For security reasons you can not register. One word. First I've tried to find standart decision. From reviewed by me were: django-registration and django password-reset . These are nice tools to install and give it a go. But I've needed a more complex decision. And the idea was that own bicycle is always better. So I've thought of django admin and that it has all the things you need to do this yourself in no time. (Actually it's django.contrib.auth part of django, but used out of the box in Admin UI) You can find views you need for this in there. they are: password_reset password_reset_...

Vagrant error: * Unknown configuration section 'hostmanager'.

Sometimes you get a vagrant environment or boilerplate with a Vagrantfile config in there and do a vagrant up command. And see some errors. like this: There are errors in the configuration of this machine . Please fix the following errors and try again : Vagrant: * Unknown configuration section 'hostmanager'. To fix this one needs: $ vagrant plugin install vagrant - hostmanager Installing the ' vagrant-hostmanager ' plugin . This can take a few minutes . . . Fetching : vagrant - hostmanager - 1.8 .6 . gem ( 100 % ) Installed the plugin ' vagrant-hostmanager (1.8.6) ' ! So command to fix this as follows: vagrant plugin install vagrant-hostmanager