禁用选项charField选择取决于另一个属性(Django)

时间:2018-11-20 03:24:32

标签: python django django-models django-forms

因此,我的model.py中包含以下内容:

UNITY_CHOICES = (
    ('g', 'Gram(s)'),
    ('kg', 'Kilogram(s)'),
    ('l', 'Liter(s)'),
    ('cl', 'Centiliter(s)'),
)
class Recipe_Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.FloatField()
    cost = models.DecimalField(max_digits=20, decimal_places=2)

    quantityUnit = models.CharField(
        max_length=2,
        choices=UNITY_CHOICES,
        default=GRAM,
    )
class Ingredient(models.Model):
    name = models.CharField(max_length=200)
    articleNumber = models.IntegerField(unique=True)
    costPrice = models.DecimalField(max_digits=20, decimal_places=2)
    costAmout = models.FloatField()
    costUnity = models.CharField(
        max_length=2,
        choices=UNITY_CHOICES,
        default=GRAM,
    )

我有一个简单的表单可以将此模型添加到我的数据库中:

class Recipe_IngredientForm(forms.ModelForm):
    class Meta:
        model = Recipe_Ingredient
        fields = ('quantity', 'quantityUnit', 'ingredient')

所以我想知道是否有一种方法可以根据所选择的成分来过滤数量单位可用的选择。 我将通过一个示例来阐明这一点:假设我选择添加Potato,并且Potato的costUnity为'g',那么我想使'kg'和'g'为quantityUnit的唯一选择。这是一个好例子吗?如果不够清楚,我可以尝试考虑一些更好的方法。 无论如何,有可能这样做吗?谢谢。

更新: forms.py:

class Recipe_IngredientForm(forms.ModelForm):

    class Meta:
        model = Recipe_Ingredient
        fields = ('quantity', 'quantityUnit', 'ingredient')

模板:

{% extends 'recipe/base.html' %}

{% block content %}
    <h1>Add Ingredient to Recipe</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>
{% endblock %}

渲染的HTML:

<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form"><input type="hidden" name="csrfmiddlewaretoken" value="tXVR3NM1R4TBwOJArWWClL71r8S5C18gWKz9mKK42wlEamf6NcBjzrieF5dQBOaO">
    <p>
        <label for="id_quantity">Quantity:</label>
        <input type="number" name="quantity" required="" id="id_quantity" step="any">
    </p>
    <p>
        <label for="id_quantityUnit">QuantityUnit:</label>
        <select name="quantityUnit" id="id_quantityUnit">
            <option value="g" selected="">Gram(s)</option>
            <option value="kg">Kilogram(s)</option>
            <option value="l">Liter(s)</option>
            <option value="cl">Centiliter(s)</option>
        </select>
    </p>
    <p>
        <label for="id_ingredient">Ingredient:</label> <select name="ingredient" required="" id="id_ingredient">
        <option value="" selected="">---------</option>
        <option value="1">Carrot</option>
        <option value="2">Potato</option>
        <option value="3">Water</option>
        <option value="4">Juice</option>

        </select>
    </p>
    <button type="submit" class="save btn btn-default">Save</button>
</form>

0 个答案:

没有答案