Robert Johnstone
Robert Johnstone

Reputation: 5371

Can you have a view function in your URLS.py file

This is just an academic question. I don't intend this for production but can you put a view function above your url routes in your url.py file? Something like:

from django.conf.urls import patterns, include, url
from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello World!")

urlpatterns = patterns('',
    url(r'^$', 'hello_world'),
)

Upvotes: 0

Views: 332

Answers (1)

Alasdair
Alasdair

Reputation: 308849

Yes, the view can be in your urls file, although I wouldn't recommend it as a way to organise your Django project.

However, in the url() you should use the view itself, not a string.

urlpatterns = [
    url(r'^$', hello_world),
]

Providing string view arguments e.g. 'myproject.urls.hello_world' is deprecated in Django 1.8 and removed in Django 1.10.

The view argument can be any callable, you can even use a lambda function (again, I wouldn't recommend it).

urlpatterns = [
    url(r'^$', lambda req: HttpResponse("Hello World"),
]

Upvotes: 3

Related Questions