2
votes

For me this is weird, maybe it isn't and I'm missing something obvious:

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class formRegistro(UserCreationForm):    
    class Meta:
        model = User
        fields = ("first_name", "last_name", "email", "username", "password1", "password2")
        widgets = {
                'first_name': forms.TextInput(attrs={'class':'form-control'}),
                'last_name': forms.TextInput(attrs={'class':'form-control'}),
                'email': forms.TextInput(attrs={'class':'form-control'}),
                'username': forms.TextInput(attrs={'class':'form-control'}),
                'password1': forms.PasswordInput(attrs={'class':'form-control'}),
                'password2': forms.PasswordInput(attrs={'class':'form-control'})
        }

views.py

def registro(request):    
    template = "perfiles/registro.html"
    form = formRegistro()
    context = {'form' : form}
    return render(request, template, context)

html registro.html

<form class="form-horizontal" action="{% url 'perfiles:registro' %}" method="post">
    {% csrf_token %}        
        <fieldset>
            {{form}}
        </fieldset>         
        <input type="submit" value="Submit">
</form>

It looks fine to me, I'm just rendering a form. All I want is to add "form-control" to the input's classes. What is weird is that it only adds "form-control" to the fields "first_name", "last_name" and "email_address". ?ยก No form-control-class for the inputs "username", "password1" and "password2".

Here is the rendered html: screenshot

1

1 Answers

4
votes

If you look at the source code of the UserCreationForm you will see that these three fields are declaratively defined:

class UserCreationForm(forms.ModelForm):
    ...
    username = forms.RegexField(...)
    password1 = forms.CharField(...)
    password2 = forms.CharField(...)
    ...

According to the documentation, you cannot override them in Meta:

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

Therefore your best option would be to copy those declarations into your own class and override the widget options there.

Update: Another option would be to modify widget attributes in the __init__ method of the form as @catavaran suggested. See this answer for an example.