仅当selectbox具有特定值时,django admin才显示字段

时间:2016-04-30 21:41:50

标签: python django django-admin

models.py

class FixedIncome(Asset):
   isin = models.CharField(max_length=6, blank=False)
   coupon = models.DecimalField(max_digits=7, decimal_places=4, help_text="Percent")
   payment_frequency = models.ForeignKey(PaymentFrequency)
   months = models.ManyToManyField(Month, blank = False, verbose_name = "Payment months")
   duration = models.DecimalField(max_digits=4, decimal_places=2, default='0')
   maturity_date = models.DateTimeField(default=datetime.now, blank=False)

   class Meta:
      verbose_name_plural = "Fixed Income"

我想django admin显示maturity_date属性,仅在选择月份(数字1到12,选择框)时才显示。我读过有关js的内容,但我无法做到:(

1 个答案:

答案 0 :(得分:2)

我使用jquery解决了这个问题,并在我的ModelAdmin上添加了一个类Media

admin.py

class FixedIncomeAdmin(admin.ModelAdmin):
model = FixedIncome
can_delete = False
list_display = ['name', 'country', 'industry', 'isin', 'coupon', 'payment_frequency']
list_filter = ['name', 'isin', 'country', 'industry']
search_fields = ['name', 'isin', 'country', 'industry']

class Media:
    js = ('/static/admin/js/assets_admin.js',)

assets_admin.js

django.jQuery('#id_payment_frequency').change(function(){
if(django.jQuery("#id_payment_frequency option:selected").text() == 0)
    {
        django.jQuery(".form-row.field-months").hide();
    }else
    {
        django.jQuery(".form-row.field-months").show();
    }
});

如果" payment_frequency"的选择框(0到12)有一个0,然后在表格中隐藏了几个月

希望能帮助某人。 :)