سؤال

I know how to add a 'class' or other widget attribute to an automatically built ModelForm:

class ExampleSettingForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ExampleSettingForm, self).__init__(*args, **kwargs)
        self.fields['example_field'].widget.attrs['class'] = 'css_class' 
    class Meta:
        model = Example

How do I insert a help_text= into the example_field Field?

هل كانت مفيدة؟

المحلول

As of Django 1.6: You can edit it within the Meta class. Try:

class ExampleSettingForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ExampleSettingForm, self).__init__(*args, **kwargs)
        self.fields['example_field'].widget.attrs['class'] = 'css_class' 
    class Meta:
        model = Example
        help_texts = {
                'example_field': ('Here is some help'),
        }

Docs on this are at https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields. See release notes at http://django.readthedocs.org/en/latest/releases/1.6.html . You can set your own label, help_text and error_messages.

نصائح أخرى

This is what I did in Django 1.9:

class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ('__all__')
        help_texts = {
            "my_field": "This is case sensitive..."
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top