如何在Django中实现从属下拉列表

时间:2019-08-18 08:19:08

标签: python django django-forms

我有一个包含食物名称及其价格的食物表。每当用户从模板表单中选择食物时,与其相关的价格应自动显示在表单中。我该怎么办??

models.py

class Food(models.Model):
    name = models.CharField(max_length = 100)
    price = models.IntegerField()

class Payment(models.Model):
    food = models.ForeignKey(Food, on_delete=models.CASCADE)

forms.py

class PaymentForm(forms.ModelForm):
    class Meta:
        model = Payment
        fields = '__all__'

views.py

def payment_details(request):
    amounts = Food.objects.all()

    context={
        'amounts' : amounts
            }


    return render(request, 'app_name/payment.html',context)

模板

<label>Select the Food</label>
     <select name="name" class="form-control" required>
           {% for amount in amounts %}
            <option value="{{amount.food.name}}">{{amount.food.name}}</option>
           {% endfor %}
     </select>
<label>Amount You Need to Pay</label>

<select name="name" class="form-control" required>
        {% for amount in amounts %}
           <option value="{{amount.food.price}}">{{amount.food.price}}</option>
        {% endfor %}
</select>

1 个答案:

答案 0 :(得分:1)

首先:在模型文件中,更改

model.Models to models.Model

像其他人一样。在进行更改之前,您将无法使用它。

第二个:当您尝试在模板中访问此查询集时,您将必须这样访问它:

{% for amount in amounts %}
{{ amount.price }}
{{ amount.name }}
{% endfor %}

第三:“从属下拉菜单”

<label>Select the Food</label>
<select name="name" class="form-control" required>
    {% for amount in amounts %}
       <option value="{{amount.food.name}}">Food: {{ amount.name }}, Price: {{ amount.price }}</option>
    {% endfor %}
</select>

将查询集传递给模板时,您可以在同一for循环中访问两个表单字段。似乎最好的选择是将这两个选项都放在一个下拉菜单中,因为这暗示着它们是相互依赖的。

希望能帮助您! :)