Django Display Objects Data from Database Django.How

Author avatar wrote on 06/06/2022

Boolean prints in a django template?


  {{ bool_var|yesno:"Agree,Disagree" }}

 

Or

 {% if var == True %} Yes {% else %} No {% endif %}

</code

Default if value evaluates to False (e.g. None, an empty string, 0, False)

{{ profile.user.first_name|default:"--" }}

 

Default_if_none

{{ profile.user.first_name|default_if_none:"--" }}

 

Choice display

 {{ x.get_choices_display }}

 

Filed choice check

 {% if tr_language.language|stringformat:'s'  == 'N' %}
 

 

Checkbox

Select

If options are not passed

Field choices with key values

In view

context['unit_choices'] = CompanyService._meta.get_field('unit').choices

 

In template

Get value from multiple select

lang_list = request.POST.getlist('languages')
for language in lang_list:
    lang_obj = Language.objects.get(id=language)
    GlossaryLanguage(glossary=p1, language=lang_obj).save()

 

Date and Time

Default input value

With local time

        {{ request.date_time|localtime|date:'Y-m-d' }} at {{ request.date_time|localtime|date:'H:i' }}

 

Or

        {% with local=request.date_time|localtime %}
            Leave on {{ local|date:'Y-m-d' }} at {{ local|date:'H:i' }}
        {% endwith %}

 

If the date is string you need to convert it to date first in the view

        if isinstance(date_from, str):
            date_from = datetime.strptime(date_from, '%Y-%m-%d')

 

Date with default after 3 days

Radio button

CRUDgen Django CRUD generator