gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:55 24 4
gpt4 key购买 nike

我有这些模型

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

关于python - Django ModelForm 从其他字段创建字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20034338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com