How can I exclude a declared field in ModelForm in form's subclass?

这一生的挚爱 提交于 2019-12-05 04:47:16

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3287974/how-can-i-exclude-a-declared-field-in-modelform-in-forms-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!