Search code examples
pythondjangopython-3.xurldjango-2.0

Django 2.0.7 how URL app_name works


I'm working on a project built with python 3.4.3 and django 2.0.7 and I'm stuck with URLs files logic. I still haven't figured this error out: "ImportError: No module named 'fields'.

Here's what I have:

urls.py

from django.urls import include, path
from django.contrib import admin
from bridge.core import views as core_views

urlpatterns = [
    path('', core_views.home),
    path('backoffice/fields/', include('fields.urls', namespace='backoffice')),
    path('admin/', admin.site.urls),
]

fields/urls.py

from django.urls import path
from . import views

app_name = 'fields'

urlpatterns = [
    path('', views.list_fields, name='list_fields'),
]

What does "app_name" is supposed to be filled with? How "app_name" works?

According to there files, when I submit "/backoffice/fields/" in the browser django should invoke "views.list_fields", shouldn't?

If any other information is required to help me with this issue, just let me know and I'll provide it as quickly as possible.

Thanks in advance


Solution

  • The app_name is used to reference your urls else where. You will also see referenced as namespacing. If you would have two different apps with the same url name, it wouldn't always pick the right one. So you namespace them and call them as such:

    {% url 'employee:name' %}
    {% url 'customer:name' %}
    

    You can use the names in more than just template tags, like reverse('employee:name') and such.

    The problem you are running into is that it doesn't know where to find your urls file. If your installed app is bridge.fields, try using include(bridge.fields.urls).

    To fully find your problem I would have to see you project folder structure as to where your main urls file is and where your fields.urls is. Remember that fields.urls really means a file named urls.py that is located in the folder named fields.