Jan Vorcak
Jan Vorcak

Reputation: 19989

Refer to my (reusable) app's url namespace in Django

I want to write a reusable Django application.

I tell my users to add the following to their urls.py

path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),

And in my urls.py I want to have a view login_callback.

Now in my view, I need to get a value of slack_integration:login_callback.

I can trust the user that he/she will integrate it with slack_integration prefix and use it. But is this the best practise? Can I somehow get the name of the namespace for the app if user chooses a different name for it?

Thanks a lot!

Upvotes: 1

Views: 293

Answers (1)

FlipperPA
FlipperPA

Reputation: 14311

Using namespace= within urls.py files is no longer supported, as it moves something specific to the Django app outside of the Python package that is the Django app.

The best practice now is to define the app_name within the urls.py file inside the Django app.

The old way: DON'T DO THIS (pre-Django 2.0)

the root urls.py

path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),

The new way: DO THIS! (Django 2.0+)

the root urls.py

from django.urls import path, include

urlpatterns = [
    path('slack/', include(('slack_integration.urls', 'slack_integration')),
]

slack_integration/urls.py

from django.urls import path

app_name = "slack_integrations"

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
]

As you can see, this keeps the namespace for the patterns within the app itself, along with the templates most likely to use it. The days of extra instructions on how to include an app are over! Good luck.

Upvotes: 1

Related Questions