2

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

1 Answer 1

1

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! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.