Django ModelForm具有模型中未包含的其他字段 [英] Django ModelForm with extra fields that are not in the model

查看:99
本文介绍了Django ModelForm具有模型中未包含的其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完成了ModelForm,添加了一些在模型中不是的额外字段。保存表单时,我会使用这些字段进行计算。

I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.

多余的字段会显示在表单上,​​并且在上载表单时会在POST请求中发送。问题是,当我验证表单时,它们没有添加到 cleaned_data 词典中。如何访问它们?

The extra fields appear on the form and they are sent in the POST request when uploading the form. The problem is they are not added to the cleaned_data dictionary when I validate the form. How can I access them?

推荐答案

可以扩展Django ModelForm 与额外的领域。假设您有一个自定义的用户模型,并且此 ModelForm

It's possible to extend Django ModelForm with extra fields. Imagine you have a custom User model and this ModelForm:

class ProfileForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['username', 'country', 'website', 'biography']

现在,假设您想添加一个额外的字段(用户模型中不存在,可以说是图像头像) 。通过执行以下操作扩展您的表单:

Now, imagine you want to include an extra field (not present in your User model, lets say an image avatar). Extend your form by doing this:

from django import forms

class AvatarProfileForm(ProfileForm):

    profile_avatar = forms.ImageField()

    class Meta(ProfileForm.Meta):
        fields = ProfileForm.Meta.fields + ('profile_avatar',)

最后(假设表单具有 ImageField ) ,请在实例化视图时记住包含 request.FILES

Finally (given that the form has an ImageField), remember to include request.FILES when instantiating the form in your view:

# (view.py)

def edit_profile(request):
    ...
    form = AvatarProfileForm(
        request.POST or None, 
        request.FILES or None, 
        instance=request.user
    )
    ...

希望有帮助。祝你好运!

Hope it helps. Good luck!

编辑:

我得到的是只能连接元组(而不是列表))到元组错误在AvatarProfileForm.Meta.fields属性中。将其更改为元组并且可以使用。

I was getting a "can only concatenate tuple (not "list") to tuple" error in AvatarProfileForm.Meta.fields attribute. Changed it to a tuple and it worked.

这篇关于Django ModelForm具有模型中未包含的其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆