| How to require selection of a M2M with intermediate table/model during admin record creation? | M Hill | 8/28/13 7:30 PM | I have been beating my head against the wall trying to figure this out.
I came up with a simplified example to illustrate what I'm trying to
do. This is the view. As you can see, it doesn't accommodate hooking up the new User with any Position(s). So I wrote a UserAdmin and a form to go with it. The new admin.py:# imports class UserPositionAdmin (admin.TabularInline): model = UserPosition extra = 1 class UserCreationForm (forms.ModelForm): class Meta: model = User class UserAdmin (admin.ModelAdmin): form = UserCreationForm inlines = (UserPositionAdmin,) admin.site.register (User, UserAdmin) admin.site.register (Position) Now the input form looks like this: Now my problem is that I require each User to have at least one Position, but I can't figure out how to get the form to fail validation (i.e., in the clean() call) if no Position is selected in the inline. I've tried waiting until the User's save() function is reached, and tried checking in the UserAdmin's save_model(), but so far have been unable to find out at those points if a Position was selected before form submission or not. So I think the UserCreationForm is the right place to check for it. The problem seems to be that the field isn't technically part of the User class, so the form validation doesn't look for a clean_userpositions() function. I tried creating a function by that name, but it never got called if the Position was blank (I didn't test with a valid Position selection). It seems to me this can't possibly be something nobody's ever done before, but I haven't been able to find the answers even in the voluminous Django 1.5 documentation. I would greatly appreciate direction on how to validate that a Position is selected. Thanks in advance. |
| Re: How to require selection of a M2M with intermediate table/model during admin record creation? | M Hill | 8/31/13 10:55 AM | Another application of the validation occurred to me: Since multiple rows can be added to the form, I would want to check for and reject multiple selections of the same Position title. |