Skip to main content
 首页 » 编程设计

python之Django ModelForm 从其他字段创建字段

2024年08月28日33over140

我有这些模型

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 对象,并在保存模型时将其保存为新 T 恤的颜色?

请您参考如下方法:

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

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