Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model object with dynamically added attributes

I'm looking for a way to dynamically add extra attributes to django model instances so that they are accessible in the template

For example,

in models.py

class Foo(models.Model):
    name = models.TextField()

in views.py

def my_view(request):
    f = Foo.objects.get(id=1234)

    # method in question
    f.____add_extra_attribute____('extra_attribute', attr_value)

    return render(request, 'my_template.html', {'foo_instance':f})

in my_template.html

<h1>{{ foo_instance.name }}</h1>
<p>{{ foo_instance.extra_attribute }}</p>

is there a way to accomplish this without rendering the instance as a dictionary instead of a Foo model object?

like image 460
adamF Avatar asked Oct 22 '25 07:10

adamF


1 Answers

Following @mgilson's comment, you can pass the extra_attribute to the template in a separate context variable:

def my_view(request):
    f = Foo.objects.get(id=1234)
    extra_attribute = attr_value
    return render(request, 'my_template.html', 
                  {'foo_instance': f, 'extra_attribute': attr_value})

If you still want to set the attribute on a model instance, you can set it directly:

f.extra_attribute = attr_value
like image 134
alecxe Avatar answered Oct 24 '25 21:10

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!