Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django dynamic url parameter names

Basically trying to do

    {%  url dynamic_url_name dynamic_parameter_name=dynamic_parameter_value %}

Tried the simplest approach of

<a href="{% url belongs_to belongs_to_url_arg=entry|getattribute:belongs_to_url_arg_value %}">{{entry}}</a>
    {% include 'mainsite/children/title_template.html' with
        the_title=title_text
        is_title_page=True
        entries_of="title"
        belongs_to="profile"
        belongs_to_url_arg="user"
        belongs_to_url_arg_value="author"
    %}

But unfortunately this resulted in utter failure of enter image description here

From this I can tell that parameters can't be context variables, so what I can try to do next is to simply unpack a dictionary as I would do inside python with something like

{% url **{dynamic_parameter_name:dynamic_parameter_value} %}

But I have no idea if it is possible inside django templates, and if possible how?


My urls look like

re_path(r'^title/(?P<title_text>[a-zA-Z0-9-]+)/$', TitlePage.as_view(), name='title')
re_path(r'^user/(?P<user>[a-zA-Z0-9-]+)/$', ProfilePage.as_view() ,name='profile')

And I the url is choosen either by a context variable or in an include tag, hence it is a variable.

{% url url_variable xxx=value %}

Now, url_variable is already a part of django, url tag accepts variable as it's first argument. But the xxx is not always the same, rather it changes according to url_variable, in this particular case; if url_variable is title, I want xxx to be title_text and if it is profile I want it to be user. The parameter name is held in belongs_to, so if this was a regular python function, I could've simply done

url(url_variable, **{belongs_to: value})

and it would've unpacked it with the correct parameter name. So I need some kind of equivalency of this in template processor

like image 822
Işık Kaplan Avatar asked Feb 26 '26 15:02

Işık Kaplan


1 Answers

I think you're overcomplicating things. You haven't shown your views themselves, but I can't see why they couldn't all take a commonly-named parameter - say, param - that does the specific work. So the URLs could be:

re_path(r'^title/(?P<param>[a-zA-Z0-9-]+)/$', TitlePage.as_view(), name='title')
re_path(r'^user/(?P<param>[a-zA-Z0-9-]+)/$', ProfilePage.as_view() ,name='profile')

and now you can do

{% url dynamic_url_name param=dynamic_parameter_value %}
like image 190
Daniel Roseman Avatar answered Feb 28 '26 05:02

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!