views:

55

answers:

1

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>
+1  A: 

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

$.post(URL_TO_YOUR_VIEW, {charge: charge}, function(data) {
    //here you can use jquery to insert values to the html like this:
    $('#id_ammount').val(data.ammount);
    //also update extended membership you can sth like this:
    if(data.extended_membership)
    {
         $('#id_extended_membership').attr('checked', 'checked');
    }   
    else
    {
         $('#id_extended_membership').removeAttr('checked');
    }
}, "json");

On the server side you need to add view to handle ajax call. It might look similar to this:

def magic_view_name(request):
    if request.is_ajax() and request.method == 'POST':
        charge = request.POST['charge']
        ammount = #get ammount somehow
        extended_memebership = #get ext. memebership somehow
        data = simplejson.dumps({'ammount': ammount,
                                 'extended_membership': extended_membership}, 
                                encoding="utf-8", 
                                ensure_ascii=False)
        return HttpResponse(data, mimetype="application/javascript")

    return HttpResponse(u'No data for you')

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.

Lukasz Dziedzia
@Dzida....thnx...this is exactly what I wanted :) I'm a bit new to this AJAX stuff so I guess that's where I got stuck.
Stephen
Cool. Glad i could help you. AJAX with jquery and django is quite easy. Code I posted here(with minor modifications) usually covers most of my needs. If you are new to jquery and ajax take a look here: http://api.jquery.com/category/ajax/ . .load() function is also very useful
Lukasz Dziedzia