| | 2008 | In some cases, such as the use of generic views or the re-use of |
|---|
| | 2009 | custom views for multiple models, specifying the view function may |
|---|
| | 2010 | confuse the reverse URL matcher (because multiple patterns point to |
|---|
| | 2011 | the same view). |
|---|
| | 2012 | |
|---|
| | 2013 | For that problem, Django has **named URL patterns**. Using a named |
|---|
| | 2014 | URL patter, it's possible to give a name to a pattern, and then |
|---|
| | 2015 | reference the name, rather than the view function. A named URL |
|---|
| | 2016 | pattern is defined by replacing the pattern tuple by a call to |
|---|
| | 2017 | the ``url`` function):: |
|---|
| | 2018 | |
|---|
| | 2019 | from django.conf.urls.defaults import * |
|---|
| | 2020 | |
|---|
| | 2021 | url(r'^people/(\d+)/$', |
|---|
| | 2022 | 'django.views.generic.list_detail.object_detail', |
|---|
| | 2023 | name='people_view'), |
|---|
| | 2024 | |
|---|
| | 2025 | and then using that name to perform the reverse URL resolution instead |
|---|
| | 2026 | of the view name:: |
|---|
| | 2027 | |
|---|
| | 2028 | from django.db.models import permalink |
|---|
| | 2029 | |
|---|
| | 2030 | def get_absolute_url(self): |
|---|
| | 2031 | return ('people_view', [str(self.id)]) |
|---|
| | 2032 | get_absolute_url = permalink(get_absolute_url) |
|---|
| | 2033 | |
|---|
| | 2034 | More details on named URL patterns can be found in `URL dispatch documentation`_. |
|---|
| | 2035 | |
|---|
| | 2036 | .. _URL dispatch: ../url_dispatch/#naming-url-patterns |
|---|
| | 2037 | |
|---|