0

i like to use the url template tag in my model's content.

example:

models content:

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

in template.html:

<div>{{ Car.description }}</div>

result

<div>this is a link to our main page: <a href="/">home</a>

is it possible, or do i have to write my own template tag?

thanks in advance Roman

1

2 Answers 2

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..

Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

i just want to store an internal link in the car's description. to ensure that it is valid when the url changes, i need to use the {{ url }} template tag behaviour. or is it possible to use template tags in a model field?
Can't you store the link on it's own and then render it as usual at template level?
it has to be in the text, and a user should be able to set another link. a wiki is a better example.
Then IMO it would be better to store the full URL at DB level (rather than a "renderable" URL tag) and then use autoescape.
OK, i'll give both a template-tags and a custom model property a try Thank.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.