Django template tag iterrate object fields dynamically

Django -- Posted on Aug. 5, 2024

Django iterrate object fields dynamically

              
                import datetime
from decimal import Decimal
from django import template
from django.db import models
from django.urls import reverse,reverse_lazy, NoReverseMatch, resolve
from django.apps import apps
from django.db.models.fields.files import ImageFieldFile, FileField
from django.db.models.fields import DateTimeField
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()


@register.simple_tag
def display_data(object):
    items = {}
    for field in object._meta.fields:
        print(type(field), field.name)
        value = getattr(object,field.name)
        if isinstance(value, Decimal):
            value = round(value,0)
        elif isinstance(value, datetime.datetime):
            format = '%Y-%m-%d %H:%M:%S'
            print(format)
            # applying strftime() to format the datetime
            string = value.strftime(format)
            value = str(string)
        elif isinstance(field, models.ForeignKey):
            related_object = value  # This is the related object
            if related_object:  # Check if the related object exists
                value = str(related_object) 
        items[field.name] = value
    return items
                  
   
            

Related Posts