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
--
You received this message because you are subscribed to the Google Groups "Django
developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-developers/8c839dc6-1ed5-6910-e9e2-c18cb9d90123%40nerdocs.at.