[Answer]-Using variables in Django model content

0đź‘Ť

âś…

I can’t figure out why you would need to do that. Assuming that I fully-understood your question, you are attempting to store something within a model’s field that then behaves “dynamically” when rendered.

A model field’s content that stores a URL should contain a URL and only a URL by utilizing the URLField.

Else, if you’re dynamically building the URL from somewhere else, simply use template markup, i.e. the url template tag as it is meant to be used; it can also take parameters depending on the specific URL pattern. I.e. the url tag is meant to be used in the template’s context.

Let me know if you update the question to describe what you are trying to achieve. But storing “behaviour” at data level is something to simply stay away from.

1đź‘Ť

Assuming you have this:

car.description = 'this is a link to our main page: <a href="{{ url }}">home</a>'

You can do:

from django.template import Context, Template
from django.core.urlresolvers import reverse


class Car(models.Model):
    def description_with_url(self):
        return Template(self.description).render({'url': reverse('home')})

or use the same logic in custom template tag instead of method..

👤mariodev

Leave a comment