1

I've tried to implement the following solution from here: How to paginate Django with other get variables?

I added this to my views.py

from urllib.parse import urlencode
from django import template
register = template.Library()

@register.simple_tag
def url_replace(request, field, value):

    dict_ = request.GET.copy()

    dict_[field] = value

    return dict_.urlencode()

def teacher_list(request, **kwargs):
    paginator = Paginator(results, 1)
    page = request.GET.get('page')

    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        results = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        results = paginator.page(paginator.num_pages)

template.html

{% if teacher_list.has_next %}
<li><a href="?{% url_replace request 'page' teacher_list.next_page_number %}">Next</a></li>
{% endif %}

However, this gives me: Invalid block tag on line 155: 'url_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

I also tried loading:

@register.simple_tag(takes_context=True)
def url_replace(context, **kwargs):
    query = context['request'].GET.dict()
    query.update(kwargs)
    return urlencode(query)

without success. I also tried:

@register.simple_tag(takes_context=True)
def url_replace(request, **kwargs):
    query = request.GET.dict()
    query.update(kwargs)
    return urlencode(query)

None of these seem to work.

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Roma
  • 449
  • 6
  • 23

1 Answers1

1

Django could not to load your tag

by docs custom-template-tags

you need add templatetags (change your_app and your_tags on your valid values):

your_app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        your_tags.py

in the template load your tags

{% load your_tags %}
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • Thanks a lot! This works. I hope there are no security implications with such way of using GET requests. Also, I was wondering if you offer consulting services? – Roma Sep 25 '17 at 14:39
  • glad to help you! i'm not sure for security, any way i think it better to use some mapping of available get params. about consulting: in my mind SO more better solution) – Brown Bear Sep 25 '17 at 14:48
  • Yes, SO is great, but there are some bits to the projects that are beyond the scope that I can learn anytime soon and I'm concerned about my code optimisation. I would also like to launch the projects and I would like to have someone senior to look and improve my code. If you work as a freelancer, I would gladly pay for your services. – Roma Sep 25 '17 at 15:00
  • sorry for long time of the answer, but now i'm working on hard project, and SO it is place where i can to relax a little. – Brown Bear Sep 25 '17 at 19:28
  • Oh, no problem :) – Roma Sep 25 '17 at 19:32