2

我在提交表单后生成 pdf,我想重定向到“已生成 pdf”或使用表单重新加载页面。我不知道该怎么做,我想它可以用 javascript/jquery 来完成,但我没有找到办法。

这是生成 pdf 的视图:

def myview(response):
    resp = HttpResponse(content_type='application/pdf')
    result = generate_pdf('my_template.html', file_object=resp)
    return result
4

3 回答 3

3

您不能从创建 PDF 文件的同一视图重定向,一个选项是先发送成功页面,然后开始下载。

您的成功观:

def pdf_success(request):
    # View stuff
    return render_to_response('pdf.html', {}, context_instance=ctx)

您需要将其添加到您的pdf.html模板中:

<meta http-equiv="REFRESH" content="0;url={% url "myview" %}">
于 2013-07-20T00:04:28.777 回答
2

首先创建成功视图:

def pdf_success(request):
    return render_to_response('pdf_success.html', {},
                              context_instance=RequestContext(request))

然后在成功后做一个重定向:

def myview(response):
    resp = HttpResponse(content_type='application/pdf')
    result = generate_pdf('my_template.html', file_object=resp)
    if result:
        return HttpResponseRedirect('/url/to/success/view')

只是给你的想法

于 2013-07-19T23:26:37.747 回答
2

从此片段中,您可以创建自定义装饰器

 from functools import wraps
 from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect

def redirect(url):
    """
    Executes a HTTP 302 redirect after the view finishes processing. If a value is 
    returned, it is ignored. Allows for the view url to be callable so the
    reverse() lookup can be used.

    @redirect('http://www.google.com/')
    def goto_google(request):
        pass

    @redirect(lambda: reverse('some_viewname'))
    def do_redirect(request):
        ...

    """
    def outer(f):
        @wraps(f)
        def inner(request, *args, **kwargs):
            f(request, *args, **kwargs)
            return HttpResponseRedirect(url if not callable(url) else url())
        return inner
    return outer




def permanent_redirect(url):
    """
    Executes a HTTP 301 (permanent) redirect after the view finishes processing. If a
    value is returned, it is ignored. Allows for the view url to be callable so the
    reverse() lookup can be used.

    @permanent_redirect('/another-url/')
    def redirect_view(request):
        ...

    @redirect(lambda: reverse('some_viewname'))
    def do_redirect(request):
        ...

    """
    def outer(f):
        @wraps(f)
        def inner(request, *args, **kwargs):
            f(request, *args, **kwargs)
            return HttpResponsePermanentRedirect(url if not callable(url) else url())
        return inner
    return outer

您可以通过以下方式使用其中任何一种:

@redirect('http://stackoverflow.com')
def myview(response):
    resp = HttpResponse(content_type='application/pdf')
    result = generate_pdf('my_template.html', file_object=resp)
    return result

或者:

    @permanent_redirect('http://stackoverflow.com')
    def myview(response):
        resp = HttpResponse(content_type='application/pdf')
        result = generate_pdf('my_template.html', file_object=resp)
        return result
于 2013-07-19T23:28:21.983 回答