views:

110

answers:

2

Hi,

In my class I have about 12 fields. One field is status, another is reason. When I go to the edit page in the django admin, I only want to show the second field (reason field) if the status=='rejected'. The problem is very simple: just showing the fields according to the user input.

+2  A: 

There is unfortunately no easy way to do this purely server-side. However, it should be relatively easy to accomplish with some JavaScript – toggling the visibility of the reason field based on the status. The following is an example using jQuery:

$(document).ready(function() {
    // Toggle visibility on page load
    setReasonVisibility();

    // Toggle visibility on status change
    $('form #id_status').bind('change', setReasonVisibility)

    function setReasonVisibility() {
        var form = $('form');
        var status = $(form).find('#id_status').val();
        if (status == 'rejected') 
            $(form).find('#id_reason').show();
        else
            $(form).find('#id_reason').hide();
    }
});

To have the form load the JavaScript file, you need to refer to it in a Media class to the form for your model, somehow like this:

class YourModelForm(forms.ModelForm):
     class Meta:
         model = YourModel
     class Media:
         js = ('path/to/jquery.js', 'path/to/your-js-file.js')

This solution should work seamlessly within the Django admin.

Guðmundur H
A: 

It's not clear to me whether you're referring to the change list or the individual edit page for an item. If the latter, @Guðmundur H has a good jQuery solution. If the former, you could do it by providing a method on your model, reason_if_rejected, that returns the reason if the status is 'rejected' and otherwise returns an empty string. You can then include the name of this method in your list_display setting.

Carl Meyer