如何在Django中将一个表单字段拆分为模型的多个字段? [英] How to split one form fields into multiple fields of a model in django?

查看:87
本文介绍了如何在Django中将一个表单字段拆分为模型的多个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题类似于

Using multiple input fields for one model's attribute with django

如何

我需要的基本上是 MultiValueField ,在这里我可以将一个表单字段- Name 中的数据保存到两个模型字段中-名,姓。我找不到类似MultiValueField的东西。

What I need is basically the opposite of MultiValueField where I can save data from one form field - Name into two model fields - Firstname, Lastname. I'm unable to find any such thing like the opposite of MultiValueField.

有人可以建议我这样做的更好方法是什么。

Can someone please suggest me what is the better way to do it.

推荐答案

为什么不在 Form 中定义 name 字段,并覆盖save方法以将其保存到模型字段中,如下所示:

Why don't you define the name field in Form and override the save method to save to the model fields like this:

class SomeForm(forms.ModelForm):
    name = forms.CharField(max_length=255, required=True)

    class Meta:
        model = YourModel
        fields = ['name', 'and_other_fields']

    def save(self, commit=True)
        instance = super(SomeForm, self).save(commit=False)
        _name = self.cleaned_data.get('first_name').split(' ')
        instance.first_name = _name[0]
        instance.last_name = ' '.join(_name[1:])
        instance.save()
        return instance

这篇关于如何在Django中将一个表单字段拆分为模型的多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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