无效的表单未以模态返回JSON /表单字段错误

时间:2018-07-09 15:47:52

标签: javascript jquery ajax django

我正在Django中尝试将模式形式与AJAX一起使用,因此我知道了,以便模式显示形式内容,并且在没有形式错误的情况下它可以正确地提交/工作,但是在存在形式错误的情况下,它可以正确地提交/工作似乎没有将响应发送回AJAX(至少这是我的猜测)。出现表单错误时,它将刷新页面并在新页面(而不是模式窗口)中显示表单,并且表单将保存用户输入,并且将显示表单字段错误。如果这听起来令人困惑,请告诉我,我可以上传一些截图以说明问题。

这是我的jQuery / AJAX ...

<script>
function apply_form_field_error(fieldname, error) {
    var input = $("#id_" + fieldname),
        container = $("#div_id_" + fieldname),
        error_msg = $("<span />").addClass("help-inline ajax-error").text(error[0]);

    container.addClass("error");
    error_msg.insertAfter(input);
}

function clear_form_field_errors(form) {
    $(".ajax-error", $(form)).remove();
    $(".error", $(form)).removeClass("error");
}

function django_message(msg, level) {
    var levels = {
        warning: 'alert',
        error: 'error',
        success: 'success',
        info: 'info'
    },
    source = $('#message_template').html(),
    template = Handlebars.compile(source),
    context = {
        'tags': levels[level],
        'message': msg
    },
    html = template(context);

    $("#message_area").append(html);
}

function django_block_message(msg, level) {
    var source = $("#message_block_template").html(),
        template = Handlebars.compile(source),
        context = {level: level, body: msg},
        html = template(context);

    $("#message_area").append(html);
}

var formAjaxSubmit = function(form, modal) {
   $(form).on("submit", "#create_form", function(e) {
    e.preventDefault();
    var self = $(this),
        url = self.attr("action"),
        ajax_req = $.ajax({
            url: url,
            type: "POST",
            data: {
                name: self.find("#id_name").val()
            },
            success: function(data, textStatus, jqXHR) {
              $(modal).modal('toggle');
              alert("Design created!");  // <-- This is just a placeholder for now for testing
              window.location.replace("{% url 'engineering:gaas_wafer_design_list' %}");
            },
            error: function(data, textStatus, jqXHR) {
                var errors = $.parseJSON(data.responseText);
                $.each(errors, function(index, value) {
                    if (index === "__all__") {
                        django_message(value[0], "error");
                    } else {
                        apply_form_field_error(index, value);
                    }
                });
            }
        });
    });
}
$('#create-button').click(function() {
   $('#form-modal-body').load('create/', function () {
       formAjaxSubmit('#form-modal-body form', '#form-modal');
   });
});

这是我的gaas_wafer_design_form_inner.html(加载到模式内容中的表单)...

{% load widget_tweaks %}
<form id="create_form" method="post" action="{% url 'engineering:gaas_wafer_design_create' %}">{% csrf_token %}
  <div class="row">
    <div class="form-group col-sm-12">
      <div class="form-group">
        <label for="{{ form.design_ui.id_for_label }}"><b>Design UI</b></label>
        {% render_field form.design_ui class+="form-control" %}
        {{ form.design_ui.errors }}
      </div>
    </div>
  </div>
  <!--/.row-->
  <div class="row">
    <div class="form-group col-sm-4">
      <div class="form-group">
        <label for="{{ form.emitting.id_for_label }}"><b>Emitting</b></label>
        {% render_field form.emitting class+="form-control" %}
        {{ form.emitting.errors }}
      </div>
    </div>
    <div class="form-group col-sm-4">
      <div class="form-group">
        <label for="{{ form.contact_location.id_for_label }}"><b>Contact Location</b></label>
        {% render_field form.contact_location class+="form-control" %}
        {{ form.contact_location.errors }}
      </div>
    </div>
    <div class="form-group col-sm-4">
      <div class="form-group">
        <label for="{{ form.optical_power.id_for_label }}">Optical Power</label>
        {% render_field form.optical_power class+="form-control" %}
        {{ form.optical_power.errors }}
      </div>
    </div>
  </div>
  <!--/.row-->
  <div class="row">
    <div class="form-group col-sm-6">
      <div class="form-group">
        <label for="{{ form.design_date.id_for_label }}"><b>Design Date</b></label>
        {% render_field form.design_date class+="form-control" %}
        {{ form.design_date.errors }}
      </div>
    </div>
    <div class="form-group col-sm-6">
      <div class="form-group">
        <label for="{{ form.designer.id_for_label }}"><b>Designer</b></label>
        {% render_field form.designer class+="form-control" %}
        {{ form.designer.errors }}
      </div>
    </div>
  </div>
  <!--/.row-->
  <div class="row">
    <div class="form-group col-sm-6">
      <div class="form-group">
        <label for="{{ form.designer_ui.id_for_label }}">Designer UI</label>
        {% render_field form.designer_ui class+="form-control" %}
        {{ form.designer_ui.errors }}
      </div>
    </div>
    <div class="form-group col-sm-6">
      <div class="form-group">
        <label for="{{ form.design_document.id_for_label }}">Design Document</label>
        {% render_field form.design_document class+="form-control" %}
        {{ form.design_document.errors }}
      </div>
    </div>
  </div>
  <!--/.row-->
  <div class="row">
    <div class="form-group col-sm-4">
      <div class="form-group" style="float:left;">
        <label for="{{ form.in_trash.id_for_label }}">In Trash</label>
        {% render_field form.in_trash class+="form-control" %}
        {{ form.in_trash.errors }}
      </div>
    </div>
    <div class="form-group col-sm-4">
      <div class="form-group">
        <label for="{{ form.inactive_date.id_for_label }}">Inactive Date</label>
        {% render_field form.inactive_date class+="form-control" %}
        {{ form.inactive_date.errors }}
      </div>
    </div>

  </div>
  <!--/.row-->
  <div class="row">
    <div class="form-group col-sm-12">
      <div class="form-group">
        <label for="{{ form.notes.id_for_label }}">Notes</label>
        {% render_field form.notes class+="form-control" %}
        {{ form.notes.errors }}
      </div>
    </div>
  </div>
  <br />
  <!--/.row-->
  <span style="float:right;">
    <input type="submit" class="btn btn-primary" value="Save" />
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
  </span>
</form>

这是我的Django视图...

class GaasWaferDesignCreateView(LoginRequiredMixin, SuccessMessageMixin, 

AjaxTemplateMixin, CreateView):
    template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form_inner.html'
    ajax_template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form_inner.html'
    form_class = GaasWaferDesignForm
    form = GaasWaferDesignForm()
    model = GaasWaferDesign
    success_url = reverse_lazy('engineering:gaas_wafer_design_list')
    success_message = "yes!"

    def form_valid(self, form):
        """
        If the request is ajax, save the form and return a json response.
        Otherwise return super as expected.
        """
        if self.request.is_ajax():
            self.object = form.save(commit=False)
            self.object.created_by = self.request.user
            self.object = form.save()
            return HttpResponse(json.dumps("success"),
                content_type="application/json")

        else:
            object = form.save(commit=False)
            object.created_by = self.request.user
            object.save()

        return super(GaasWaferDesignCreateView, self).form_valid(form)

    def form_invalid(self, form):
        """
        We haz errors in the form. If ajax, return them as json.
        Otherwise, proceed as normal.
        """
        if self.request.is_ajax():
            return HttpResponseBadRequest(json.dumps(form.errors),
                content_type="application/json")
        return super(GaasWaferDesignCreateView, self).form_invalid(form)

非常感谢您能提供的帮助!

0 个答案:

没有答案