3

I know you can refer to a urlname in a template so that you don't need to hardcode your url links in your templates whenever you want to change them.

For example in a template, I use:

<a href="{% url 'urlname' parameter %}">The link</a>

My problem is, if I want to pass a more complex parameter to be used in the url regex. In my case, I want to pass a concatenation of two strings separated by an "_". Those strings come from Python objects and I don't get how to do that. Let's say for example, those strings are the firstname and lastname of a user.

I tried:

<a href="{% url 'urlname' "user.firstname_user.lastname" %}">The link</a>

And others tricks but none worked.

Can someone help?

MarAja
  • 1,547
  • 4
  • 20
  • 36

2 Answers2

3

Simply, you don't.

You either adjust your url to have two capture groups (which would also require a slight change to the view)

url(r'(?P<first_name>\w+)_(?P<last_name>\w+)/$', view_name, name='url_name')
{% url 'urlname' user.firstname user.lastname %}

Or you just find a different url that suffices.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 1
    ^^ Actually when you say it, it is just so logic! I nevertheless found a trick with the "with keyword" and the "add function" but it was quite dirty... – MarAja Jun 01 '16 at 11:45
  • @MarAja - It sounds like you'd be better off creating a custom template tag, although Its still cleaner to just make a url to do it – Sayse Jun 01 '16 at 11:51
0

Please have a look at this thread. The good answer for you, assuming you're using posititionnal arguments :

<a href="{% url 'urlname' parameter=user.firstname_user.lastname %}">The link</a>

Assuming your url conf is like so :

url(r'^urlname/(?P<parameter>(catching regexp))$',...)
Community
  • 1
  • 1
Maxime B
  • 966
  • 1
  • 9
  • 30
  • If you believe a question is a duplicate, then you should leave a link to it as a comment (and then later voting to close when you have 3k+ rep) – Sayse Jun 01 '16 at 11:34
  • It might be a duplicate, but maybe his case isn't covered. – Maxime B Jun 01 '16 at 11:37