From c98ac3e83e537577cb90b2840c022e13e1c3c2b1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 29 May 2013 14:08:48 +0100 Subject: Added get_url hook to HyperlinkedIdentityField in line with HyperlinedRelatedField. Closes #883 --- rest_framework/relations.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'rest_framework/relations.py') diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 41707efc..42abf3ca 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -537,6 +537,25 @@ class HyperlinkedIdentityField(Field): if format and self.format and self.format != format: format = self.format + # Return the hyperlink, or error if incorrectly configured. + try: + return self.get_url(obj, view_name, request, format) + except NoReverseMatch: + msg = ( + 'Could not resolve URL for hyperlinked relationship using ' + 'view name "%s". You may have failed to include the related ' + 'model in your API, or incorrectly configured the ' + '`lookup_field` attribute on this field.' + ) + raise Exception(msg % view_name) + + def get_url(self, obj, view_name, request, format): + """ + Given an object, return the URL that hyperlinks to the object. + + May raise a `NoReverseMatch` if the `view_name` and `lookup_field` + attributes are not configured to correctly match the URL conf. + """ lookup_field = getattr(obj, self.lookup_field) kwargs = {self.lookup_field: lookup_field} try: @@ -562,7 +581,7 @@ class HyperlinkedIdentityField(Field): except NoReverseMatch: pass - raise Exception('Could not resolve URL for field using view name "%s"' % view_name) + raise NoReverseMatch() ### Old-style many classes for backwards compat -- cgit v1.2.3