【问题标题】:validate and submit Django form (django-crispy-forms) with Ajax使用 Ajax 验证并提交 Django 表单 (django-crispy-forms)
【发布时间】:2018-07-22 00:09:26
【问题描述】:

我是 django 和网络开发的新手。我需要帮助使用 Ajax 提交 Django 表单(使用 django-crispy-forms)我该怎么做:

  1. 验证输入

  2. 提交而不重新加载

  3. 验证失败时显示错误

现在我可以提交表单并将条目保存到数据库中,但在此过程中重新加载整个页面。 我在下面包含了我的代码的相关 sn-ps

//forms.py

class SubscriptionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SubscriptionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.template_pack = 'bootstrap3'
        self.helper.form_tag        = True
        self.helper.form_id         = 'sub-form-1'
        self.helper.form_class      = 'form-inline'
        self.helper.field_template  = 'bootstrap3/inline_field.html'
        self.helper.layout          = Layout(

            Div(Div(css_class='sub-form-notifications-content'),
                css_class='sub-form-notifications'),

            InlineField('name',  id='subName'),
            InlineField('email', id='subEmail'),

            FormActions(Submit('submit', 'Notify me', css_class='form-control')),

    )

class Meta:
    model = Sub
    fields = "__all__"

def clean_email(self):
    """
   Validate that the supplied email address is unique for the
   site.

   """
    if User.objects.filter(email__iexact=self.cleaned_data['email']):
        raise forms.ValidationError(
            _("This email address is already in use. Please supply a different email address."))
    return self.cleaned_data['email']

//views.py

from django.shortcuts import render, redirect
from .forms import SubscriptionForm
from .models import Sub


def index(request):
    if request.method == 'POST':
        sub_form = SubscriptionForm(request.POST)
        if sub_form.is_valid():
            sub_form.save()
            # return redirect('landing:landing')

    else:
        sub_form = SubscriptionForm()
    return render(request, 'landing/index.html', {'sub-form': sub_form})

// 模板

...
         {% crispy sub-form %}
...

// 呈现 HTML 格式

<form class="form-inline" id="sub-form-1" method="post">
    <input type='hidden' name='csrfmiddlewaretoken'
           value='tdiucOssKfKHaF7k9FwTbgr6hbi1TwIsJyaozhTHFTKeGlphtzUbYcqf4Qtcetre'/>
    <div class="sub-form-notifications">
        <div class="sub-form-notifications-content">
        </div>
    </div>
    <div id="div_id_name" class="form-group">
        <label for="subName" class="sr-only requiredField">Name</label>
        <input type="text" name="name" maxlength="30" required placeholder="Name"
           class="textinput textInput form-control" id="subName"/>
    </div>
    <div id="div_id_email" class="form-group"><label for="subEmail" class="sr-only requiredField">Email address</label>
        <input type="email" name="email" maxlength="60" required placeholder="Email address"
           class="emailinput form-control" id="subEmail"/>
    </div>
    <div class="form-group">
        <div class="controls ">
            <input type="submit" name="submit" value="Notify me" class="btn btn-primary" id="submit-id-sub-form"/>
        </div>
    </div>
</form>

【问题讨论】:

  • 请在此处发布呈现的表单,因为如果您想要基于 AJAX 的解决方案,我们需要查看呈现的 HTML。
  • @Krystofee 我编辑了帖子以包含呈现的 HTML,谢谢

标签: python jquery ajax django django-forms


【解决方案1】:

我会尝试让您了解如何轻松做到这一点。

将 onsubmit 事件监听器添加到表单和错误块 e. G。在将显示错误的表单下方。

模板

<form class="form-inline" id="sub-form-1" method="post" onsubmit="sendData();">
    ...
</form>
<div class="error-block">
    <!-- Here is the space for errors -->
</div>

现在处理程序会将数据发送到要验证和保存的视图

<script>

    function sendData(e) {
        e.preventDefault(); // don not refresh the page

        var form_data = {
            name: $('input[name="name"]').val(),
            ... other field values ...
        }

        $.ajax({
            url: "{% url 'url-you-want-send-form-to' %}",
            method: "POST",
            data: form_data,
            success: function(response) {
                // here are the success data in the response
                // you can redirect the user or anything else
                //window.location.replace("{% url 'success-url' %}");
            },
            error: function(response) {
                // here are the errors which you can append to .error-block
                //$('.error-block').html(response);
            }
        })

    }

</script>

在视图中,您将收到与提交表单相同的表单中的数据,但您不必将整个模板呈现给响应,而只需将验证表单中的错误呈现,因此您将发送的视图您的 ajax POST 请求必须与呈现表单的视图不同。您可以创建另一个来处理它。

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2020-08-28
    • 2017-07-08
    • 2013-05-26
    • 2016-01-05
    • 2015-05-13
    • 2014-10-10
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多