How to restrict values in admin input form?

43 views
Skip to first unread message

Mark Phillips

unread,
Apr 6, 2012, 1:55:20 PM4/6/12
to django users
I have a table D that contains two foreign keys from tables A and B. There is another table in the model, call it C, that relates the keys in A and B. In the admin input form for table D, I want to restrict the values for B based on what the user input for A and the values already stored in table C. For example:

Table C has the following data
A.id | B.id
 1    |   1  
 1    |   2
 1    |   3
 2    |   4
 2    |   3

In the admin form for table D, if the user selects 2 for A.id, I want to only show 4 and 3 in the drop down for B.id. If the user selects 1 for A.id, I want to show 1,2,3 in the drop down for B.id. Is this possible? How would I incorporate this restriction for the admin input form for table D. 

As a 1 week old django newbie, I am not sure what to look for in the documentation, which, by the way, I find to be excellent - well written, clear, concise, and very helpful. Thank-you to all the writers on the project! For what it is worth, I am using django 1.3 on Debian testing (that is the latest version in the Debian repositories).

Thanks,

Mark

Shawn Milochik

unread,
Apr 6, 2012, 2:00:03 PM4/6/12
to django...@googlegroups.com
https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#adding-custom-validation-to-the-admin

Essentially, make a ModelForm exactly as you would normally, and add
logic to it.

You're going to want to change the queryset of the field(s) in question.

For example:


class ThingAdminForm(forms.ModelForm):


def __init__(self, *args, **kwargs):
super(ThingAdminForm, self).__init__(*args, **kwargs)

if self.instance:
self.fields['whatever'].queryset =
self.fields['whatever'].queryset.filter(something=something_else)

class Meta:
model = ThingForm

Reply all
Reply to author
Forward
0 new messages