Reputation: 27956
I just started up with django.
Following this tutorial, I ended up with the following urls.py
:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
This links to polls.urls.py
which has its own router.
The part I don't like is the string literal 'polls.urls' which is, well... a string literal.
I would like to somehow reference the file directly using some of python's power, and have AT LEAST my IDE protect me.
What happens if I want to move that polls.urls.py
file, or rename it, or rename polls? Should I trust my IDE to catch a reference from a string literal?
This is almost like doing this monstrosity, and is very hard for me to accept as the best practice.
It just seems odd to me.
Is there a way to use something less prone to errors than string literals in django's routers?
Upvotes: 1
Views: 146
Reputation: 15738
I don't see problems with using string literals as URLconf is loaded prior to starting of server (runserver)
If there is a problem you would get ModuleNotFound error
From source of include() :
if isinstance(urlconf_module, six.string_types): urlconf_module = import_module(urlconf_module)
You would see good amount of import_module usage through Django framework and string literals.
Your IDE would know if there is unresolved reference (Pycharm does)
Upvotes: 1
Reputation:
So from what I understand or what I know there are two ways of url mapping using the
path' or
url`
for path method you bound to do what you did that is:
from django.urls import path, include
but you are to also import your views.py
For second method your are to:
from django.conf.urls import url
then your are to import your views there as:
from .views import home_page
home_page being a function or class in your views.py
Example of mapping
url(r'^home/$', home_page),
so no need to actually to actually create urls.py if you use this method
Upvotes: 0