使用模板中的数据动态填充 Django 表单

populating a django form dynamically with the data from the template

我有一个django视图如下:

@login_required(login_url="login/")
def review(request):
    table = DummyTable(DummyModel.objects.all())        
    form = DummyForm()        
    return render(request, 'review.html', {'reviews': table, 'DummyForm': form})

我正在传递一个默认值 DummyForm,它是一个 django-crispy-form(尽管我认为这与问题无关)并且我需要根据用户点击的记录来填充它在。表格本身看起来像:

from .models import DummyModel
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit
from django.forms import ModelForm


class DummyForm(ModelForm):

    class Meta:
        model = DummyModel
        fields = ['name', 'description', 'time_points']

    def __init__(self, *args, **kwargs):
        super(DummyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-10'
        self.helper.layout = Layout(
            Field('name'),
            Field('description'),
            Field('time_points'),
            ButtonHolder(
                Submit('submit', 'Submit', css_class='button white')
            ))

现在,我有一个 javascript 函数,当用户单击某些链接并接收我要在表单中呈现的记录的主键时调用该函数。目前情况如下:

<script>
        function EditDialog(pk) {
            // Currently doing nothing with the primary key
            // Is there a way to initialise the form with data using this key?
            $( "#dialog" ).modal({width: 500, height: 500});
            return false;
        }
    </script>

这个JS函数初始化表单为:

<div id="dialog" class="modal" title="Edit" style="display:none">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <!-- Can I pass the primary key variable here??? -->
          {% crispy DummyForm %}
        </div>
      </div>
    </div>
  </div>

除了我在屏幕上显示的是一个空表格外,一切都很好。 JS函数中如何将表单绑定到主键给定的记录

通常,在视图中我可以执行以下操作:

# As an example, just bind to the record with primary key=1
rec = DummyModel.objects.filter(pk=1).first()
form = DummyForm(model_to_dict(rec))

所以,在某种程度上,我需要在我的模板中做一些类似的事情。

在您的 JS 中,您可以向 Django 视图发出 AJAX 请求,该请求将 return 表单填充值。

JS 看起来像:

<script>
    function EditDialog(pk) {
       //ajax request to retrieve the populated form
       $.ajax({
          url: '/url/to/the/view/which/returns/the/populated/form',
          method: 'GET',
          data: {
             pk: pk
          },
          success: function(formHtml){
             //place the populated form HTML in the modal body
             $('.modal-body').html(formHtml);
             $( "#dialog" ).modal({width: 500, height: 500});
          },
          dataType: 'html'
       });

       return false;
    }
</script>

处理 AJAX 请求的视图如下所示:

@login_required(login_url="login/")
def populate_form(request):
   pk = request.GET.get('pk')
   rec = DummyModel.objects.get(pk=pk)
   form = DummyForm(model_to_dict(rec)) 

   return render(request, 'form.html', {'DummyForm': form})

form.html 模板将是一个非常简单的模板,不会扩展您的基本模板,只会包含:

{% crispy DummyForm %}

请注意,我保持代码简单,您必须在 populate_form 视图中添加对 pk 的验证,并处理对 populate_form 的未验证 AJAX 调用(例如:a页面打开时间长,session过期点击编辑按钮的用户)