Using negative argument to limit flatpages

I’m using The flatpages app.

In the document, there is a headline that Limiting flatpages by base URL.


{% get_flatpages '/cookies/' as cookies_page %}

In my scenario, I need to use negative argument to limit flatpages.

Lets say, I have following flatpage URLs:

/cookies/, /privacy/, /other-1/, /other-2/, /other-3/ ...

How can I get a list of pages other than the privacy and cookies pages?

Something like:

{% get_flatpages not ‘/cookies/’ and not /'privacy/ as other_pages %}

If you look at the code in django.contrib.flatpages.templatetags.flatpages, you’ll see how get_flatpages works. It takes the parameters and creates a FlatpageNode object with the starts_with parameter (if supplied)

It’s the render method in FlatpageNode that performs the filtering using that prefix.

To do something like you describe, you’ll probably need to create your own template tag and re-implement these methods using whatever query criteria you wish to implement.

(Or, you could just implement the appropriate query on the FlatPage model within your view and pass the results in your context to your template. I guess the decision depends upon how many pages you’re going to want to do this with.)

1 Like

Thank you. I will try to implement these solutions.

However, I’m wondering that; Would following approach be so wrong for separating known pages and others?

Suppose that known pages are written as hard coded urls to reference them with url template tag.

# sample.urls                 
urlpatterns = [
    path('privacy-policy/', views.flatpage, {'url': '/privacy-policy/'}, name='privacy'),
    path('cookies-policy/', views.flatpage, {'url': '/cookies-policy/'}, name="cookies")
# sample.html                 
{% load flatpages %}                 
{% get_flatpages as flatpages %}

<h2>Other pages</h2>
{% for page in flatpages %}
	{% if page.url != "/cookies-policy/" and page.url != "/privacy-policy/" %}
       <li><a href="{{ page.url }}">{{ page.title }}</a></li>
    {% endif %}
{% endfor %}
<h2>Known pages</h2>
<a href="{% url 'cookies' %}" >Cookies Policy</a>
<a href="{% url 'privacy' %}">Privacy Policy</a>

That’s a judgement call, based on a principle I’ve developed over the years.

Would I say it’s wrong? Yes.

I’m a strong believer in the separation of functionality between the views and templates. Logic that determines what is to be rendered belongs in the view. Logic that adds or excludes data to be rendered does not belong in the template.
(As mentioned elsewhere here on a number of occasions, this principle comes from having been subjected to multiple Java applications that retrieve and augment data to be displayed both in servlets and JSPs. Such situations create maintenance nightmares.)

Having said all that, would I say you would be wrong in adopting that? Nope There’s nothing intrinsically wrong with doing it that way. That’s just a choice I would not make.

1 Like