Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building reverse urls in get_resource_uri

if anybody reads the Tastypie-Mailinglist: I did not get an answer there, so sorry for crossposting here.

In Tastypie, I changed a Resource's URL pattern, because I use another key than the PK. This works fine when I access the Resource. Now I want to nest this Resource into a parent Resource, but the nested Resource contains the URIs with the PK, not my custom key. What I learned is that in my case, I have to change the child's get_resource_uri.

The method in my child's resource (which is a NamespacedResource) looks like this:

def get_resource_uri(self, bundle_or_obj):

    obj = bundle_or_obj.obj if isinstance(bundle_or_obj, Bundle) else bundle_or_obj

    kwargs={
        'resource_name': self._meta.resource_name,
        'custom_id': obj.custom_id
        }

    return self._build_reverse_url('api_dispatch_detail', kwargs=kwargs)

The child's url override method is this:

def override_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<custom_id>[-_\w\d]+)%s$" % (
                self._meta.resource_name,
                trailing_slash()
            ),
            self.wrap_view('dispatch_detail'),
            name="api_dispatch_detail"
        ),
    ]

But the application cannot reverse the URL. I get this error:

Reverse for 'api_dispatch_detail' with arguments '()' and keyword arguments '{'custom_id': u'3_ee5-4423', 'resource_name': 'myresource'} not found.

How do I reverse the URL correctly?

Thanks in advance.

like image 417
schneck Avatar asked Nov 04 '22 16:11

schneck


1 Answers

The tastypie's internal urls always need resource_name and api_name kwargs.

Your kwargs should contain:

kwargs = {
    'api_name': 'v1',  # Or whatever you have set for your api
    'resource_name': self._meta.resource_name,
    'custom_id': obj.custom_id
}
like image 158
Ania Warzecha Avatar answered Nov 15 '22 05:11

Ania Warzecha