|
1 | 1 | title: django.urls.exceptions NoReverseMatch Python Code Examples |
2 | 2 | category: page |
3 | 3 | slug: django-urls-exceptions-noreversematch-examples |
4 | | -sortorder: 500013610 |
| 4 | +sortorder: 500013640 |
5 | 5 | toc: False |
6 | 6 | sidebartitle: django.urls.exceptions NoReverseMatch |
7 | 7 | meta: Python example code for the NoReverseMatch exception class from the django.urls.exceptions module. |
8 | 8 |
|
9 | 9 |
|
10 | | -[NoReverseMatch](https://docs.djangoproject.com/en/dev/ref/exceptions/#noreversematch) |
11 | | -([source code](https://github.com/django/django/blob/b9cf764be62e77b4777b3a75ec256f6209a57671/django/urls/exceptions.py)) |
| 10 | +[NoReverseMatch](https://docs.djangoproject.com/en/stable/ref/exceptions/#noreversematch) |
| 11 | +([source code](https://github.com/django/django/blob/master/django/urls/exceptions.py)) |
12 | 12 | is a [Django](/django.html) exception that is raised when a URL |
13 | 13 | cannot be matched against any string or regular express in your URL |
14 | 14 | configuration. |
@@ -103,3 +103,191 @@ def get_current_remote_methods(view): |
103 | 103 | return _get_remote_methods_for(view, |
104 | 104 | view.request.path_info) |
105 | 105 | ``` |
| 106 | + |
| 107 | + |
| 108 | +## Example 2 from AuditLog |
| 109 | +[Auditlog](https://github.com/jjkester/django-auditlog) |
| 110 | +([project documentation](https://django-auditlog.readthedocs.io/en/latest/)) |
| 111 | +is a [Django](/django.html) app that logs changes to Python objects, |
| 112 | +similar to the Django admin's logs but with more details and |
| 113 | +output formats. Auditlog's source code is provided as open source under the |
| 114 | +[MIT license](https://github.com/jjkester/django-auditlog/blob/master/LICENSE). |
| 115 | + |
| 116 | +[**AuditLog / src / auditlog / mixins.py**](https://github.com/jjkester/django-auditlog/blob/master/src/auditlog/mixins.py) |
| 117 | + |
| 118 | +```python |
| 119 | +import json |
| 120 | + |
| 121 | +from django.conf import settings |
| 122 | +try: |
| 123 | + from django.core import urlresolvers |
| 124 | +except ImportError: |
| 125 | + from django import urls as urlresolvers |
| 126 | +~~try: |
| 127 | +~~ from django.urls.exceptions import NoReverseMatch |
| 128 | +~~except ImportError: |
| 129 | +~~ from django.core.urlresolvers import NoReverseMatch |
| 130 | +from django.utils.html import format_html |
| 131 | +from django.utils.safestring import mark_safe |
| 132 | + |
| 133 | +MAX = 75 |
| 134 | + |
| 135 | + |
| 136 | +class LogEntryAdminMixin(object): |
| 137 | + |
| 138 | + def created(self, obj): |
| 139 | + return obj.timestamp.strftime('%Y-%m-%d %H:%M:%S') |
| 140 | + created.short_description = 'Created' |
| 141 | + |
| 142 | + def user_url(self, obj): |
| 143 | + if obj.actor: |
| 144 | + app_label, model = settings.AUTH_USER_MODEL.split('.') |
| 145 | + viewname = 'admin:%s_%s_change' % (app_label, model.lower()) |
| 146 | +~~ try: |
| 147 | +~~ link = urlresolvers.reverse(viewname, args=[obj.actor.id]) |
| 148 | +~~ except NoReverseMatch: |
| 149 | +~~ return u'%s' % (obj.actor) |
| 150 | + return format_html(u'<a href="{}">{}</a>', link, obj.actor) |
| 151 | + |
| 152 | + return 'system' |
| 153 | + user_url.short_description = 'User' |
| 154 | + |
| 155 | + def resource_url(self, obj): |
| 156 | + app_label, model = obj.content_type.app_label, obj.content_type.model |
| 157 | + viewname = 'admin:%s_%s_change' % (app_label, model) |
| 158 | +~~ try: |
| 159 | +~~ args = [obj.object_pk] if obj.object_id is None else [obj.object_id] |
| 160 | +~~ link = urlresolvers.reverse(viewname, args=args) |
| 161 | +~~ except NoReverseMatch: |
| 162 | +~~ return obj.object_repr |
| 163 | +~~ else: |
| 164 | +~~ return format_html(u'<a href="{}">{}</a>', link, obj.object_repr) |
| 165 | + resource_url.short_description = 'Resource' |
| 166 | + |
| 167 | + def msg_short(self, obj): |
| 168 | + if obj.action == 2: |
| 169 | + return '' # delete |
| 170 | + changes = json.loads(obj.changes) |
| 171 | + s = '' if len(changes) == 1 else 's' |
| 172 | + fields = ', '.join(changes.keys()) |
| 173 | + if len(fields) > MAX: |
| 174 | + i = fields.rfind(' ', 0, MAX) |
| 175 | + fields = fields[:i] + ' ..' |
| 176 | + return '%d change%s: %s' % (len(changes), s, fields) |
| 177 | + msg_short.short_description = 'Changes' |
| 178 | + |
| 179 | + def msg(self, obj): |
| 180 | + if obj.action == 2: |
| 181 | + return '' # delete |
| 182 | + changes = json.loads(obj.changes) |
| 183 | + msg = '<table><tr><th>#</th><th>Field</th><th>From</th><th>To</th></tr>' |
| 184 | + for i, field in enumerate(sorted(changes), 1): |
| 185 | + value = [i, field] + (['***', '***'] if field == 'password' else changes[field]) |
| 186 | + msg += format_html('<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>', *value) |
| 187 | + |
| 188 | + msg += '</table>' |
| 189 | + return mark_safe(msg) |
| 190 | + msg.short_description = 'Changes' |
| 191 | + |
| 192 | +``` |
| 193 | + |
| 194 | + |
| 195 | +## Example 3 from django-filer |
| 196 | +[django-filer](https://github.com/divio/django-filer) |
| 197 | +([project documentation](https://django-filer.readthedocs.io/en/latest/)) |
| 198 | +is a file management library for uploading and organizing files and images |
| 199 | +in Django's admin interface. The project's code is available under the |
| 200 | +[BSD 3-Clause "New" or "Revised" open source license](https://github.com/divio/django-filer/blob/develop/LICENSE.txt). |
| 201 | + |
| 202 | +[**django-filer / filer / models / filemodels.py**](https://github.com/divio/django-filer/blob/develop/filer/models/filemodels.py) |
| 203 | + |
| 204 | +```python |
| 205 | +# -*- coding: utf-8 -*- |
| 206 | +from __future__ import absolute_import, unicode_literals |
| 207 | + |
| 208 | +import hashlib |
| 209 | +import os |
| 210 | +from datetime import datetime |
| 211 | + |
| 212 | +from django.conf import settings |
| 213 | +from django.core.files.base import ContentFile |
| 214 | +from django.db import models |
| 215 | +~~from django.urls import NoReverseMatch, reverse |
| 216 | +from django.utils import timezone |
| 217 | +from django.utils.encoding import python_2_unicode_compatible |
| 218 | +from django.utils.translation import ugettext_lazy as _ |
| 219 | + |
| 220 | +from .. import settings as filer_settings |
| 221 | +from ..fields.multistorage_file import MultiStorageFileField |
| 222 | +from . import mixins |
| 223 | +from .foldermodels import Folder |
| 224 | + |
| 225 | + |
| 226 | +try: |
| 227 | + from polymorphic.models import PolymorphicModel |
| 228 | + from polymorphic.managers import PolymorphicManager |
| 229 | +except ImportError: |
| 230 | + # django-polymorphic < 0.8 |
| 231 | + from polymorphic import PolymorphicModel, PolymorphicManager |
| 232 | + |
| 233 | + |
| 234 | +class FileManager(PolymorphicManager): |
| 235 | + def find_all_duplicates(self): |
| 236 | + r = {} |
| 237 | + for file_obj in self.all(): |
| 238 | + if file_obj.sha1: |
| 239 | + q = self.filter(sha1=file_obj.sha1) |
| 240 | + if len(q) > 1: |
| 241 | + r[file_obj.sha1] = q |
| 242 | + return r |
| 243 | + |
| 244 | + def find_duplicates(self, file_obj): |
| 245 | + return [i for i in self.exclude(pk=file_obj.pk).filter(sha1=file_obj.sha1)] |
| 246 | + |
| 247 | + |
| 248 | +def is_public_default(): |
| 249 | + # not using this setting directly as `is_public` default value |
| 250 | + # so that Django doesn't generate new migrations upon setting change |
| 251 | + return filer_settings.FILER_IS_PUBLIC_DEFAULT |
| 252 | + |
| 253 | + |
| 254 | +@python_2_unicode_compatible |
| 255 | +class File(PolymorphicModel, mixins.IconsMixin): |
| 256 | + file_type = 'File' |
| 257 | + _icon = "file" |
| 258 | + _file_data_changed_hint = None |
| 259 | + |
| 260 | + folder = models.ForeignKey( |
| 261 | + Folder, |
| 262 | + verbose_name=_('folder'), |
| 263 | + related_name='all_files', |
| 264 | + null=True, |
| 265 | + blank=True, |
| 266 | + on_delete=models.CASCADE, |
| 267 | + ) |
| 268 | + file = MultiStorageFileField(_('file'), null=True, blank=True, max_length=255) |
| 269 | + _file_size = models.BigIntegerField(_('file size'), null=True, blank=True) |
| 270 | + |
| 271 | + sha1 = models.CharField(_('sha1'), max_length=40, blank=True, default='') |
| 272 | + |
| 273 | + has_all_mandatory_data = models.BooleanField(_('has all mandatory data'), default=False, editable=False) |
| 274 | + |
| 275 | + |
| 276 | +## ... source file abbreviated to get to the examples ... |
| 277 | + |
| 278 | + |
| 279 | + @property |
| 280 | + def canonical_url(self): |
| 281 | + url = '' |
| 282 | +~~ if self.file and self.is_public: |
| 283 | +~~ try: |
| 284 | +~~ url = reverse('canonical', kwargs={ |
| 285 | +~~ 'uploaded_at': self.canonical_time, |
| 286 | +~~ 'file_id': self.id |
| 287 | +~~ }) |
| 288 | +~~ except NoReverseMatch: |
| 289 | +~~ pass # No canonical url, return empty string |
| 290 | + return url |
| 291 | + |
| 292 | +## ... source file continues with no further relevant examples ... |
| 293 | +``` |
0 commit comments