Search code examples
pythondjangodjango-modelsdjango-viewsdjango-urls

Django downloading excel file return object name instead of excel file


I have a website where we download a xl file i have my view as below instead of returning the excel file its returning the text file with name of the object inside it how do i solve this

views.py:

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

urls.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()

Solution

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

    in objects there are multiple attributes there you've to get only your file attribute like this

    @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