DownloadButton demo#

You can generate buttons that download files with ease.

It does not matter if the file is a real file from disk, or generated on the fly during the request.

Just call amethod from the client, and respond to that method using Django's FileResponse. Tetra will do the rest.

# download_button/__init__.py
import io

from django.http import FileResponse

from tetra import Component, public


class DownloadButton(Component):

    filename: str = "foo.txt"

    def load(self, filename: str = "foo.txt", *args, **kwargs):
        self.filename = filename

    @public
    def download_file(self):
        return FileResponse(
            io.BytesIO(b"Hello, World!"),
            content_type="text/plain",
            filename=self.filename,
            as_attachment=True,
        )

<!-- download_button.html -->
{% load i18n %}
<div>
  <button
      id="download_button"
      class="btn btn-primary"
      @click="download_file()">
    {% translate "Download file" %}
  </button>
</div>

Demo