python - 带有不在模型中的额外字段的 Django ModelForm

标签 python django forms

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

额外的字段出现在表单上,​​并在上传表单时在 POST 请求中发送。问题是当我验证表单时它们没有添加到 cleaned_data 字典中。如何访问它们?

最佳答案

EDIT 2020(Django 2 或更高版本)

在 Django 2+ 中,您可以像这样添加额外的字段:

class ProfileForm(forms.ModelForm):
    
    extra_field = forms.ImageField()

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

原始答案(Django 1)

可以使用额外的字段来扩展 Django ModelForm。假设你有一个自定义的用户模型和这个 ModelForm:

class ProfileForm(forms.ModelForm):

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

现在,假设您想要包含一个额外的字段(在您的用户模型中不存在,比如说图像头像)。通过这样做来扩展您的表单:

from django import forms

class AvatarProfileForm(ProfileForm):

    profile_avatar = forms.ImageField()

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

最后(假设表单有一个 ImageField),记得在 View 中实例化表单时包含 request.FILES:

# (view.py)

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

希望对您有所帮助。祝你好运!

编辑:

我在 AvatarProfileForm.Meta.fields 属性中收到“只能将元组(而不是“列表”)连接到元组”错误。将其更改为元组,并且可以正常工作。

关于python - 带有不在模型中的额外字段的 Django ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229039/

相关文章:

python - 当 find 返回 NoneType 时 BeautifulSoup 错误处理

python - pandas - 将列标签分配给记录值作为最小/最大函数的结果

python - 在 Jupyter Notebook Cell 中执行突出显示的代码?

javascript - 验证后 Angular 表单重置

jquery - 使用 jQuery 根据下拉框值动态添加表单字段(或字段集)

python - 有什么方法可以将消息发送到松弛 bolt 中的线程吗?

python - Gunicorn 上的 Django 服务 POST 请求作为 GET 接收?

django - 组织 Django 单元测试

python - 在 web.py 中返回多行

forms - Rails Select helper in form required True 不起作用