2013-09-15 3 views
3

Я хочу обновить форму в событии изменения в раскрывающемся списке.обновить форму django с jquery/ajax

Вот мое мнение:

from django.utils import simplejson 
response_dic={} 
#drop down list 
actToValidateId=add_form.cleaned_data['actsToValidate'].pk 
act=ActsIdsModel.objects.get(id=actToValidateId) 
ids_form = ActsIdsForm(instance=act) 

ids_form_dic={} 
for field in ids_form.fields: 
    ids_form_dic[field]=getattr(act, field) 
response_dic['ids_form']=ids_form_dic 
response_dic['act']=dict([(attr, getattr(act, attr)) for attr in [f.name for f in act._meta.fields]]) 

return HttpResponse(simplejson.dumps(response_dic), mimetype="application/json") 

Вот Javascript код:

function display_act_ids(choice) 
{ 
    $form=$('#act_ids_form'); 
    var form_data = $form.serialize(); 
    $.ajax 
    ({ 
     url: $form.attr('action'), 
     type: 'POST', 
     dataType: 'json', 
     data: form_data, 
     success: function(result) 
     { 
      alert(result.ids_form.fileNoCelex); 
     } 
    }); 

    //don't submit the form 
    return false; 
} 

Теперь две проблемы:

1/Если я хочу, чтобы присвоить соответствующие значения для моего формы, я могу обновить функцию успеха, как показано ниже:

$("#myfield").val(result.ids_form.myfield); 

Но что делать, если у меня есть много полей для заполнения? Есть ли функция, чтобы сделать это автоматически? Может быть, цикл будет ...

2/Моя основная проблема: Я использую экземпляр act (и другие переменные) во многих местах в своем шаблоне (не в моей форме). Например:

{% if act.councilPath %} 
    <div class="row-fluid">{{ act.councilPath }}</div> 
{% endif %} 

Таким образом, невозможно использовать ajax. Это означает, что я должен переписать свой шаблон, чтобы он работал. Например:

<div id="council_path" class="row-fluid"></div> 

И в моей функции успеха:

$("#council_path").html(result.act.councilPath); 

Это было бы очень долго, чтобы обновить. Есть ли лучший способ сделать, например, ajax «post and load»?

Скажите, пожалуйста, если я не понимаю.

ответ

6

Чтобы обновить форму Джанго с JQuery/Ajax, вот мой метод ... Три ключевых момента: положить шаблон формы в отдельном HTML-страницы, использование render_to_string на ваш взгляд, и отправить ответ HTML Аяксу.

index.html страница:

{% extends "base.html" %} 

{% block content %} 
    <!-- you can put here everything that doesn't need to be updated (text, css inclusion, etc.) --> 
    <!-- act validation form --> 
    <form id="act_ids_form" class="form-inline" action="{% url act_ids %}" method="post">{% csrf_token %} 
      <!-- drop down list --> 
      <div id="actsToValidateChoice" class="fieldWrapper"> 
        {{ add_form.actsToValidate.errors }} 
        {{ add_form.actsToValidate }} 
      </div> 
      <!-- div to update the part of the form that must be updated --> 
      <div id="act_ids_form_div">{% include form_template %}</div> 
    </form> 

{% endblock %} 

forms.py:

class ActsAddForm(forms.Form): 
     #drop down list  
     actsToValidate=forms.ModelChoiceField(queryset=ActsIdsModel.objects.filter(validated=0), empty_label="Select an act to validate", widget=forms.Select(attrs={'onchange': 'display_act_ids()'})) 

form.html:

<!-- act ids form --> 
<!-- put here everything that must be updated on the change of your drop down list --> 
<div class="row-fluid">{{ ids_form.non_field_errors }}</div> 

{% if act.councilPath %} 
     <div class="row-fluid"><a class="info_msg" href="{{act.councilPath}}" target="_blank">{{ displayName.councilPath }}</a></div> 
{% endif %} 

<table class="table table-bordered table-hover table-condensed span12"> 
     <tr> 
      {% for field in ids_form %} 
       <td> 
        <div class="fieldWrapper"> 
         {{ field.errors }} 
         {{ field }} 
        </div> 
       </td> 
      {% endfor %} 
     </tr> 
</table> 

urls.py:

from django.conf.urls import patterns, url 

urlpatterns = patterns('actsIdsValidation.views', 
    url(r'^/?$', 'act_ids', name='act_ids'), 
    url(r'^form.html$', 'act_ids', name='act_ids'), 
) 

views.py:

def act_ids(request): 
    response_dic={} 
    #html page of the form 
    form_template='actsIdsValidation/form.html' 

    if request.method == 'POST': 
     #if drop down list not empty 
     if request.POST["actsToValidate"]!="": 
      #add form: contains the drop down list only 
      add_form = ActsAddForm(request.POST); 
      actToValidateId=request.POST["actsToValidate"].pk 
      act=ActsIdsModel.objects.get(id=actToValidateId) 
      ids_form = ActsIdsForm(instance=act) 
      response_dic['ids_form']=ids_form 
      response_dic['act']=act 

      return HttpResponse(render_to_string(form_template, response_dic, RequestContext(request))) 

    #GET 
    #unbound ids_form 
    response_dic['ids_form'] = ActsIdsForm() 
    response_dic['add_form'] = ActsAddForm() 
    response_dic['form_template'] = form_template 
    return render_to_response('actsIdsValidation/index.html', response_dic, context_instance=RequestContext(request)) 

Ajax вызов:

function display_act_ids() 
{ 
    $form=$('#act_ids_form'); 
    var datastring = $form.serialize(); 
    $.ajax({ 
     type: "POST", 
     url: $form.attr('action'), 
     dataType: 'html', 
     data: datastring, 
     success: function(result) 
     { 
      /* The div contains now the updated form */ 
      $('#act_ids_form_div').html(result); 
     } 
    }); 

    //don't submit the form 
    return false; 
} 

Вуаля!

Смежные вопросы