haikal/inventory/mixins.py
2025-01-27 15:41:30 +00:00

61 lines
2.2 KiB
Python

from django import forms
from django.utils.translation import get_language
class AddClassMixin:
"""
Mixin for adding classes to form fields and wrapping them in a div with class 'form-floating'.
"""
def add_class_to_fields(self):
"""
Adds the class to the fields of the form and wraps them in a div with class 'form-floating'.
"""
for field_name, field in self.fields.items():
# Add classes to the field
if isinstance(field.widget, forms.Select):
existing_classes = field.widget.attrs.get('class', '')
field.widget.attrs['class'] = f"{existing_classes} form-select form-select-sm".strip()
else:
existing_classes = field.widget.attrs.get('class', '')
field.widget.attrs['class'] = f"{existing_classes} form-control form-control-sm".strip()
# Wrap the field in a div with class 'form-floating'
field.widget.attrs['wrapper_class'] = 'form-floating'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_class_to_fields()
def __getitem__(self, name):
"""
Overrides the __getitem__ method to wrap the field in a div with class 'form-floating'.
"""
field = super().__getitem__(name)
wrapper_class = field.field.widget.attrs.pop('wrapper_class', None)
if wrapper_class:
field = forms.utils.safety.mark_safe(f'<div class="{wrapper_class}">{field}</div>')
return field
class LocalizedNameMixin:
"""
Mixin to provide a reusable get_localized_name method.
"""
def get_local_name(self):
"""
Returns the localized name based on the current language.
"""
if get_language() == 'ar':
return getattr(self, 'arabic_name', None)
return getattr(self, 'name', None)
# class AddDealerInstanceMixin:
# def form_valid(self, form):
# if form.is_valid():
# form.instance.dealer = self.request.user.dealer.get_root_dealer
# form.save()
# return super().form_valid(form)
# else:
# return form.errors