Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputing text from urls.py in Django

Is there any way I can simply output text (not HTML) from urls.py instead of calling a function (in views.py or otherwise)?

urlpatterns = patterns('',
    url(r'^$', "Hello World"),
)
like image 547
Robert Johnstone Avatar asked Dec 11 '22 22:12

Robert Johnstone


2 Answers

No, definitly. A url must map a pattern to a callable, and this callable must accept a HttpRequest as first argument and return a HttpResponse.

The closer thing you could do would be to map the pattern to a lambda (anonymous function), ie:

from django.http import HttpResponse

urlpatterns = patterns('',
    url(r'^$', lambda request: HttpResponse("Hello World", content_type="text/plain")),
)

but I would definitly not consider this as good practice.

like image 71
bruno desthuilliers Avatar answered Dec 28 '22 08:12

bruno desthuilliers


The url function takes a callable, so something like

rlpatterns = patterns('',
    url(r'^$', lambda req:HttpResponse("Hello World")),
)

would work. There is really nothing gained in doing so though, except making your urls.py harder to read.

First, you should consider whether you really want this. If there is a need for it (I have never had a need to do this, and I've written a fair share of Django apps during the years), you could wrap this into something more compact, e.g.

Note that passing a string directly to url treats it as a method name.

def static_text(s):
    return lambda req:HttpResponse(s)

rlpatterns = patterns('',
    url(r'^$', static_text("Hello World")),
)
like image 45
Krumelur Avatar answered Dec 28 '22 07:12

Krumelur