2007-04-09 21:11:39 +08:00
|
|
|
from django.template import loader, RequestContext
|
2008-12-08 12:53:34 +08:00
|
|
|
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
|
2005-11-16 00:55:26 +08:00
|
|
|
|
2007-09-15 19:12:54 +08:00
|
|
|
def direct_to_template(request, template, extra_context=None, mimetype=None, **kwargs):
|
2005-11-16 01:19:33 +08:00
|
|
|
"""
|
2006-01-04 07:57:14 +08:00
|
|
|
Render a given template with any extra URL parameters in the context as
|
2005-11-16 01:19:33 +08:00
|
|
|
``{{ params }}``.
|
|
|
|
"""
|
2007-09-15 19:12:54 +08:00
|
|
|
if extra_context is None: extra_context = {}
|
2006-10-30 22:30:43 +08:00
|
|
|
dictionary = {'params': kwargs}
|
|
|
|
for key, value in extra_context.items():
|
|
|
|
if callable(value):
|
|
|
|
dictionary[key] = value()
|
|
|
|
else:
|
|
|
|
dictionary[key] = value
|
2007-04-09 21:11:39 +08:00
|
|
|
c = RequestContext(request, dictionary)
|
|
|
|
t = loader.get_template(template)
|
2007-06-22 15:15:04 +08:00
|
|
|
return HttpResponse(t.render(c), mimetype=mimetype)
|
2006-01-04 07:57:14 +08:00
|
|
|
|
2008-12-08 12:53:34 +08:00
|
|
|
def redirect_to(request, url, permanent=True, **kwargs):
|
2005-11-16 01:19:33 +08:00
|
|
|
"""
|
2006-01-04 07:57:14 +08:00
|
|
|
Redirect to a given URL.
|
|
|
|
|
|
|
|
The given url may contain dict-style string formatting, which will be
|
2005-11-16 01:19:33 +08:00
|
|
|
interpolated against the params in the URL. For example, to redirect from
|
2006-01-04 07:57:14 +08:00
|
|
|
``/foo/<id>/`` to ``/bar/<id>/``, you could use the following URLconf::
|
2005-11-16 01:19:33 +08:00
|
|
|
|
|
|
|
urlpatterns = patterns('',
|
2006-10-30 21:49:45 +08:00
|
|
|
('^foo/(?P<id>\d+)/$', 'django.views.generic.simple.redirect_to', {'url' : '/bar/%(id)s/'}),
|
2005-11-16 01:19:33 +08:00
|
|
|
)
|
2006-01-04 07:57:14 +08:00
|
|
|
|
2005-11-16 01:19:33 +08:00
|
|
|
If the given url is ``None``, a HttpResponseGone (410) will be issued.
|
2008-12-08 12:53:34 +08:00
|
|
|
|
|
|
|
If the ``permanent`` argument is False, then the response will have a 302
|
|
|
|
HTTP status code. Otherwise, the status code will be 301.
|
2005-11-16 01:19:33 +08:00
|
|
|
"""
|
|
|
|
if url is not None:
|
2008-12-08 12:53:34 +08:00
|
|
|
klass = permanent and HttpResponsePermanentRedirect or HttpResponseRedirect
|
|
|
|
return klass(url % kwargs)
|
2005-11-16 01:19:33 +08:00
|
|
|
else:
|
2006-01-04 07:57:14 +08:00
|
|
|
return HttpResponseGone()
|