简体   繁体   中英

Passing object as kwargs to URL tag in template?

Let's say I have a model like the following

from django.db import models
class Person(models.Model):
    first_name = models.CharField(max_length=36)
    last_name = models.CharField(max_length=36)

and I have in urls.py a URL like

path(r'profile/<str:first_name>/<str:last_name>/', ..., name='profile')

In the template, if there's a variable person I could get their profile url by typing {% url "profile" person.first_name person.last_name %} .

However, I would really prefer to not repeat myself and do something more along the lines of {% url "profile" **person %} --- that's not a valid syntax but the point is I'd like to use the attributes on person as the arguments to the URL tag. That way, if I ever change the URL pattern to use, say, middle_name as well, I don't need to edit the template again.

Is there a (preferably built-in, but custom tags okay too) way to do this? I've spent a while on google with queries like "django url template tag kwargs" but haven't found anything. (And I want to avoid changing the URL itself since it is exposed to end user.)

Instead of using a template tag you can simply add a method to your model class that will return the correct url for that model. A commonly used method is get_absolute_url [Django docs] which is even used by Class Based Views to get the url to redirect after successful form submission, etc. The implementation for you would be something like:

from django.db import models
from django.urls import reverse


class Person(models.Model):
    first_name = models.CharField(max_length=36)
    last_name = models.CharField(max_length=36)
    
    def get_absolute_url(self):
        return reverse('profile', kwargs={'first_name' : self.first_name, 'last_name': last_name})

Now in the template you can simply write:

{{ person.get_absolute_url }}

Note : First names and Last names won't make good parameters for urls as a person may have spaces in their first name, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM