简体   繁体   中英

django admin show field only if selectbox has a particular value

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"

I want to django admin show the maturity_date attribute, only if month (numeric 1 to 12, selectbox) is selected. I've read something about js, but I can't do it :(

I solved that using jquery and adding a class Media on my ModelAdmin

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();
    }
});

if the selectbox of "payment_frequency" (0 to 12) has a 0, then months is hidden in the form

Hope to help to someone.! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM