根据另一个atribute(Django)禁用选项charField选项

2024-10-03 04:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有以下几点型号.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')

所以我想知道是否有一种方法可以根据所选的配料筛选出可用的数量单位。 我将试着用一个例子来说明:假设我选择添加土豆,土豆的成本单位是“g”,那么我想让“kg”和“g”成为quantityUnit的唯一选择。这是个好例子吗?如果不够清楚的话,我可以试着想出更好的办法。 不管怎样,有可能做这样的事吗?谢谢。你知道吗

更新: 表单.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>

Tags: nameformiddefaultvaluemodelsrecipelabel