'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte django

so i have variable contains with bytes and i want to write it to text and download it. but to use write, it's must in bytes. so how to make from bytes to string?

now i got error like this. i tried to decode it, but it cannot works.

'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte

here's the code:

def create_file(f):
    print(f) #f = b'\x8b\x86pJ'
    response = HttpResponse(content_type="text/plain")
    response['Content-Disposition'] = 'attachment; filename=file.txt'

    filename = f
    print(filename) # filename = b'\x8b\x86pJ'
    download = filename.decode('utf-8')
    response.write(download)
    print(response)

    return response

You can try

def create_file(f):
    print(f) #f = b'\x8b\x86pJ'
    response = HttpResponse(content_type="text/plain")
    response['Content-Disposition'] = 'attachment; filename=file.txt'

    filename = f
    print(filename) # filename = b'\x8b\x86pJ'
    download = filename.decode('latin-1')
    response.write(download)
    print(response)

    return response
Back to Top