Django ModelForm override widget

后端 未结 1 799
难免孤独
难免孤独 2020-11-30 08:49

Disclaimer: I am a beginner with python and Django but have Drupal programming experience.

How can I override the default widget of this:

#models.py
         


        
相关标签:
1条回答
  • 2020-11-30 09:00

    If you want to override the widget for a formfield in general, the best way is to set the widgets attribute of the ModelForm Meta class:

    To specify a custom widget for a field, use the widgets attribute of the inner Meta class. This should be a dictionary mapping field names to widget classes or instances.

    For example, if you want the a CharField for the name attribute of Author to be represented by a <textarea> instead of its default <input type="text">, you can override the field’s widget:

    from django.forms import ModelForm, Textarea
    from myapp.models import Author
    
    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = ('name', 'title', 'birth_date')
            widgets = {
                'name': Textarea(attrs={'cols': 80, 'rows': 20}),
            }
    

    The widgets dictionary accepts either widget instances (e.g., Textarea(...)) or classes (e.g., Textarea).

    https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields

    0 讨论(0)
提交回复
热议问题