覆盖Forms.modelAdmin中的django表单

时间:2017-11-07 11:14:55

标签: python django django-modeladmin

当我想覆盖表单中的字段时,我遇到了问题

该课程如下所示

   class UserCreationForm(forms.ModelForm):
class Meta:
    model = User
    fields = ['password', 'services', 'project', 'email', 'name', 'first_name', 'role']

我想用另一个值修改字段'Services'。 为此,我使用了get_form函数:

class UserAdmin(admin.ModelAdmin):
      exclude = ('uuid',)
      search_fields = ('email', "project")
      list_display = ("email", "project", "nb_connexion")
      form = UserCreationForm


    def get_form(self, request, obj=None, **kwargs):
        if obj != None:
            print(obj.name)
            print(request)
            form = super(UserAdmin, self).get_form(request, obj=obj, **kwargs)
            form.base_fields['services'].initial = Service.objects.filter(projects=obj.project)

        return form

但我仍然可以获得所有服务的相同结果,而我只对获得一个项目的服务感兴趣。非常感谢。

由于

1 个答案:

答案 0 :(得分:2)

您当前正在尝试设置initial,这是选择的初始值。如果您想限制选项,则需要覆盖queryset

您可以在__init__方法中更改表单的字段:

class UserCreationForm(forms.ModelForm):
    class Meta:
    model = User
    fields = ['password', 'services', 'project', 'email', 'name', 'first_name', 'role']

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['services'].queryset = Service.objects.filter(projects=self.instance.project)

您的UserAdmin课程已使用form = UserCreationForm,因此您只需删除get_form方法。

class UserAdmin(admin.ModelAdmin):
    ...
    form = UserCreationForm
    ...