簡體   English   中英

Django OneToOne字段作為表單中的下拉列表

[英]Django OneToOne field as a dropdown in a form

我有兩個相關的模型:

class Report(Model):
    ...
    product_line = models.OneToOneFiled(ProductLine)

class ProductLine(Model):
    name = models.CharField()
    ...

我希望用戶上傳報告並指定它所屬的產品系列。 產品系列字段應該是一個下拉列表,其中包含預定義的產品名稱。

我的問題是如何渲染此字段以及如何分析回發的值。

渲染

對於渲染,我想我可以這樣做:

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})

在模板內部,我可以遍歷names並填充下拉列表中的項目。 我對么?

保存

保存時:

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')

這種方法是否正確? clean_product_line是驗證和返回model對象的正確位置嗎?

一種更簡單的方法是將產品系列的額外字段添加到表單定義中:

class ReportForm(ModelForm):
    product_line = forms.ModelChoiceField(queryset=ProductLine.objects.all())

這將自動負責顯示和驗證下拉列表。 使用cleaning_data中的值,您需要在保存后手動設置實例上的字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM