Pankaj Sharma
Pankaj Sharma

Reputation: 2277

django template tag missing 1 required positional argument : value

In my django project, I have custom template tag to set correct next link in pagination:

@register.tag(name='url_replace')
def url_replace(request, field, value):
   print('this is form tag',request,field,value)
   d = request.GET.copy()
   d[field] = value
   return d.urlencode()

In my template:

  {% if is_paginated %}
    <ul class="pagination pull-right">
      {% if page_obj.has_previous %}
        <li><a href="?{% url_replace request 'page' page_obj.previous_page_number %}">&laquo;</a></li>
      {% else %}
        <li class="disabled"><span>&laquo;</span></li>
      {% endif %}
      {% for i in paginator.page_range %}
        {% if page_obj.number == i %}
          <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
        {% else %}
          <li><a href="?{% url_replace request 'page' i %}">{{ i }}</a></li>
        {% endif %}
      {% endfor %}
      {% if page_obj.has_next %}
        <li><a href="?{% url_replace request 'page' page_obj.next_page_number %}">&raquo;</a></li>
      {% else %}
        <li class="disabled"><span>&raquo;</span></li>
      {% endif %}
    </ul>
  {% endif %}

Looks every thing fine but it is showing me error:

Exception Value:
url_replace() missing 1 required positional argument: 'value'

I'm unable to figure out the problem as I passed all three arguments!

Upvotes: 1

Views: 718

Answers (2)

You should use @register.simple_tag whose function can get the values from the template tag as shown below, then the error is solved. *@register.tag's function cannot get the values but can get the tokens from the template tag and you can see my answer explaining more about @register.simple_tag and @register.tag:

# @register.tag(name='url_replace')
@register.simple_tag(name='url_replace')
def url_replace(request, field, value):
    # ...
             #        Values
             #      ↓    ↓    ↓
{% url_replace request 'page' i %}

In addition, @register.tag's function must have parser as the 1st parameter and token as the 2nd parameter in convention (other names are fine) otherwise there is an error.:

@register.tag(name='url_replace')
def url_replace(parser, token):
               #  ↑       ↑
               # 2 parameters

Upvotes: 0

eran
eran

Reputation: 6931

Change the @register.tag to @register.simple_tag. @register.tag is something bit more complicated

compare https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#django.template.Library.simple_tag with https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#registering-the-tag

Upvotes: 1

Related Questions