Python Django ModelForm从其他字段生成字段

Python Django ModelForm从其他字段生成字段,python,django,django-models,django-forms,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 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',)

如何从“颜色代码”字段中获取颜色对象,并在保存模型表单时将其保存为新T恤的颜色?

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

class TshirtForm(forms.ModelForm):
    class Meta:
        model = Tshirt
        fields = ('name', 'color')
这将在表单中为您提供一个select字段。只需确保添加一些颜色供用户选择即可

但是如果你想让你的用户“创造”新的颜色,你应该使用两种形式,一种用于颜色,另一种用于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

你能不能把它作为一个下拉选择?我希望用户选择一种颜色,但我不希望颜色出现在选择字段中,我希望颜色是从他们输入的代码中获取的。是的,错过了。Added and else语句:如果捕获到异常,该行将不会运行。我很好奇,您是否使用返回颜色十六进制的颜色选择器?是的。此外,我还编辑了您的代码以使其正常工作。只有两个小改动:表单小部件没有“required”参数,所以我必须在color表单字段上显式地设置它,并且清除的_数据['color']需要是一个color实例,而不是color id。