[英]Django OneToOne field as a dropdown in a form
I have two models related like this: 我有两个相关的模型:
class Report(Model):
...
product_line = models.OneToOneFiled(ProductLine)
class ProductLine(Model):
name = models.CharField()
...
I want users to upload a report and specify which product line it belongs to. 我希望用户上传报告并指定它所属的产品系列。 The product line field should be a dropdown list with predefined product names in it.
产品系列字段应该是一个下拉列表,其中包含预定义的产品名称。
My question is how to render this field and how to analysis the value posted back. 我的问题是如何渲染此字段以及如何分析回发的值。
For rendering, I guess I can do this: 对于渲染,我想我可以这样做:
render():
allProducts = ProductLine.objects.all() // side question: how to cache this queryset for repeated use?
names = []
for p in allProducts:
names.push(p.name)
return render(..., {'names': names})
Inside the template, I can loop over names
and populate the items of the dropdown list. 在模板内部,我可以遍历
names
并填充下拉列表中的项目。 Am I correct? 我对么?
When saving: 保存时:
postHandler():
// This is the part I am not so sure
// Since the value for the product line field will be a string
// I guess I cannot rely on a form object to validate it and expect
// it to pass, am I correct?
// so when I create a form out of ProductLine, I should use
// a customized validator instead:
class ReportForm(Form):
class Meta:
model = Report
clean_product_line():
cd = self.cleaned_data
allProducts = ProductLine.objects.all()
valid_names = []
for p in allProducts:
valid_names.push(p.name)
if cd in valid_names:
return allProducts.filter(name=cd)[0]
raise ValidationError('Invalid product name')
Is this approach correct? 这种方法是否正确? Is
clean_product_line
the right place for validation and returning a model
object back? clean_product_line
是验证和返回model
对象的正确位置吗?
A much simpler way would be to add an extra field for the product line to the form definition: 一种更简单的方法是将产品系列的额外字段添加到表单定义中:
class ReportForm(ModelForm):
product_line = forms.ModelChoiceField(queryset=ProductLine.objects.all())
That will automatically take care of displaying and validating the dropdown. 这将自动负责显示和验证下拉列表。 You'll need to manually set the field on the instance after saving though, using the value from cleaned_data.
使用cleaning_data中的值,您需要在保存后手动设置实例上的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.