Django: dynamic url in patterns

I am trying to use a template containing a link such as:

<a href="{% url search query,page.previous_page_number %}">previous</a>

I am trying to use it in several contexts; In other words, the URL of the search alias must point to a different target, depending on the view that the template displays.

Is there a way to pass such an alias to a template so that the following (or similar) works:

direct_to_template(request, 'my_template.html', {'search': my_url_alias})
+3
source share
3 answers

As far as I know, you cannot, because for some reason I do not understand, the tag urldoes not accept a string as an input argument.

, url templatetag django, .

- ( ):

class NavUrlNode(Node):

    def __init__(self, *args):
        self.name_var = Variable(args[0])
        self.args=[]
        for ii in range(1,args.__len__()):
            self.args.append(Variable(args[ii]))

    def render(self, context):
        name = self.name_var.resolve(context)
        args=[]
        for ii in range(self.args.__len__()):
            args.append(self.args[ii].resolve(context))
        return reverse(name, args=args)


@register.tag
def navigation_url(parser, token):
    args = token.split_contents()
    return NavUrlNode(*args[1:])
+2

:

from django.template          import Library, Node, Variable
from django.core.urlresolvers import reverse

register = Library()

class DynUrlNode(Node):
    def __init__(self, *args):
        self.name_var = Variable(args[0])
        self.args     = [Variable(a) for a in args[1].split(',')]

    def render(self, context):
        name = self.name_var.resolve(context)
        args = [a.resolve(context) for a in self.args]
        return reverse(name, args = args)

@register.tag
def dynurl(parser, token):
    args = token.split_contents()
    return DynUrlNode(*args[1:])
+1

The knipknap solution helped me a lot, however there is one small drawback: an index error occurs every time you pass no arguments. To overcome this, simply replace the DynUrlNode constructor with the following:

   def __init__(self, *args):
    self.name_var = Variable(args[0])
    try:
        self.args     = [Variable(a) for a in args[1].split(',')]
    except IndexError:
        self.args = []
0
source

Source: https://habr.com/ru/post/1732731/


All Articles