How to split one form fields into multiple fields of a model in django?

痞子三分冷 提交于 2019-12-11 16:59:16

问题


This question is similar to

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

and

How to render two form fields as one field in Django forms?

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.


回答1:


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



回答2:


Assuming, user will type first name and last name seperated by space. you can use this:

u_name = YourModelName()

name = request.POST['name'].split(" ") # give attribute name in html and use that name here
first_name = name[0]
last_name = name[1]

u_name.first_name = first_name
u_name.last_name = last_name

u_name.save()

you can use any method to save your data. just use split.



来源:https://stackoverflow.com/questions/57288620/how-to-split-one-form-fields-into-multiple-fields-of-a-model-in-django

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