How to limit User groups name field to three choices?
I have django model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
#other fields
When I create new UserProfile instance I want have only 3 group names to choice (in adm开发者_JS百科in interface and in my custom form): "student", "instructor", "dean". What is the best way to do it? Should I extend User model or Group?
First, make sure that you have three Group objects created, which correspond to your groups.
Next, you need to limit the choices in the admin. I'm not sure though, I think the group is in the User form? Here is one solution, which is a bit hackish. Override the UserChangeForm from http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/admin.py and use it as the custom form in the admin.
class UserForm(UserChangeForm):
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
names = ['student','instructor','dean']
self.fields['groups'] = forms.ModelChoiceField(queryset=Group.objects.filter(name__in=names))
class MyUserAdmin(UserAdmin):
form = UserForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
精彩评论