Django: multiple different fields -> one model

时间:2018-09-18 20:20:15

标签: django

I want to show different fields (a html-option-field who gets Mymodel.object.all and a textfield) and save it to one model field.

How can I build this?

MultiValueField (https://docs.djangoproject.com/en/2.1/ref/forms/fields/) doesn't help with different fields? Has someone an example? How can I define which kind of field it is?

EDIT: How can I determine which field I want to save in the model-field? I use a ModelForm.

1 个答案:

答案 0 :(得分:1)

您应该在选择字段中使用forms.ModelChoiceField(choices=ModelClass.objects.all()),也可以将小部件设置为widget=forms.CheckboxSelectMultiple

您的表格可以像

class SuperForm(forms.Form):
    cool_field = forms.ModelChoiceField(
        choices=ModelClass.objects.all(),
        widget=forms.CheckboxSelectMultiple,
    )

    text_area = forms.CharField(widget=forms.Textarea)