K
K
KIN19912015-05-20 09:28:12
Django
KIN1991, 2015-05-20 09:28:12

How to make a composite field in Django?

Hello everyone, there is a model with a fio field, you need to create a form and divide this field into 3 parts, i.e. into the first name, last name and patronymic fields. How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
marazmiki, 2015-05-20
@KIN1991

# models.py
class Model(models.Model):
    fio = models.CharField(max_length=255)

# forms.py
class Form(forms.ModelForm):
    first_name = forms.CharField()
    middle_name = forms.CharField()
    last_name = forms.CharField()

    def clean(self):
        self.instance.fio = '{first_name} {middle_name} {last_name}'.format(**self.cleaned_data)
        return self.cleaned_data

    class Meta:
        model = Model
        fields = ['first_name', 'last_name', 'middle_name']

The code was written directly in the browser, did not check for spelling, but the idea is exactly this: in clean () of the form, we substitute the collected value in self.instance, which will be the object of the model associated with the form.

Z
zelsky, 2015-05-20
@zelsky

fio.split(" ", 1) - if space

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question