pdf生成后重定向

时间:2013-07-19 23:14:35

标签: javascript python django

我在提交表单后生成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

3 个答案:

答案 0 :(得分: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" %}">

答案 1 :(得分: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')

只是为了给你一个想法

答案 2 :(得分:2)

通过此snippet,您可以创建自定义装饰器

 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