F
F
Flash902015-08-26 21:31:45
Django
Flash90, 2015-08-26 21:31:45

How to dynamically override widgets for ModelForm?

There is a form:

class RegistrationForm(forms.ModelForm) :

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta :
        model = User
        fields = ('username', 'email', 'date_birth', 'phone')
        widgets = {
            'date_birth' : forms.DateInput(format='%Y-%m-%d',
                                           attrs={'type' : 'date'}),
            'username' : forms.TextInput(attrs={}),
            'email' : forms.TextInput(attrs={'type' : 'email'}),
            'phone' : forms.TextInput(attrs={}),
        }

    def clean_password(self):
        print(self)
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2 :
            raise forms.ValidationError('Passwords dont match')
        return password1

    def save_form(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

It is necessary that, if filled out incorrectly, a form is returned indicating errors (in this case, I'm just interested in adding the 'error-form' CSS class to incorrectly filled widgets fields). It is desirable to do this without js. Initially, I thought that it was possible to redefine widgets for an instance of the class, something like:
self.Meta.widgets[key].attrs['class'] = 'error_form' , but the entire class is redefined.
Is it possible to somehow redefine widget only for an instance, or maybe there is a more correct method.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
marazmiki, 2015-08-31
@marazmiki

Yes, this is a regular feature :

class RegistrationForm(forms.ModelForm) :
    error_css_class = 'error-form'

Z
zelsky, 2015-08-26
@zelsky

If I understand you correctly. That is already provided in jung.

def foo(request):
    messages.success(request, "Huge success!")
    return render(request, 'index.html')

{% for message in messages %}
    <div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question