views:

48

answers:

2

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

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

But this does not work as it adds/keeps also an username field in the resulting form. This field was declared explicitly in UserChangeForm. Even adding username to exclude attribute does not help.

Is there some proper way to exclude it and I am missing something? Is this a bug? Is there some workaround?

A: 

Try this:

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')

This dynamically removes a field from the form when it is created.

gruszczy
A: 

It seems the (generic) workaround (still missing taking exclude into the account) is:

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]

But this smells like a bug to me.

Mitar
I have opened a [bug for Django](http://code.djangoproject.com/ticket/13971).
Mitar