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"),
)
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.
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")),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With