dowjones123
dowjones123

Reputation: 3837

Django rest framework - including url for authentication

I am following the DJango rest framework tutorial here:

http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#adding-login-to-the-browsable-api

And, at the end of the file, add a pattern to include the login and logout views for the browsable API.

urlpatterns += patterns('',
    url(r'^api-auth/', include('rest_framework.urls',
                               namespace='rest_framework')),
)

It says:

The r'^api-auth/' part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework' namespace.

I don't understand why this is the case,i.e. why it does not matter what the string "api-auth" is, it seems to function properly for any string XXXX in the regex

Upvotes: 3

Views: 2460

Answers (1)

agconti
agconti

Reputation: 18103

Just like r'/admin' doesnt matter what you actually name it. In a general sense, Its just a mapping a of from a string, matching the url request to a class or function based view. Conceptually it's the same as the dictionary below:

{
 'add': lambda x, y: x + y,
 'subtract': lambda x,y: x - y
 ... ect. ...
}

Except in Django the keys, add and subtract, are regex url patterns and the 'SomeView.as_view()' are the lambda functions. Something like this:

{
 r'^about/$': TemplateView.as_view(template_name='pages/about.html'),
 r'^admin/': include(admin.site.urls)
}

when you include('rest_framework.urls') your including the Django Rest-Framework's own mapping of url patterns to views, just like the about above. You can think of it as a nested dict:

{
 r'^about/$': TemplateView.as_view(template_name='pages/about.html'),
 r'^admin/': {
   r'^about/$': TemplateView.as_view(template_name='pages/about.html'),
   r'^admin/': include(admin.site.urls)
   }
}

More information on how django processes requests can be found from the django docs here.

Upvotes: 2

Related Questions