1

I need to assign a boostrap class to all my user's field in Django admin form, I wrote this code but it does not work.

  formfield_overrides = {
    models.CharField:     {'widget': TextInput(attrs={'class': 'form-control'})},
    models.CharField:     {'widget': EmailInput(attrs={'class': 'form-control'})},
    models.DateField:     {'widget': DateTimeInput(attrs={'type': 'date', 'class': 'form-control'})},
    models.EmailField:    {'widget': EmailInput(attrs={'class': 'form-control'})},
    models.BooleanField:  {'widget': CheckboxInput(attrs={'class': 'form-control'})},
 }

Can you help me?

3
  • Check the docs on how to do it. Commented Nov 4, 2017 at 18:13
  • Yes, I've read the docs but I am not able to bind the form to my admin page Commented Nov 4, 2017 at 18:20
  • @Mark116 To bind the form to the administrator page, you must in the admin.py to create a class that inherit the admin.ModelAdmin. Next, specify the form attribute with your form. Commented Nov 4, 2017 at 22:37

2 Answers 2

1

Your form

#yourapp/forms.py
class YourForm(forms.ModelForm):
    class Meta: 
        model = YourModel
        fields = (field1,field2,field3,)

    def __init__(self, *args, **kwargs): 
        super().__init__(*args, **kwargs)
        for field in self._meta.fields:
            attrs = {'class':'form-control'}
            if self.fields[field].widget.__class__.__name__ == "DateTimeInput":
                attrs.update({'type':'date'})
            self.fields[field].widget.attrs.update(attrs)

Next, admin.py

#yourapp/admin.py
from django.contrib import admin
from .forms import YourForm
from .models import YourModel

class AdminModel(admin.ModelAdmin):
    form = YourForm

admin.site.register(YourModel,AdminModel)

You can learn more from the documentation.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to override some of the Field options for use in the admin, please check this for detail: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides. And the most common use of formfield_overrides is to add a custom widget for a certain type of field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.