Skip to content

Instantly share code, notes, and snippets.

@geoffrey-eisenbarth
Last active January 5, 2025 16:56
Show Gist options
  • Save geoffrey-eisenbarth/1f7fec831b69a9b72aec7259d9902efd to your computer and use it in GitHub Desktop.
Save geoffrey-eisenbarth/1f7fec831b69a9b72aec7259d9902efd to your computer and use it in GitHub Desktop.
Django Form Attributes Mixin
from django.utils.translation import gettext_lazy as _
class FormMixin:
"""Adds extra classes and attributes to HTML widgets."""
# This value will change with your CSS framework.
# https://missing.style/
error_css_class = 'bad color'
PLACEHOLDERS = {
'username': _('Email Address'),
'email': _('Email Address'),
'password': _('Password'),
'password1': _('Create Password'),
'password2': _('Confirm Password'),
'old_password': _('Old Password'),
'new_password1': _('New Password'),
'new_password2': _('Confirm New Password'),
'zip_code': _('ZIP Code'),
'card_exp_date': _('Expiration Date (MM/YY)'),
'subject': _('Subject'),
'message': _('Message'),
'first_name': _('First Name'),
'last_name': _('Last Name'),
'company': _('Company'),
'job_title': _('Job Title'),
'county': _('County of Residence or Work'),
}
AUTOCOMPLETES = {
'username': 'email',
'email': 'email',
'password': 'current-password',
'password1': 'new-password',
'password2': 'new-password',
'new_password1': 'new-password',
'new_password2': 'new-password',
'zip_code': 'postal-code',
'card_exp_date': 'cc-exp',
'first_name': 'given-name',
'last_name': 'family-name',
'company': 'organization',
'job_title': 'organization-title',
}
HELP_TEXTS = {
}
EXTRA_ATTRS = {
'email': {
'required': "true",
},
'message': {
'style': 'height: 250px;',
},
'username': {
'autofocus': "",
'type': "email",
},
'zip_code': {
'pattern': r"(^\d{5}$)|(^\d{9}$)|(^\d{5}-\d{4}$)",
},
}
# https://hyperscript.org/
HYPERSCRIPTS = {
'new_password1': "install PasswordValidator(targetElement: #id_new_password2)",
'new_password2': "install PasswordValidator(targetElement: #id_new_password1)",
'password1': "install PasswordValidator(targetElement: #id_password2)",
'password2': "install PasswordValidator(targetElement: #id_password1)",
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.fields:
widget = self.fields[field_name].widget
if placeholder := self.PLACEHOLDERS.get(field_name):
widget.attrs['placeholder'] = placeholder
widget.attrs.update({
'autocomplete': self.AUTOCOMPLETES.get(field_name, 'off'),
})
if help_text := self.HELP_TEXTS.get(field_name):
self.fields[field_name].help_text = help_text
if extra_attrs := self.EXTRA_ATTRS.get(field_name):
widget.attrs.update(extra_attrs)
if hyperscript := self.HYPERSCRIPTS.get(field_name):
widget.attrs['_'] = hyperscript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment