I have this class in my model:
class ServiceCharge(models.Model):
name = models.CharField(max_length=30)
amount = models.PositiveIntegerField()
extends_membership = models.BooleanField(default=False)
def __unicode__(self):
return str(self.name)
What I want to have is in the form for charging users a service charge, when a charge is selected from the dropdown menu, the two values for amount and extends_membership are updated on the form depending on the selected charge.
My forms.py:
class vModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "%s" % obj.name
class PayServiceChargeForm(PaymentsForm):
service_charge = vModelChoiceField(queryset=ServiceCharge.objects.all(),
empty_label=" ")
class Meta(PaymentsForm.Meta):
exclude = ('member', 'payment_type', 'transacted_by', 'description')
Then the form template:
<table border="0">
<tr>
<td><strong>{% trans "Service Charge" %}</strong></td>
<td>{{ form.service_charge }}</td>
<td><strong>{% trans "Extends Membership" %}</strong></td>
<td>{{ form.extends_membership }}</td>
</tr>
<tr>
<td valign="top"><strong>{% trans "Expiry Date" %}</strong></td>
<td valign="top">{{ form.expiry_date }}</td>
<td valign="top"><strong>{% trans "Amount" %}</strong></td>
<td>{{ form.amount }}</td>
</tr>
</table>
I was trying out some jQuery but I got stuck after getting the currently selected charge:
<script type="text/javascript">
$(document).ready(function(){
$("#id_service_charge").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#id_service_charge option:selected");
var output = "";
if(selected.val() != 0){
charge = selected.val();
.... (update values) ....
}
}
</script>
I would do this by making AJAX call to the server for amount and extended_membership associated with selected charge and then update html fields wtih retrieved data.
To do this you need to add something like this to onSelectChange()
On the server side you need to add view to handle ajax call. It might look similar to this:
You need also add proper url pattern to your urls.py and that should work.
Hope it helps you.
BTW, I guess that you do not want to allow users to change price for selected ServiceCharge. If so you can show them as readonly values not as editable form fields.