How can I get the reverse url for a Django Flatpages template

后端 未结 10 1162
情深已故
情深已故 2021-01-31 10:33

How can I get the reverse url for a Django Flatpages template

10条回答
  •  一向
    一向 (楼主)
    2021-01-31 10:51

    None of the solutions mentioned sufficiently followed the DRY principle in my opinion, so I just did this:

    # core/templatetags/hacks.py
    
    from django import template
    
    register = template.Library()
    
    @register.simple_tag
    def flaturl(title):
        """
            Returns the url for a flatpage based on the title.
            NOTE: Obviously the title must be unique.
        """
    
        from django.contrib.flatpages.models import FlatPage
    
        try:
            page = FlatPage.objects.get(title=title)
        except:
            return ""
    
        return page.url
    

    Then in any template that needs to make a link, I did this:

    {% load hacks %}
    ...
    Page Title
    

    I might add some caching in there to keep the performance up, but this works for me.

提交回复
热议问题