繁体   English   中英

通过jQuery` .ajax`提交后,显示Django表单的验证错误

[英]Display validation errors of a Django Form after submitting via jQuery `.ajax`

一般

我在模态中有一个表单。 模态内容(表单)由jQuery .load通过$('.modal-content').load('{% url 'edito' q.id %}'); Django通过此URL通过render_to_string返回.modal-content的HTML。

问题

如果我提交表单,我想在.modal-content.modal-content表单,如果发生验证错误,否则关闭模式。

如果存在验证错误,我得到的只是关闭模态独立工作或者我没有样式重定向到表单action={% url 'edito' q.id %} ,因为django只返回.modal-content的内容.modal-content

edito.html(模态内容,以.modal-content

<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">&times;</button>
  <h4 class="modal-title">Edit</h4>
</div>
<div class="modal-body">
  <form id="myForm" method="post" class="form" role="form" action="{% url 'edito' q_id %}">{% csrf_token %}
    <fieldset>
      {% for field in form %}
        {% if field.errors %}
          <div class="form-group has-error">
            <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
            <input class="form-control" id="{{ field.id_for_label }}" name="{{ field.html_name }}" placeholder="{{ field.field.widget.attrs.placeholder }}" type="text" />
            <span class="help-block">{% for error in  field.errors %}{{ error }}<br />{% endfor %}</span>
          </div>
        {% else %}
          <div class="form-group">
            <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
            <input class="form-control" id="{{ field.id_for_label }}" name="{{ field.html_name }}" placeholder="{{ field.field.widget.attrs.placeholder }}" type="text" value="{{ field.value }}" />
          </div>
        {% endif %}
      {% endfor %}
    </fieldset>
    <div class="form-actions">
      <input id="sendMe" type="submit" class="btn btn-primary" value="Edit" />
      <!--<a class="btn btn-warning" href="../..">Cancel</a>-->
    </div>
    </form>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>

<script type="text/javascript">
  $('#myForm').submit(function() { // catch the form's submit event
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            $('.modal-content').html(response); // should check if with validation errors
            $('#myModal').modal("hide"); 
        },
    });
    return false;
  });
</script>

无论如何,这是模态关闭的那个。 如果我使用以下脚本,我将被重定向到render_to_string返回的无样式HTML网站。

替代脚本部分

<script type="text/javascript">
  $('#myForm').live('submit', function() {
      $.ajax({ 
          type: $(this).attr('method'), 
          url: this.action, 
          data: $(this).serialize(),
          context: this,
          success: function(data, status) {
              $('#myModalContent').html(data);
          }
      });
      return false;
  });
</script>

views.py

def edito(request, **kwargs):
    if request.method == 'POST':
        instance = Question.objects.get(id=kwargs.get("question_id"))
        form = QuestionCreationForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            return HttpResponse(
                render_to_string(
                    "edito.html",
                    {'q_id': kwargs.get("question_id"), },
                    request=request,
                )
            )
        else:
            return HttpResponse(
                render_to_string(
                    "edito.html",
                    {
                        'q_id': kwargs.get("question_id"),
                        'form': form,
                    },
                    request=request,
                )
            )
    else:
        q = Question.objects.get(id=kwargs.get("question_id"))
        prefilled_data = {
            ...
        }
        form = QuestionCreationForm(initial=prefilled_data)
        return HttpResponse(
            render_to_string(
                "edito.html",
                {
                    'form': form,
                    'q_id': kwargs.get("question_id")
                },
                request=request,
            )
        )

main.html(模态所在的位置)

<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">
    <div id="myModalContent" class="modal-content">
    </div>
  </div>
</div>

<a href="{% url 'edito' q.id %}" onclick="$('.modal-content').load('{% url 'edito' q.id %}');" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-edit"></span></a>

Form.errors.as_json非常适合这种情况。

返回序列化为JSON的错误。

以下是调用as_json()方法后链接到上面的页面的示例。

{"sender": [{"message": "Enter a valid email address.",
 "code": "invalid"}], "subject": [{"message": "This field is
> required.", "code": "required"}]}

当表单提交并且无效时,您的django表单处理程序应该发送此JSON响应。 然后你的javascript可以遍历列表并标记相应的表单字段。

如果表单提交成功,你的django代码应返回类似{'status':'ok'}的内容,然后你的javascript可以关闭模​​态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM