Take the 2-minute tour ×

I have a form that triggers an ajax request to a view after the user tabs out of the 'address' field. It retrieves the zip code and then populates pickups with the same zip. The problem is that if there are any form errors is that the drop down with the results I generate from my get_pickups view is lost. How can I keep it so that even on form errors it will keep the results

def get_pickups(request):   

    if request.is_ajax():   
        # Get available pickup dates based upon zip code
        zip = request.POST.get('zip',None)
        routes = Route.objects.filter(zip=zip).values_list('route',flat=True)       

        two_days_from_today = date.today() + relativedelta(days = +2)

        submitted_from = request.POST.get('template',None)
        if submitted_from == '/donate/':
            template = 'donate_form.html'
            results = PickupSchedule.objects.filter(route__in=routes,date__gt = two_days_from_today, current_count__lt=F('specials')).order_by('route','date')
            template = 'donate-external.html'

        return render_to_response(template,{ 'zip':zip, 'results':results}, context_instance=RequestContext(request))

my ajax call via jquery:

        type: "POST",
        data: {
        'zip': zip,
        success: function(data){            

                results = $(data).find('#results').html()           
                $("#id_pickup_date").replaceWith("<span>" + results + "</span >");      
        error: function(){
share|improve this question
Can you give an example of "form errors"? e.g. bad zip? –  Jeff Oct 12 '12 at 1:07
It's not necessarily an error with the zip code but if there is any other error on the form such as a required field not entered. –  Austin Oct 12 '12 at 1:13

1 Answer 1

up vote 1 down vote accepted

I can think of two approaches:

  1. Attach the contents of that dropdown to your POST and return it along with the data in the other fields if there's an error (downside: added complexity in server code)
  2. Use javascript to check if that zip field is non-empty on page load/reload. If it's not empty (e.g. error return), call your ajax lookup for that dropdown (downside: duplicate calculations)

I'd use whichever solution you feel most skilled with (python/django or javascript)

share|improve this answer
After submitting my question I realized I could do it the same way you mention in solution 2. I would have preferred to do this in python/django but I just checked on page load if the field length was greater than zero and then made the same ajax call. Thanks –  Austin Oct 12 '12 at 12:23

Your Answer


