Taras
Taras

Reputation: 507

How to access to get URL address by name in Django at model file (like {{ url 'urlname' }} at template)

Need to access URL by name at model, can't just hardcode it. Need it for error message for a new object creating. Any suggestions?

Update: Just need to put url to error message, not reverse

Upvotes: 0

Views: 270

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599630

Your question is not totally clear, but I think you are asking about the reverse function.

Upvotes: 1

Karim N Gorjux
Karim N Gorjux

Reputation: 3033

I suggest you use a template tag. You can build one for your model and avoid polluting the model about stuff not related to the domain level and keep the presentation level to the template.

Check the docs here on how add a templatetags your app.: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/

Here a snippet of code to use as starting point for your url generation

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def url_for_object(context, object):
    # you have both the context and the object available to
    # generate your url here
    url = ....
    return url

In your template use

{% url_for_object my_object %}

Upvotes: 0

Uroš Trstenjak
Uroš Trstenjak

Reputation: 903

You can define get_absolute_url method in your model and than access it in other model's methods. Check https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url

Upvotes: 0

Related Questions