Can I have two urls.py with different names? - django

In Django, is it possible to have two different files with url patterns, neither of which is called urls.py ? Or does Django rely on there being only one set of url patterns per Django app, and that it must be called urls.py ?
I'm using Django CMS and I want to split an app across two apphooks and two menus. So I've tried splitting urls.py into pub_urls.py and train_urls.py but I appear to have broken things by doing that, despite the cms_app.py naming the correct urls - eg:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
from resources.menu import TrainingMenu, PublicationMenu
class PublicationApp(CMSApp):
name = _("Publication App") # give your app a name, this is required
urls = ["resources.pub_urls"] # link your app to url configuration(s)
menus = [PublicationMenu]
class TrainingApp(CMSApp):
name = _("Training App") # give your app a name, this is required
urls = ["resources.train_urls"] # link your app to url configuration(s)
menus = [TrainingMenu]
apphook_pool.register(PublicationApp) # register your app
apphook_pool.register(TrainingApp) # register your app
Is something like this possible? Or do I have to split this into two different apps?

There is nothing to stop your urls.py simply acting as a way of including multiple other urls files:
urls.py:
from django.conf.urls.defaults import patterns, include
urlpatterns = urlpatterns + patterns('',
(r'^', include('pub_urls')),
(r'^', include('train_urls')))
pub_urls.py:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
(r'^$', 'homeview'),
(r'^stuff/$', 'stuffview')
)
etc.
ROOT_URLCONF in your settings file points to the root url file.

Django doesn't care what your urlpatterns file is called. The default base urlconf is by convention called urls.py, but in fact that's just a setting and can be overridden. After that, you need to explicitly include urlconfs by module name, so again it makes no difference what they're called.
I'm not familiar with Django-CMS and I don't know what it's doing in its CMSApp class, but I suspect you're going to have to dig into that to see what's going on.

It is configurable using ROOT_URLCONF setting.
From django docs
ROOT_URLCONF
A string representing the full Python import path to your root URLconf.
For example: "mydjangoapps.urls". Can be overridden on a per-request basis
by setting the attribute urlconf on the incoming HttpRequest object. See How
Django processes a request for details.
You can also write/get a middleware which can set it appropriately depending upon the host or other parameters in the request.

Related

Setting up simple Django ViewSet APIs from multiple apps

I’m still learning django and assume this may be easy for some. I’m trying to figure out the best way of simply setting up the API URLs (and so that they all display in the api root and can actually be used in the project - in my case at /api/). I’m using django rest framework, and can’t seem to set up more than one API - it works for just one, but the problem occurs when trying to set up another.
So I have an app called pages and accounts (and core - the default where the main urls.py is). I’ve created another urls.py inside the pages app and another inside the accounts app.
accounts/urls.py:
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r"accounts", views.AccountsViewSet, basename="accounts")
urlpatterns = router.urls
pages/urls.py:
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r"pages", views.PagesViewSet, basename="pages")
urlpatterns = router.urls
And the core urls.py:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from rest_framework.routers import DefaultRouter
router = routers.DefaultRouter()
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include("pages.urls")), # works but root only shows pages API
# path("api/", include("pages.urls", "accounts.urls")), # fails with error: “django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.”
# path("api/", include(router.urls)), # no error but root api is empty
]
I would assume, possibly incorrectly, that just router.urls should include all the apis when visiting the root. The root apis currently looks like this when using just include("pages.urls”):
{
"pages": "http://localhost:8000/api/pages/"
}
How can I get it to correctly show all apis? The only way I could do it was by putting router.register(r"accounts", views.AccountsViewSet, basename="accounts”) in the pages urls.py, which is very undesirable, especially as the project grows even further.
Thank you
Have you tried to use:
path("api/pages/", include("pages.urls")),
path("api/accounts/", include("accounts.urls")),
In your urls.py?
Possibly that would mean your routes would be:
{
"pages": "http://localhost:8000/api/pages/pages/"
"accounts": "http://localhost:8000/api/accounts/accounts/"
}
In that case you could try to use
router.register("", views.AccountsViewSet, basename="accounts")
in accounts/urls.py.
And similarly,
router.register("", views.AccountsViewSet, basename="pages")
in pages/urls.py.
That way, you might achieve to have routes like:
{
"pages": "http://localhost:8000/api/pages/"
"accounts": "http://localhost:8000/api/accounts/"
}
if that is what you want.

What is the purpose of app_name in urls.py in Django?

When include()ing urlconf from the Django app to the project's urls.py, some kind of app's name (or namespace) should be specified as:
app_namespace in include((pattern_list, app_namespace), namespace=None) in main urls.py
or
app_name variable in app's urls.py.
Since, I guess, Django 2, the second method is the preferred one Although I copy-pasted first function signature from Django 3 documentation. But that's not the main point.
My current understanding of namespace parameter of include() is that it's what I use when using reverse().
What is the purpose of app_name in app's urls.py or app_namespace in main urls.py?
Are these exactly the same thing?
How is it used by Django?
Existing questions (and answers) I've found here explain HOW I should specify it rather than WHY.
In this answer, I am taking the DRF package and its URL patterns. If you want to try any of the snippets mentioned in this answer, you must install (pip install djangorestframework) and add rest_framework to INSTALLED_APPS list.
The application namespace can be set in two ways, [Ref: Django doc]
in urls.py using app_name varibale.
You can see that DRF has set the app_name in urls.py. Django will use this app_name as the application namespace only if we are included the patterns with module reference.
That is, include(module, namespace=None)
Example:
urlpatterns = [
path('drf-auth/bare/', include('rest_framework.urls')),
]
in include((pattern_list, app_namespace), namespace=None) function using app_namespace parameter.
In this method, you can set an additional app_namespace for the application, if you want.
Most importantly, we are passing a pattern_list instead of module
Example:
from rest_framework.urls import urlpatterns as drf_urlpatterns
urlpatterns = [
path('drf-auth/foo/', include((drf_urlpatterns, 'foo-app-namespace'))),
]
Complete Example
from django.urls import path, include, reverse
from rest_framework.urls import urlpatterns as drf_urlpatterns
urlpatterns = [
path('drf-auth/bare/', include('rest_framework.urls')),
path('drf-auth/foo/', include((drf_urlpatterns, 'foo-app-namespace'))),
path('drf-auth/bar/', include((drf_urlpatterns, 'bar-app-namespace'))),
]
print(reverse('rest_framework:login'))
print(reverse('foo-app-namespace:login'))
print(reverse('bar-app-namespace:login'))
#results
/drf-auth/bare/login/
/drf-auth/foo/login/
/drf-auth/bar/login/
What is the purpose of app_name in app's urls.py or app_namespace in main urls.py?
Both are used to set the application namespace. The app_name can be used as a default application namespace, if defined in the urls.py.
Are these exactly the same thing?
No.
How is it used by Django?
The application namespace and instance namespace are used to retrieve the URL path. In Django, whenever the reverse(...) function get executed, Django looking for an application namespace first, than any other. You can read more about how Django resolve the URL here, Reversing namespaced URLs
app_name in app/urls.py and app_namespace in include((pattern_list, app_namespace), namespace=None) in main urls.py are the same referenced as application namespace which describes the name of the application that is being deployed.
One can either pass the whole app/urls.py or a string reference of app/urls.py with app_name to include()
# blog.urls
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index(), name='index'),
path('<int:pk>/', views.post(), name='detail'),
]
# project urls
from django.urls import include, path
urlpatterns = [
path('', include('blog.urls')),
]
OR
a tuple of url patterns and app_namespace to include()
# project urls
from django.urls import include, path
from blog.urls import urlpatterns as blogpatterns
urlpatterns = [
path('', include((blogpatterns, 'blog'))),
]
app_namespace will be the default application namespace when provided in include(). If app_namespace is not provided, then it will look for app_name in blog/urls.py and that will be the default namespace.
Without the app namespace, urls are added to global namespace which may lead to url conficts.
URL namespaces and included URLconfs | Term application namespace | include()
For years, we've (at Django) been skirting around the (confusing) distinction between an application name(space) and an instance namespace. We've always just recommended using instance namespace, as per the examples in the docs.
What's happened with Django 2.0 (and onwards) is they've made it so you can't use an instance namespace without also (first) using an application name. Instead of fixing code, we should update our examples to the correct usage.
The include needs to go like this:
urlpatterns += [ url('API/', include((router.urls, 'pikachu')) ]
The tendency is to include the second namespace='pikachu' instance namespace parameter as well, but that's not needed — it defaults to None and is set to 'pikachu' in this case automatically.
Generally, users want to be including an app-level URLs module explicitly setting the app_name attribute there, rather than including the router by hand.
From https://docs.djangoproject.com/en/3.0/topics/http/urls/#introduction :
URL namespaces allow you to uniquely reverse named URL patterns even
if different applications use the same URL names. It’s a good practice
for third-party apps to always use namespaced URLs (as we did in the
tutorial). Similarly, it also allows you to reverse URLs if multiple
instances of an application are deployed. In other words, since
multiple instances of a single application will share named URLs,
namespaces provide a way to tell these named URLs apart.

Rewrite URL to exclude Django application name

on my live server, I am trying to remove/rewrite the need to include the application name in the URL, as without it I get a 404. For example:
http://www.example.com/myapp/page.html
to
http://www.example.com/page.html
This is especially tricky since i don't want this to affect the django admin URL which excludes the app name.
This is on Apache Server on Ubuntu on a shared host (A2).
You're root urls.py most likely looks something like this:
"""
Definition of urls for api.
"""
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^myapp/', include('myapp.urls'))
]
When you just replace r'^myapp/' with r'^' the app will be automatically tried, when there is nothing else before that fits (so it's best to put it to the end of the list)

django urls: "Django tried these URL patterns"

I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface

Should every django app within a project have it's own urls.py?

I am working on a django project which will contain several apps. Each app will have their own set of models and views.
Should each app also define their own url's with a urls.py or maybe a function. What is the best practice for defining urls of apps within a django project, and integrating these urls with the main urls.py (root url conf) ?
It depends. If you're dealing with a tiny website with one app, you can keep all the expressions in the same urls.py.
However, when you're dealing with a more complicated site with truly separate apps, I prefer the following structure:
myapp
admin.py
forms.py
models.py
urls.py
views.py
manage.py
settings.py
urls.py
Don't forget each folder needs it's own __ init__.py
# urls.py
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Notice the expression does not end in $,
# that happens at the myapp/url.py level
(r'^myapp/', include('myproject.myapp.urls')),
)
# myapp/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('myproject.myapp.views',
(r'^$', 'default_view',
(r'^something/$', 'something_view',
)
You also may want to look at Class-based Generic Views
If your app is going to display anything to the user with its own url pattern, it should probably have its own urls.py file. So in your base urls file, you'd have something in your urlpatterns like url(r'', include('path.to.app.urls')). Then your app's urls.py file would have a pattern like url(r'^$', 'path.to.app.views.view').
If the app is mostly self-contained and having its own place in the URL hierarchy makes sense, then it should have its own urls.py. But even if it does exist, it's still only a guideline to the project developer unless include() is used to graft it into the project URLconf.