Django ModelForm从其他字段创建字段

时间:2013-11-17 18:12:39

标签: python django django-models django-forms

我有这些模型

class Color(models.Model):
    code = models.CharField(max_length=7, unique=True)
    name = models.CharField(max_length=100)
class Tshirt(models.Model):
    name = models.CharField(max_length=100)
    color = models.ForeignKey(Color)

我有这个表格

class TshirtForm(forms.ModelForm):
    color_code = forms.CharField(min_length=7, max_length=7)
    class Meta:
        model = Tshirt
        fields = ('name',)

如何从color_code字段中获取Color对象并将其保存为保存modelform时新T恤的颜色?

1 个答案:

答案 0 :(得分:3)

如果您希望用户选择颜色,只需扩展字段

class TshirtForm(forms.ModelForm):
    class Meta:
        model = Tshirt
        fields = ('name', 'color')

这将为您提供表单中的选择字段。只需确保添加一些颜色供您的用户选择。

但如果您希望用户“创建”新颜色,则应使用两种形式,一种用于颜色,另一种用于T恤。这比试图以一种形式做所有事情更简单。

<强>更新

好的,请更新您的表单:

class TshirtForm(forms.ModelForm):
    color_code = forms.CharInput()

    class Meta:
        model = Tshirt
        fields = ('name', 'color')
        widget = {'color': forms.HiddenInput(required=False)}

    def clean(self, *args, **kwargs):
        # If users are typing the code, better do some validation
        try:
            color = Color.objects.get(
                code=self.cleaned_data.get('color_code')
            )
        except (ObjectDoesNotExist, MultipleObjectsReturned):
            raise forms.ValidationError('Something went wrong with your code!')
        else:
            # Update the actual field
            self.cleaned_data['color'] = color.id