0

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

agconti
  • 15,820
  • 15
  • 69
  • 108
dowjones123
  • 3,233
  • 5
  • 34
  • 72

1 Answers1

1

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.

agconti
  • 15,820
  • 15
  • 69
  • 108
  • Thanks, I didnt understand the answer fully, and I am looking up about the lambda functions part. Couple of observations - firstly, I figured out that 'api-auth' string is not completely irrelevant because there is a standalone login page at http://127.0.0.1:8000/api-auth/login/ (I found this by fluke, wasn't documented), so if i put the 'api-auth' string as xxxx, i need to go to login url as http://127.0.0.1:8000/xxxx/login/ – dowjones123 Jun 22 '14 at 22:53
  • Also, I may directly go to http://127.0.0.1:8000/snippets/ and I ascertained that inside the source code of HTML, in the logout link, the Log out, the xxxx is also reflected - so indeed the framework internally uses the url regex string I use – dowjones123 Jun 22 '14 at 22:56
  • @dowjones123 the strings are not irrelevant at all. When you go to `yoursite.com/yourstring` it will server up the content generated by your view. What you name `yourstring` doest matter because it can be anything, its just a key to map to your view. – agconti Jun 22 '14 at 23:31