Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin. Hide field on change select field

I have model:

class CategoryField(models.Model):
    selectfield = models.IntegerField(choices=SELECT_FIELD_CHOICES, default=1)
    verified = models.BooleanField(default=True, verbose_name='Required?')

In admin page I have selectField with choices: "value1", "value2", "value3", ... When I select "value2" I need to show verified field. How can I do it?

like image 408
Detonavomek Avatar asked Oct 01 '14 10:10

Detonavomek


1 Answers

You would need to add some JavaScript in order to show or hide the field. jQuery 1.9.1 is available in Django admin already via the django.jQuery object.

The simplest way to add this JavaScript is to add a Media meta class to your model form and add the form to the ModelAdmin:

# forms.py

from django import forms

class CategoryFieldForm(forms.ModelForm):
    . . .

    class Media:
        js = ('category-field-admin.js',)


# admin.py

from django.contrib import admin

from your_app.forms import CategoryFieldForm
from your_app.models import CategoryField


class CategoryFieldAdmin(admin.ModelAdmin):
    form = CategoryFieldForm


admin.site.register(CategoryField, CategoryFieldAdmin)


# category-field-admin.js

// pseudo code - change as needed

(function($) {
    $(function() {
        var selectField = $('#id_selectField'),
            verified = $('#id_verified');

        function toggleVerified(value) {
            value == 'value2' ? verified.show() : verified.hide();
        }

        // show/hide on load based on pervious value of selectField
        toggleVerified(selectField.val());

        // show/hide on change
        selectField.change(function() {
            toggleVerified($(this).val());
        });
    });
})(django.jQuery);
like image 179
Brandon Avatar answered Oct 13 '22 19:10

Brandon