英文:
Django 4, how can I download a generated CSV file to browser while passing additional context to template?
问题
In views.py,我有一个视图,向用户显示发票信息,并有一个按钮用于创建批量支付文件。当点击按钮时,它会读取一个CSV模板文件,然后从数据库中更新数据创建一个新的CSV文件,然后直接下载到浏览器。
同时,我想返回一些上下文信息以生成有关处理状态的通知,返回错误消息等。似乎我需要通过多个HTTP请求/响应来实现这一点,但我不确定如何去做。
这是视图:
class InvoiceView(TemplateView):
    model = Cost
    template_name = "pipeline/invoices_list.html"
    costs = Cost.objects.all()
    def get_context_data(self, **kwargs):
        # 一些上下文数据
        return context
    def post(self, request, *args, **kwargs):
        if "batch-pay-csv" in request.POST:
            response, batch_payment_status = create_batch_payment_template(self.costs)
            context = self.get_context_data(**kwargs)
            context['batch_payment_status'] = batch_payment_status
            return response
以下是create_batch_payment_file()函数的缩写版本(在utils.py中):
def create_batch_payment_file(costs):
    '''
    从/static中的模板创建批量支付文件。
    '''
    invoices = costs.filter(invoice_status__in=["REC", "REC2"])
    processing_status = {}  # 格式:发票PO号 {状态(成功/错误),消息}
    response = HttpResponse(
        content_type='text/csv',
        headers={'Content-Disposition': 'attachment; filename="WISE_BATCH_PAYMENT.csv"'},
    )
    # 对于每个发票,将数据写入CSV
    context = processing_status
    return response, context
我开始认为在模板上生成一个下载按钮可能会更容易,而不是尝试自动下载到浏览器,但很乐意听听任何想法。
英文:
In views.py, I have a view that displays invoice information to the user, and a button for creating a batch payment file. When the button is clicked, a CSV template file is read, and a new CSV is created from that template with updated with data from the database, and then downloaded directly to the browser.
At the same time, I want to return some context to generate toast notifications about the processing status, return error messages, etc. It seems I need to do this via multiple HTTP requests/responses, and I'm not sure how to go about it.
Here's the view:
class InvoiceView(TemplateView):
    model = Cost
    template_name = "pipeline/invoices_list.html"
    costs = Cost.objects.all()
    def get_context_data(self, **kwargs):
        # some context data
        return context
    def post(self, request, *args, **kwargs):
        if "batch-pay-csv" in request.POST:
        
            response, batch_payment_status = create_batch_payment_template(self.costs)
            context = self.get_context_data(**kwargs)
            context['batch_payment_status'] = batch_payment_status
            return response
and an abbreviated version of the create_batch_payment_file() function (in utils.py):
def create_batch_payment_file(costs):
    '''
    Create a batch payment file from the template in /static. 
    
    '''
    invoices = costs.filter(invoice_status__in=["REC", "REC2"])
    processing_status = {} # format: invoice PO number {status (success/error), message}
    
    response = HttpResponse(
        content_type='text/csv',
        headers = {'Content-Disposition': 'attachment; filename = "WISE_BATCH_PAYMENT.csv"'},
    )
    # for invoice in invoices, write stuff to the CSV
    context = processing_status
    return response, context
I'm starting to think it would be easier to generate a download button on the template rather than try to automatically download it to the browser, but would love to hear any ideas.
答案1
得分: 1
搞清楚了!我将其从实用函数更改为views.py中的视图,以便我可以通过AJAX调用它,并将数据字典传递给HttpResponse对象的头文件。
def create_batch_payment_file(request):
    '''
    从/static中的模板创建批量付款文件。
    '''
    invoices = Cost.objects.filter(invoice_status__in=["REC", "REC2"])
    processing_status = {}  # 格式:发票PO号 {状态(成功/错误),消息}
    response = HttpResponse(
        content_type='text/csv',
        headers={'Content-Disposition': 'attachment; filename="WISE_BATCH_PAYMENT.csv"'},
    )
    # 对于每张发票,将内容写入CSV
    data = processing_status
    response['X-Processing-Status'] = json.dumps(data)
    return response
然后在客户端进行AJAX调用:
$("#batch-payment-create").on("submit", function(e) {
    e.preventDefault()
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    $.ajax({
        headers: { 'X-CSRFToken': csrftoken },
        type: "POST",
        url: "/myapp/myview/",
        data: "",
        success: function(data, testStatus, xhr) {
            var blob = new Blob([data]);
            var link = document.createElement('a');
            var processing_status = xhr.getResponseHeader('X-Processing-Status');
            console.log('Processing status:', processing_status);
            link.href = window.URL.createObjectURL(blob);
            link.download = "WISE_batch_payment.csv";
            link.click();
        }
    })
})
希望对其他人有所帮助!
英文:
Figured it out! Instead of using it as a utility function, I turned it into a view in views.py so I could call it with AJAX, and passed the data dict into the headers of the HttpResponse object.
def create_batch_payment_file(request):
    '''
    Create a batch payment file from the template in /static. 
    
    '''
    invoices = Cost.objects.filter(invoice_status__in=["REC", "REC2"])
    processing_status = {} # format: invoice PO number {status (success/error), message}
    
    response = HttpResponse(
        content_type='text/csv',
        headers = {'Content-Disposition': 'attachment; filename = "WISE_BATCH_PAYMENT.csv"'},
    )
    # for invoice in invoices, write stuff to the CSV
    data = processing_status
    response['X-Processing-Status'] = json.dumps(data)
    return response
Then on the client side, made an AJAX call:
$("#batch-payment-create").on("submit", function(e) {
        e.preventDefault()
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        $.ajax({
            headers: { 'X-CSRFToken': csrftoken },
            type: "POST",
            url: "/myapp/myview/",
            data: "",
            success: function(data, testStatus, xhr) {
                var blob = new Blob([data]);
                var link = document.createElement('a');
                var processing_status = xhr.getResponseHeader('X-Processing-Status');
                console.log('Processing status:', processing_status);
                link.href = window.URL.createObjectURL(blob);
                link.download = "WISE_batch_payment.csv";
                link.click();
            }
        })
    })
Hopefully this helps someone else!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论