在超类属性中添加help_text

时间:2012-02-05 00:30:05

标签: python django

假设我有一个名为MySuper的模型:

class MySuper(models.Model):
    some_attr = models.CharField(max_length=128)

我有两个继承自此模型的子类,名为MySub1MySub2

我需要向help_text添加some_attr,但每个子类必须不同。有没有办法做到这一点?

class MySub1(MySuper):
    # ...
    # add help_text='Help text of some_attr inside MySub1'

class MySub2(MySuper):
    # ...
    # add help_text='Help text of some_attr inside MySub2'

2 个答案:

答案 0 :(得分:1)

我需要为具有不同图像尺寸的两个相同型号执行此操作。可能有一些很好的方法来概括这一点,但对于两个项目我的答案会很好。首先在您的应用中创建一个名为forms.py的文件。

from django import forms
from .models import FeaturedProduct, ShopProduct

class FeaturedProductForm(forms.ModelForm):
    class Meta:
        model = FeaturedProduct
    ihelp = "Image should be 500x220."
    src = forms.ImageField(help_text=ihelp,required=False)

class ShopProductForm(forms.ModelForm):
    class Meta:
        model = FeaturedProduct
    ihelp = "Image should be 100x100."
    src = forms.ImageField(help_text=ihelp,required=False)

请注意required默认为true,即使您的模型上有null=True, blank=True也是如此。然后在admin.py中定义您的ModelAdmin,如下所示:

from .forms import FeaturedProductForm, ShopProductForm

class ShopProductAdmin(admin.ModelAdmin):
  form = ShopProductForm

class FeaturedProductAdmin(admin.ModelAdmin):
  form = FeaturedProductForm

我省略了一些导入和整个admin.site.register废话。如果您需要更多信息,请告诉我。 forms.FIELDS的完整列表可在此处找到:

https://docs.djangoproject.com/en/dev/ref/forms/fields/

答案 1 :(得分:1)

在不必完全重新定义字段的情况下实现此目的的另一种方法是:

class MySub1(MySuper):
    pass

MySub1._meta.get_field('some_attr').help_text = 'sub1 help text'


class MySub2(MySuper):
    pass

MySub2._meta.get_field('some_attr').help_text = 'sub2 help text'