G
G
Gasoid2017-03-29 10:52:27
Django
Gasoid, 2017-03-29 10:52:27

Why does the decorator go into recursion?

Wrote a class decorator that modifies form widgets.
Doesn't work if init is redefined in the form, it goes into recursion,
what to do? where to dig?

from django import forms
from users.models import User, Role
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from .utils import field_attrs


@field_attrs({'class': 'form-control', 'required': 'required'})
class EditUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['group', 'role']

    def __init__(self, *args, **kwargs):
        super(EditUserForm, self).__init__(*args, **kwargs)
        self.fields['group'].empty_label = 'Выберите группу'


@field_attrs({'class': 'form-control', 'required': 'required'})
class EditRoleForm(forms.ModelForm):
    class Meta:
        model = Role
        fields = ['name', 'form']


@field_attrs({'class': 'form-control', 'required': 'required'},
             username={'placeholder': 'Логин'},
             password={'placeholder': 'Пароль'})
class AuthForm(AuthenticationForm):
    username = forms.CharField(max_length=100)
    password = forms.CharField(label=_("Пароль"), widget=forms.PasswordInput())

def field_attrs(all_attrs, **fargs):
    def decorator(obj):
        class Cls(obj):
            def __init__(self, *args, **kwargs):
                super(Cls, self).__init__(*args, **kwargs)
                for k in self.fields:
                    self.fields[k].widget.attrs.update(all_attrs)
                for k in fargs:
                    self.fields[k].widget.attrs.update(fargs[k])
        return Cls
    return decorator

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question