我有一个表单,它会在用户从“地址”字段中跳出后触发对视图的 ajax 请求。它检索邮政编码,然后使用相同的邮政编码填充取件。问题是,如果有任何表单错误,我从 get_pickups 视图生成的结果下拉列表会丢失。我怎样才能保留它,以便即使出现表单错误它也会保留结果
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')
else:
template = 'donate-external.html'
results = PickupSchedule.objects.filter(route__in=routes,date__gt = two_days_from_today, current_count__lt=F('specials')).order_by('date')
return render_to_response(template,{ 'zip':zip, 'results':results}, context_instance=RequestContext(request))
我通过 jquery 的 ajax 调用:
$.ajax({
type: "POST",
url:"/get_pickups/",
data: {
'zip': zip,
'template':template
},
success: function(data){
results = $(data).find('#results').html()
$("#id_pickup_date").replaceWith("<span>" + results + "</span >");
},
error: function(){
alert("Error");
}