Django下载Excel文件返回对象名称而不是Excel文件

sh7euo9m  于 2023-05-23  发布在  Go
关注(0)|答案(2)|浏览(158)

我有一个网站,我们下载了一个xl文件,我有我的看法如下,而不是返回excel文件,其返回的文本文件与名称的对象内,我如何解决这个问题

views.py

def my_view(request):
 obj = model.objects.first()
    response = HttpResponse(file, content_type=' 
  application/vnd.ms-excel',
                                )
    return response

url.py

path('temo/fill',views.my_view,name = 'my-view')

models.py

class Model(BaseModel, SingletonModel):
    file = models.FileField(
        upload_to='',
        validators=[FileExtensionValidator([''])]
    )
    person_uploaded = models.ForeignKey(
        'somemodel',
        related_name='s',
        null=True,
        on_delete=models.SET_NULL,
        )

admin.py

@admin.register(tTemplate)
class TemplateAdmin(admin.ModelAdmin):
    list_display = ('file','person_uploaded',)
    readonly_fields = ('person_uploaded',)

    def save(self, request):
        if not self.id:
            self.person_uploaded = request.user
        super().save()
fzsnzjdm

fzsnzjdm1#

obj = Plate.objects.first() # this will return you object

在对象中有多个属性,你只需要像这样获取文件属性

@api_view(['GET',])
def my_view(request):
    obj = Plate.objects.first()
    response = HttpResponse(obj.file, content_type=' 
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
  application/vnd.ms-excel')
    return response
jxct1oxe

jxct1oxe2#

file = model.objects.first() # here you are returning the entire object

而不是一个文件,所以你显然会得到对象名,而不是一个xl文件。Mos重要的是你的对象里面的xl文件

相关问题