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

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

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

相关标签:
10条回答
  • 2021-01-31 11:04

    Include flatpages in your root urlconf:

    from django.conf.urls.defaults import *
    
    urlpatterns = patterns('',
        ('^pages/', include('django.contrib.flatpages.urls')),
    )
    

    Then, in your view you can call reverse like so:

    from django.core.urlresolvers import reverse
    
    reverse('django.contrib.flatpages.views.flatpage', kwargs={'url': '/about-us/'})
    # Gives: /pages/about-us/
    

    In templates, use the {% url %} tag (which calls reverse internally):

    <a href='{% url django.contrib.flatpages.views.flatpage url="/about-us/" %}'>About Us</a>
    
    0 讨论(0)
  • 2021-01-31 11:06

    I prefer the following solution (require Django >= 1.0).

    settings.py

    INSTALLED_APPS+= ('django.contrib.flatpages',)
    

    urls.py

    urlpatterns+= patterns('django.contrib.flatpages.views',
        url(r'^about-us/$', 'flatpage', {'url': '/about-us/'}, name='about'),
        url(r'^license/$', 'flatpage', {'url': '/license/'}, name='license'),
    )
    

    In your templates

    [...]
    <a href="{% url about %}"><span>{% trans "About us" %}</span></a>
    <a href="{% url license %}"><span>{% trans "Licensing" %}</span></a>
    [...]
    

    Or in your code

    from django.core.urlresolvers import reverse
    [...]
    reverse('license')
    [...]
    

    That way you don't need to use django.contrib.flatpages.middleware.FlatpageFallbackMiddleware and the reverse works as usual without writing so much code as in the other solutions.

    Cheers.

    0 讨论(0)
  • 2021-01-31 11:08

    According to this django documentation for flatpages

    You can simply do

    {% load flatpages %}
    {% get_flatpages as flatpages %}
    <ul>
        {% for page in flatpages %}
            <li><a href="{{ page.url }}">{{ page.title }}</a></li>
        {% endfor %}
    </ul>
    

    In your template.

    0 讨论(0)
  • 2021-01-31 11:09

    When you create any flatpage, you need to specify an URL which is saved as part of the model. Hence you can retrieve the URL from any flatpage object. In a template:

    {{ flatpage.url }}
    

    Remapping flatpage URLs in urls.py and then having to use reverse sort of defeats the purpose of the flatpages app.

    0 讨论(0)
提交回复
热议问题