How can I exclude the declared field in ModelForm in a subclass of the form?

In Django, I am trying to get (subclass) a new form from a form ModelFormwhere I would like to remove some fields (or only have some fields, to be more precise). Of course, the obvious way would be to do (base form from django.contrib.auth.forms):

class MyUserChangeForm(UserChangeForm):
  class Meta(UserChangeForm.Meta):
    fields = ('first_name', 'last_name', 'email')

But this does not work, because it also adds / saves the field usernamein the received form. This field has been explicitly stated in UserChangeForm. Even adding an attribute usernamein excludedoes not help.

Is there a correct way to exclude it and am I missing something? This is mistake? Is there any workaround?

+2
source share
2 answers

Try the following:

class MyUserChangeForm(UserChangeForm):

  def __init__(self, *args, **kwargs):
    super(MyUserChangeForm, self).__init__(*args, **kwargs)
    self.fields.pop('username')

  class Meta(UserChangeForm.Meta):
    fields = ('first_name', 'last_name', 'email')

.

+3

, () ( exclude ):

def __init__(self, *args, **kwargs):
  super(UserChangeForm, self).__init__(*args, **kwargs)
  for field in list(self.fields):
    if field not in self._meta.fields:
      del self.fields[field]

.

+1

Source: https://habr.com/ru/post/1795312/


All Articles