I am from the Java Hibernate and Symfony2 background where I used to write the routing within the controller on the top of function like this:
/**
* @Route("/blog")
*/
class PostController extends Controller
{
I know its not available in Django but is there any way I can code some decorator etc. so that I can mention the URL like this:
@URL("/mytest")
class myView():
pass
While it would be very undjangonic , you could try something like this:
project/
decorators.py
views.py
urls.py
# decorators.py
from django.conf import settings
from django.utils.importlib import import_module
from django.conf.urls.defaults import patterns, url
def URL(path):
path = r'^%s$' % path[1:] # Add delimiters and remove opening slash
def decorator(view):
urls = import_module(settings.ROOT_URLCONF)
urls.urlpatterns += patterns('', url(path, view))
return view
return decorator
# views.py
from .decorators import URL
@URL('/')
def home(request):
# your view
@URL('/products')
def products(request):
# your view
# urls.py
from django.conf.urls import patterns
from . import views # import the modules with your views
urlpatterns = patterns('',) # create an empty url dispatcher to append to
And make sure every file containing this decorator is imported before processing urls (eg by importing them in the urls file).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.