简体   繁体   中英

How to Implement Dependent Dropdown list in Django

I have a Food table which contains Food name and it's price.Whenever a user selects a food from template form,the price associated with it should automatically be displayed in the form. How can I do it ??

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)

template

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

First: In your models file, change

model.Models to models.Model

like your other one. You won't be able to use it until you make that change.

Second: When you try to access this queryset in the template you will have to access it as such:

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

Third: "Dependent Drop down menu"

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

When you pass the queryset to the template you can access both form fields in the same for loop. It seems that the best option would be to put both options in a drop down menu because it implies that they are dependent.

HOPE THAT HELPS! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM