1

我的表单中有一个有效的保存方法,一旦我升级它就表现得很奇怪,我似乎无法调试问题的根源

我有一个从 ModelForm 继承的简单表单,在其中我覆盖了 save 方法以保存一些外部属性

下面是我的代码

class UserProfileForm(ExtendedMetaModelForm):
    """
    UserProfileForm

    """
    _genders = (
        ('M', _('Male')),
        ('F', _('Female')),
        )

    birthday            = forms.DateField(
        widget=extras.SelectDateWidget(attrs={'class' : 'span1'},years=(range(1930, datetime.now().year-14))),
        label   =   _('Birthday'),
        required=   False,
        error_messages  = {
            'required' : _('Birthday is required.')
        }

    )
    gender            = forms.CharField(
        label   =   _('Gender'),
        widget  =   forms.Select(choices=_genders)
    )
    bio             = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows' : '4'}))

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'bio', 'birthday', 'gender', 'email',)



    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)



        if self.instance:
            self.fields['email'].widget.attrs['readonly'] = True
            self.fields['birthday'].initial = self.instance.get_profile().birthday
            self.fields['bio'].initial = self.instance.get_profile().bio

        for i in self.fields:
            if isinstance(self.fields[i], forms.CharField):
                self.fields[i].widget.attrs["class"]       = 'input-xlarge'

    def save(self, *args, **kw):
        super(UserProfileForm, self).save(*args, **kw)
        self.instance.get_profile().bio           = self.cleaned_data.get('bio')
        self.instance.get_profile().birthday      = self.cleaned_data.get('birthday')
        self.instance.get_profile().save()

以上工作正常,现在。在初始化表单时,它会从配置文件中检索 bio、birthday 的初始值。

但是,在保存时它会继续前进而没有任何动作。我的个人资料模型非常基本,保存方法没有改变它使用models.Model的原始操作

任何人都可以就为什么会发生这种情况提出建议吗?

PS没有返回错误,它只是没有保存任何东西

更新(添加了 ExtendedMetaModelForm 类):

class ExtendedMetaModelForm(forms.ModelForm):
    """
    Allow the setting of any field attributes via the Meta class.
    """
    def __init__(self, *args, **kwargs):
        """
        Iterate over fields, set attributes from Meta.field_args.
        """
        super(ExtendedMetaModelForm, self).__init__(*args, **kwargs)
        if hasattr(self.Meta, "field_args"):
            # Look at the field_args Meta class attribute to get
            # any (additional) attributes we should set for a field.
            field_args = self.Meta.field_args
            # Iterate over all fields...
            for fname, field in self.fields.items():
                # Check if we have something for that field in field_args
                fargs = field_args.get(fname)
                if fargs:
                    # Iterate over all attributes for a field that we
                    # have specified in field_args
                    for attr_name, attr_val in fargs.items():
                        if attr_name.startswith("+"):
                            merge_attempt = True
                            attr_name = attr_name[1:]
                        else:
                            merge_attempt = False
                        orig_attr_val = getattr(field, attr_name, None)
                        if orig_attr_val and merge_attempt and\
                           type(orig_attr_val) == dict and\
                           type(attr_val) == dict:
                            # Merge dictionaries together
                            orig_attr_val.update(attr_val)
                        else:
                            # Replace existing attribute
                            setattr(field, attr_name, attr_val)
4

2 回答 2

2

在 1.5中,由于引入了自定义用户模型AUTH_PROFILE_MODULEget_profile弃用

于 2013-04-09T16:08:18.177 回答
2

正如@Ngenator 指出的那样,您正在使用已弃用的函数。您可以尝试创建自定义 User模型

settings.py

AUTH_USER_MODEL = 'myapp.MyUser'

myapp.MyUser使用您指定的属性创建一个新用户

class MyUser(AbstractBaseUser):

    bio = TextField()
    birthday = DateField()

你需要摆脱get_profile()你的形式。

def save(self, *args, **kw):

    self.instance.bio           = self.cleaned_data.get('bio')
    self.instance.birthday      = self.cleaned_data.get('birthday')

    super(UserProfileForm, self).save(*args, **kw)

注意 - 这可能会破坏您的许多数据库结构并需要进行重大升级!你真的需要 django 1.5 吗?

于 2013-04-09T16:19:02.063 回答