【问题标题】:Keep data of fields after submit a form with an error on django在 django 上提交有错误的表单后保留字段数据
【发布时间】:2017-07-29 23:58:12
【问题描述】:

在我使用 django 提交一个错误的表单后,表单的所有字段都被清除。我想保留字段上的信息,因为这将有助于用户提交数据。

这是我对应用程序的views.py:

def new(request):
    context = {}
    if request.method == 'POST':
        form = NewSubject(request.POST)
        if form.is_valid():
            context['is_valid'] = True
            form.save()
            form = NewSubject()
        else:
            context['is_valid'] = False
    else:
        form = NewSubject()

    context['form'] = form
    return render(request, 'subjects/new.html', context)

【问题讨论】:

  • 在发送到服务器之前,最好在客户端使用 JavaScript 进行验证
  • 在代码中如果表单无效表单数据没有清理,可能是你在模板上做了一些事情。
  • AK45,我还没有尝试使用 JavaScript 进行验证,但如果我可以在服务器上进行验证,对我来说会更有趣,因为我使用 slug 进行了额外的验证。 Bear Brown,我对模板进行了一些修改,我没有使用原始的 Django 表单,而是使用我自己的风格化的个性化表单。

标签: python django forms


【解决方案1】:

我建议你使用ajax。因为我们可以编写不同的情况来处理提交是否成功。如果成功 input.val('') else 显示错误和不干净的输入字段。

$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!")  // sanity check
create_post();)};   function create_post() {
console.log("create post is working!")
$.ajax({
    url : "/lrequestConfirmed/", // the endpoint
    type : "POST", // http method
    data : {
      datef: $('#datepicker').val(),
      type: $('#type').val(),
      reason: $('#reason').val()

    }, // data sent with the post request

    // handle a successful response
    success : function(json) {
        $('#datepicker').val(''); // remove the value from the input
        $('#reason').val(''); 
        $('#results').html("<div class='alert alert-success alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong> Your request has been recored</div>");
        console.log(json); // log the returned json to the console
        console.log("success"); // another sanity check
    },

    // handle a non-successful response
    error : function(xhr,errmsg,err) {
        $('#results').html("<div class='alert alert-danger alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Oops!</strong> Something went wrong</div>"); // add the error to the dom
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
});

【讨论】:

    【解决方案2】:

    就像 Bear Brown 说的,数据在出错后保留在字段中,但是我没有使用 Django 的纯表单,我需要做一些调整。 我使用原始 Django 表单创建了一个隐藏的 div,并使用 JavaScript 为我的字段传递了数据。 这是我如何进行的示例:

    原始 Django 表单的 id 基于表单上的字段名称。因此,如果您在 forms.py 中定义字段的名称,如“name”,则该字段的 id 将为“id_name”:

    function error(){ document.getElementById('name').value = document.getElementById('id_name').value;}
    

    这就是表单上的字段被调用的方式。渲染后,它将包含表单字段的数据并有一个 id,所以我通过 id ("id_name") 获取元素并为我的个性化字段传输信息。

    <div style="display: none;">
       {{ form.name }}
    </div>
    

    这是我风格化的字段,用户将在其中编辑数据并进行自己的修改。

    <input id="name" class="form-control" type="text" maxlength="100" name="name" placeholder="Ex.: Metemática" onchange="slugDefine()" onkeyup="slugDefine()" /><br>
    

    感谢您的帮助!

    【讨论】:

    • 您可以为forms.py中的输入添加样式,如下所示:name = forms.CharField(label='Disciplina', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Disciplina', 'onchange': 'slugDefine()', 'onkeyup': 'slugDefine()'}))
    猜你喜欢
    • 1970-01-01
    • 2015-07-01
    • 2013-08-28
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多