Hi devs,
I often come across the problem that I want to have a field take the autofocus in Django.
Especially when dealing with high abstraction when using ModelForms, this is barely possible using templates, so the only way is to create a ModelForm subclass and tell it to put the autofocus into that field.
This is very cumbersome, as the view itself IMHO is the better place to decide where the focus should be - especially when using GenericViews. This is very convenient.
After trying a few StackExchange solutions, I wrote a simple Mixin that can be applied to a GenericView:
class PersonUpdateView(UpdateView): model = Person fields = ["first_name", "last_name"] autofocus = "first_name"
The code is simple:
class AutoFocusMixin: """Put the 'autofocus' attribute to a given field""" autofocus = None def get_form(self, form_class=None): form = super().get_form(form_class) if self.autofocus in form.fields: form.fields[self.autofocus].widget.attrs.update({"autofocus": True}) return form
Is this worth including in Django core?
Christian
-- Dr. Christian González https://nerdocs.at