0

I have a problem when I want to override a field in my form

The class looks like below

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

I want to modify the field 'Services' with another value. For this I used the get_form function like this :

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

But I still get the same results for all the services while I am only interested in getting the services of one project.Any help would be appreciated.

Thanks

NSP
  • 1,193
  • 4
  • 15
  • 26
reda
  • 5
  • 3
  • but how i can fill the list with just the 'services' of the user, ? – reda Nov 07 '17 at 11:25
  • Note that your form may not handle hashing the `password` field correctly. You could look at extending the `UserCreationForm` and `UserAdmin` from Django. – Alasdair Nov 07 '17 at 11:33

1 Answers1

2

You are currently trying to set initial, which is the initial value selected. If you want to limit the choices, you want to override the queryset instead.

You can alter the form's fields in the __init__ method:

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)

Your UserAdmin class already uses form = UserCreationForm, so all you have to do is remove the get_form method.

class UserAdmin(admin.ModelAdmin):
    ...
    form = UserCreationForm
    ...
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
Alasdair
  • 298,606
  • 55
  • 578
  • 516