在django中渲染模板后下载文件

时间:2017-04-13 10:58:24

标签: django django-templates django-views

我正在尝试从视图重定向后同时下载csv文件并渲染模板,但它只下载文件,不会渲染模板。 我认为它可以由中间件处理,但找到一个更容易的解决方案。

class ProductUploadView(FormView):
    template_name ='upload.html'
    form_class = csvform
    success_url = 'response/'
    failed_rows = []

    def post(self,request,*args,**kwargs):
        form  = self.form_class(request.POST,request.FILES)
        file = request.FILES['csvfile']
        csvfile = csv.reader(utf_8_encoder(file), dialect='excel', delimiter=',')
        csvfile.next()

        for row in csvfile:
            if row[1] in ['PRES','GEN','GEN'] and row[2] in ['CAPS','TAB','SYP','GEL','SUSP','INJ']:
                try:
                    p, created = Product.objects.get_or_create(brand_name=row[0], category=row[1], defaults={'form': row[2], 'mrp': row[3], 'ptr': row[4]})
                except ValidationError:
                    self.failed_rows.append(row)
                    pass
            else:
                self.failed_rows.append(row)
        return HttpResponseRedirect(self.success_url)


class UploadedView(ProductUploadView):
    template_name = 'response.html'
    rows = ProductUploadView.failed_rows

    def download_view(self,request):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
        writer = csv.writer(response)
        writer.writerows(self.rows)
        return response

    def get(self,request):
        response = TemplateResponse(request,self.template_name,{'num':len(self.rows),'failed_rows':self.rows})
        response.add_post_render_callback(download_view)
        return response

0 个答案:

没有答案