Django Rest Framework Tests HyperlinkedRelatedField

I have a Django 1.8.9 application using Django Rest Framework 3.3.2 and Python 3.4

I willing to test whether my API behaves as it should be.

I'm stuck on a test which aims to verify if I can post data into a model via the API. Problem is: this model has a Foreign Key relation with another model. This foreign key is transformed into a Hyperlink by the HyperlinkedModelSerializer.

e.g: http://host:port/api/relation-model-name/id-related-model

Here is my test: (the important part is data={...})

    def test_api_create(self):
       """ Test the creation of new entries via the API """

       url = reverse(self.api_model_url+'-list')

       data = {'sid':'New change entry', 'status':'THE HYPERLINK TO THE RELATED MODEL SHOULD BE HERE', 'name':'New change entry'}

       # Check that a new entry can be created by an administrator via the API
       self.api_client.login(username='admin', password='admin')
       response =, data, format='json')
       content = self.parse_json_response(response, Status.HTTP_201_CREATED)
       self.assertEqual(content['sid'], 'New change entry')

This test works if I hard write the HyperLink but I want to build it in a generic way. I can easily retrieve the id of the related field. I would like to obtain the hyperlink in my tests.

Thanks in advance for your help!



You should have a look at how HyperlinkedRelatedField retrieves the url:

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.
    # Unsaved objects will not yet have a valid URL.
    if hasattr(obj, 'pk') and in (None, ''):
        return None

    lookup_value = getattr(obj, self.lookup_field)
    kwargs = {self.lookup_url_kwarg: lookup_value}
    return self.reverse(view_name, kwargs=kwargs, request=request, format=format)

self.reverse is just django's normal reverse function. So basiacally you just need the view_name and the lookup_value, which in your case is the id of the related field.

Need Your Help

Handle editable hierarchical data / TreeView~DataGrid hybrid

wpf datagrid controls treeview wpf-controls

I am looking for a WPF control which is a hybrid of TreeView and DataGrid, something like the Visual Studio debugger or QuickBooks contacts list etc.