adamchainz / django-htmx

Extensions for using Django with htmx.
https://django-htmx.readthedocs.io/
MIT License
1.57k stars 140 forks source link

Add cbv and fbv helpers #117

Closed Tobi-De closed 3 years ago

Tobi-De commented 3 years ago

In a project I'm working on, I created two simple helpers I use in combination with this package, so I was thinking about making a pr to add these as simple utils. Do you guys think it will be useful ?

from functools import wraps

from django.shortcuts import render

class HtmxView:
    success_url = "."

    @property
    def htmx_template(self) -> str:
        raise NotImplemented

    @property
    def htmx_partial(self) -> str:
        raise NotImplemented

    @property
    def template_name(self) -> str:
        return self.htmx_partial if self.request.htmx else self.htmx_template # noqa

def htmx_view(htmx_template: str, htmx_partial: str):
    def inner(view):
        @wraps(view)
        def func(request, *args, **kwargs):
            context: dict = view(request, *args, **kwargs)
            template = htmx_partial if request.htmx else htmx_template
            return render(request, template, context)

        return func

    return inner

# Examples

class ContactView(HtmxView, FormView):
    form_class = ContactForm
    htmx_partial = "partials/contact_form.html"
    htmx_template = "pages/contact.html"

@htmx_view(htmx_template="pages/contact.html", htmx_partial="partials/contact_form.html")
def contact(request):
    return {"form": ContactForm()}
adamchainz commented 3 years ago

Thansk but I only want this library to provide the atomic tools for building your own helpers.

Tobi-De commented 3 years ago

Thansk but I only want this library to provide the atomic tools for building your own helpers.

Ok got it, no problem