简体   繁体   English

使用Ajax验证并提交Django表单(django-crispy-forms)

[英]validate and submit Django form (django-crispy-forms) with Ajax

I'm very new at django and web development. 我在Django和Web开发方面是新手。 I need help submitting Django form (using django-crispy-forms) with Ajax How do I: 我需要与Ajax一起提交Django表单(使用django-crispy-forms)的帮助如何:

  1. validate input 验证输入

  2. submit without reloading 提交而无需重新加载

  3. display errors in case of validation failure 验证失败时显示错误

Right now i can submit the form and it saves the entries into the database but reloads the entire page in the process. 现在,我可以提交表单,它将条目保存到数据库中,但在此过程中将重新加载整个页面。 i have included relevant snippets of my code below 我在下面包含了我的代码的相关片段

// forms.py //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 // 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})

// template //模板

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

// rendered form HTML //呈现的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>

I'll try to give you an idea of how to do it easily. 我将尽力让您了解如何轻松实现。

Add the onsubmit event listener to the form and error-block eg bellow the form where errors will be displayed. 将onsubmit事件侦听器添加到表单和错误块,例如在显示错误的表单下。

template 模板

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

now the handler which will send the data to the view to be validated and saved 现在,处理程序会将数据发送到视图以进行验证和保存

<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>

In the view you'll receive the data in the same form as the form would be submitted but you will not have to render whole template to the response, but only the erros from the validated form, so the view you will send your ajax POST request to will have to be different from the view which renders the form. 在视图中,您将以与提交表单时相同的形式接收数据,但是您不必将整个模板呈现给响应,而只需渲染已验证表单中的错误,因此视图将发送ajax POST请求必须与呈现表单的视图不同。 You can create another which will handle it. 您可以创建另一个将处理它。

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

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