Ochui Princewill
Ochui Princewill

Reputation: 157

Django: Add extra attributes to form fields generated by UpdateView

Am using a custom user that is a subclass of Django AbstractUser, what am trying to archive is to allow user update their data everything works but the form look ugly. Below is my code the class attribute is not added to the form. forms.py(simplified)

class AccountEditForm(forms.ModelForm):
 class Meta:
     model = CustomUser
     fields = ('first_name', 'last_name', 'phone_number', 'date_of_birth', 'country')
     widget = {
         'first_name':forms.TextInput(
             attrs={
                 'class': 'input-bordered',
             }
         )
     }

views.py

class UserAccountDetails(LoginRequiredMixin, UpdateView):

template_name = 'dashboard/account_edit.html'
context_object_name = 'form'
form_class = AccountEditForm
model = CustomUser

def get_object(self, queryset=None):
    """
    Return the object the view is displaying.
    """
    if queryset is None:
        queryset = self.get_queryset()

    #Get logged in user from request data
    queryset = queryset.filter(pk=self.request.user.id)

    try:
        # Get the single item from the filtered queryset
        obj = queryset.get()
    except queryset.model.DoesNotExist:
        raise Http404(_("No %(verbose_name)s found matching the query") %
                    {'verbose_name': queryset.model._meta.verbose_name})
    return obj

Upvotes: 2

Views: 1877

Answers (1)

Uroš Trstenjak
Uroš Trstenjak

Reputation: 903

The widgets option is for overriding the defaults on explicitly declared fields. To add class to the field you have many options.

Option #1: Explicitly declare form field and add class through widgets in Meta.

class AccountEditForm(forms.ModelForm):
    first_name =  forms.TextField(widget=forms.TextInput())

class Meta:
     model = CustomUser
     fields = ('first_name', 'last_name', 'phone_number', 'date_of_birth', 'country')
     widgets = {
         'first_name': forms.TextInput(
             attrs={
                 'class': 'input-bordered',
             }
         )
     }

Option #2: Shorter version of option #1.

class AccountEditForm(forms.ModelForm):
    first_name =  forms.TextField(widget=forms.TextInput(attrs={'class': 'input-bordered'}))

    class Meta:
        model = CustomUser
        ...

Option #3: Add class in form's __init__ method.

class AccountEditForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AccountEditForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget.attrs['class'] = 'input-bordered'

Option #4: Use django-widget-tweaks plugin.

Upvotes: 2

Related Questions