在django admin上传后提示文件下载

时间:2016-12-19 04:13:44

标签: python django file download django-admin

我有一个用户正在上传文件的django管理页面,数据在内存中读取,而不实际存储文件。

根据内容,在磁盘上生成一个新文件。在调用clean之前,save_model方法会发生这种情况.Below是生成输出文件的方法

def clean(self):
    obj = Parser()
    cleaned_data = super(MyMethodAdminForm, self).clean()
    input_data = self.request.FILES['file_name'].read().split('\n')
    base_file = settings.MEDIA_ROOT + "/uploads/" + cleaned_data.get('file_name').name

    # This is the output file, which needs to be downloaded
    output_filename = base_file.replace('.csv', '_output.csv')
    output_list = []

    # Read the file and prepare the output data
    # on the basis of the input data
    for line in input_data:
        data = line.split(",")
        if len(data) > 1:
            dt = obj.get_data()
            current_list = [data[0], data[1]]
        else:
            dt = obj.get_data()
            current_list = [data[0]]
        current_list.append(str(dt))
        output_list.append(current_list)

    # Prepare the file on the basis of the output data
    with open(output_filename, 'a') as outcsv:
        # configure writer to write standard csv file
        writer = csv.writer(outcsv, delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
        for item in output_list:
            if len(item) > 2:
                # Write item to outcsv
                writer.writerow([item[0], item[1], item[2]])
            else:
                writer.writerow([item[0], item[1]])
    return cleaned_data

现在,我的问题是我必须允许这个文件下载,但是因为,上传域是通过负载均衡器处理的,我真的无法提供链接(也不是一个首选的方式,老实说).Is有什么方法可以强制提示文件下载吗?

我从下面的两个问题得到了一些提示,但后来没有理解我需要把这些change header thing

修改

经过多一点调试后,我尝试按照帖子Redirect on admin Save

中的建议更新response_change
    class MyMethodAdmin(admin.ModelAdmin):
        form = MyMethodAdminForm

        def response_change(self, request, obj):
            import ipdb;
            ipdb.set_trace()
            # response = HttpResponse(content_type='text/csv')
            # response['Content-Disposition'] = 'attachment; filename="%s"' % form.cleaned_data['output_file_path'] (somehow access the file-path, its incorrect ryt now, i know

            super(MyMethodAdmin, self).response_change(request, obj)

但即使是pdb也没有被调用....所以没有帮助! :(

完整的课程:

class MyMethodAdminForm(forms.ModelForm):
    class Meta(object):
        model = MyMethod
        fields = ["file_name"]

    def clean(self):
        obj = Parser()
        cleaned_data = super(MyMethodAdminForm, self).clean()
        input_data = self.request.FILES['file_name'].read().split('\n')
        base_file = settings.MEDIA_ROOT + "/uploads/" + cleaned_data.get('file_name').name
        output_filename = base_file.replace('.csv', '_output.csv')
        output_list = []

        # Read the file and prepare the output data
        # on the basis of the input data
        for line in input_data:
            data = line.split(",")
            if len(data) > 1:
                dt = obj.get_data()
                current_list = [data[0], data[1]]
            else:
                dt = obj.get_data()
                current_list = [data[0]]
            current_list.append(str(dt))
            output_list.append(current_list)

        # Prepare the file on the basis of the output data
        with open(output_filename, 'a') as outcsv:
            # configure writer to write standard csv file
            writer = csv.writer(outcsv, delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
            for item in output_list:
                if len(item) > 2:
                    # Write item to outcsv
                    writer.writerow([item[0], item[1], item[2]])
                else:
                    writer.writerow([item[0], item[1]])
        return cleaned_data

1 个答案:

答案 0 :(得分:1)

无论您何时准备好向用户发送回复:

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
writer = csv.writer(response)
# now write to writer however you want to output your CSV

根据您调用视图的位置,您可能需要覆盖多种方法。原因是django支持不同类型的管理操作,包括changeadddelete which you can read about here。我不确定你使用的是哪一个,所以你可能要尝试两者。作为第一步,我会尝试覆盖response_changeresponse_add方法:

class MyMethodAdmin(admin.ModelAdmin):
    form = MyMethodAdminForm

    def return_csv(self):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="%s"' % filename
        writer = csv.writer(response)
        writer.writerow(['Django','Admin'])
        return response

    def response_change(self, request, obj):
        return self.return_csv()

    def response_add(self, request, obj):
        return self.return_csv()