Utilities to make Django function-based views cleaner, more efficient, and better tasting. 💥
📖 Complete documentation: https://django-fbv.adamghill.com
The Django community has two ways to write views: class-based and function-based. One benefit of function-based views is that the HttpRequest input and the HttpResponse output is explicit, instead of being hidden within a hierarchy of classes and mixins.
django-fbv reduces the boilerplate code required when using function-based views. It also leverages locality of behavior -- the name of the template is clearly associated to the view, instead of being part of the return statement.
Instead of this:
# sample_app/views.py
from django.shortcuts import render
def regular_function_based_view(request):
return render(request, "template_name.html", {"data": 123})You can write this:
# sample_app/views.py
from fbv.decorators import render_html
@render_html("template_name.html")
def django_fbv_view(request):
return {"data": 123}If you want a more detailed critique of class-based views, I recommend reading https://spookylukey.github.io/django-views-the-right-way/.
pip install django-fbv OR uv add django-fbv
The decorators and views can be used by just importing them. The middleware needs to be installed.
fbv.decorators.render_html: renders a view as HTML with the specified templatefbv.decorators.render_view: renders a view as a content type with the specified templatefbv.decorators.render_json: renders dictionaries, DjangoModel, or DjangoQuerySetas aJSONresponse
fbv.views.html_view: directly render a template fromurls.pyfbv.views.redirect_view: redirect to a pattern name fromurls.pyfbv.views.file: serve a filefbv.views.favicon_file: serve an image file as the favicon.icofbv.views.favicon_emoji: serve an emoji as the favicon.ico
fbv.middleware.RequestMethodMiddleware: adds a boolean property to therequestfor the current request's HTTP method
- The
render_viewdecorator was forked fromrender_toin https://github.com/skorokithakis/django-annoying. - The
file,favicon_fileandfavicon_emojicode is from https://adamj.eu/tech/2022/01/18/how-to-add-a-favicon-to-your-django-site/.