render和render_to_response之间的区别是是否传入request到模板中
def render_to_response(template_name, context=None, content_type=None, status=None, using=None):
content = loader.render_to_string(template_name, context, using=using)
return HttpResponse(content, content_type, status)
def render(request, template_name, context=None, content_type=None, status=None, using=None):
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
更好用的是提供的通用类RedirectView
def redirect(to, *args, **kwargs):
if kwargs.pop('permanent', False):
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
return redirect_class(resolve_url(to, *args, **kwargs))
这个解析的使用场景是?
def resolve_url(to, *args, **kwargs):
if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
if isinstance(to, Promise):
to = force_text(to)
if isinstance(to, six.string_types):
if to.startswith(('./', '../')):
return to
try:
return reverse(to, args=args, kwargs=kwargs)
except NoReverseMatch:
if callable(to):
raise
if '/' not in to and '.' not in to:
raise
return to