0

我认为我没有看到任何说你不允许这样做(或者你是)的东西,但是你有什么理由不应该这样做吗?它似乎工作正常。

def get_page(request, topic_slug = 'home', tag_slug = None, form = None):

    #...

    if form is None:
        form = CommentForm()
    d = {'topic':topic, 'topics':topics, 'tags':tags, 'comments':comments, 'form':form}

    d.update(csrf(request))
    return render_to_response('page.html', d)

def save_comment(request, topic_slug):

    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            #...save
        else:
            kwargs = {'topic_slug':topic_slug}
            kwargs['form'] =form
            return get_page(request, **kwargs) #<-------------- this

    return HttpResponseRedirect(reverse('get_page', kwargs = {'topic_slug':topic_slug}))
4

1 回答 1

1

render_to_response只是一个捷径。调用它的结果仍然HttpResponse是实例。

作为证明,请参阅render_to_response()Django 源代码中的声明:

def render_to_response(*args, **kwargs):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
    return HttpResponse(loader.render_to_string(*args, **kwargs),
        **httpresponse_kwargs)

很不言自明。

通过这样写:

return get_page(request, **kwargs)

你实际上做了类似的事情:

return render_to_response(request, kwargs)

(但参数略有改变kwargs)。

于 2012-06-22T22:31:18.427 回答