首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过jQuery `.ajax`提交Django表单后显示验证错误

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

Stack Overflow用户
提问于 2016-05-07 09:58:28
回答 1查看 3.4K关注 0票数 1

一般信息

我在一个模态里面有一个表格。modals内容(表单)由jQuery .load通过$('.modal-content').load('{% url 'edito' q.id %}');加载。Django通过字符串返回.modal-content的这个URL。

问题

如果我提交表单,如果出现验证错误,我想在.modal-content中重新修改表单,否则关闭该模式。

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

代码

edito.html (modals内容,在.modal-content中)

代码语言:javascript
复制
<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站点。

替代脚本部分

代码语言:javascript
复制
<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

代码语言:javascript
复制
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 (模态在其中)

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-07 10:09:25

json非常适合这一点。

返回序列化为JSON的错误。

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

代码语言:javascript
复制
{"sender": [{"message": "Enter a valid email address.",
 "code": "invalid"}], "subject": [{"message": "This field is
> required.", "code": "required"}]}

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37087068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档