Django表单提交ajax

时间:2017-03-06 13:32:20

标签: jquery ajax django django-forms

我的new_registration视图如下:

def new_registration(request):
context = {}

if request.method == "POST":
    form = RegistrationForm(request.POST)
    if form.is_valid():
        language = Language.objects.get(key="EN")
        country = Country.objects.get(key="BE")

        user = User()
        user.username = form.cleaned_data['email']
        user.first_name = form.cleaned_data['first_name']
        user.last_name = form.cleaned_data['last_name']
        user.email = form.cleaned_data['email']
        user.set_password(form.cleaned_data['password'])
        user.save()

        # Send an email to user
        subject = "The account is created"
        plain_message = "Your account has been created successfully but it's not activated. Once your information has been processed, your account will be activated and you will get an email."
        html_message = render_to_string('master/email_templates/account_created_member.html', {'name': user.first_name})
        msg = EmailMultiAlternatives(subject, plain_message, settings.EMAIL_FROM, [user.email])
        msg.attach_alternative(html_message, "text/html")
        msg.send()

        context['form'] = RegistrationForm()
        context['success'] = "Your account has been created successfully. Once your information has been processed, your account will be activated."

        return render(request, 'master/new-registration.html', context)
else:
    form = RegistrationForm()

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

模板new_registration.html如下:

{% extends "master/base.html" %}

{% block content %}

    <div id="container" class="cls-container">

        <div id="bg-overlay" class="bg-img" style="background-image: url(/static/master/img/48210373_l.jpg)"></div>

        <div class="cls-content">
            <div class="cls-content-lg panel">
                <div class="panel-body">

                    <div>
                        {% if error %}
                            <div class="mar-btm alert alert-danger" style="border-left: none;"> {{ error }}</div>
                        {% endif %}
                    </div>
                    <div>
                        {% if success %}
                            <div class="mar-btm alert alert-primary" style="border-left: none;"> {{ success }}</div>
                        {% endif %}
                    </div>
                    <form id="registration-form" method="POST" action={% url 'new_registration' %}>
                        {% csrf_token %}
                        <div class="row">

                            <div class="col-lg-12 col-xs-12 pad-no">
                                <p class="bord-btm pad-ver text-main text-bold" style="margin-left: 7.5px;margin-right: 7.5px;">Personal info</p>

                                <fieldset>
                                    <div class="col-sm-6">
                                        <div class="form-group {% if form.first_name.errors %} has-error {% endif %}">
                                            {{ form.first_name }}
                                            {{ form.first_name.errors }}
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group {% if form.last_name.errors %} has-error {% endif %}">
                                            {{ form.last_name }}
                                            {{ form.last_name.errors }}
                                        </div>
                                    </div>

                                </fieldset>
                            </div>


                            <div class="col-lg-12 col-xs-12 pad-no">
                                <p class="bord-btm pad-ver text-main text-bold"
                                   style="margin-left: 7.5px;margin-right: 7.5px;">Account info</p>

                                <fieldset>
                                   <div class="col-sm-12">
                                        <div id="email-wrapper" class="form-group {% if form.email.errors %} has-error {% endif %}">
                                            {{ form.email }}
                                            {{ form.email.errors }}
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div id="password-wrapper" class="form-group {% if form.password.errors %} has-error {% endif %}">
                                            {{ form.password }}
                                            {{ form.password.errors }}
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div id="confirm-password-wrapper" class="form-group {% if form.password_confirm.errors %} has-error {% endif %}">
                                            {{ form.password_confirm }}
                                            {{ form.password_confirm.errors }}
                                        </div>
                                    </div>
                                </fieldset>
                            </div>


                        </div>
                        <button id="button-register" class="btn btn-primary btn-block" type="submit">Register
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

我正在尝试使用ajax发送数据并显示相应的消息。

ajax代码如下:

$('#registration-form').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: "{% url 'new_registration' %}",
                data: $('#registration-form').serialize(),
                type: 'POST',
                success: function (result) {
                    debugger;
                    // do something with the result
                },
                error: function (data) {
                    debugger;
                }
            });
        });

我知道我需要在视图中返回HttpResponse而不是渲染模板。但是在这里做正确的方法是什么?如果表单无效,我不想失去显示错误的可能性。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用JsonResponse而不是render或HttpResponse。 https://docs.djangoproject.com/en/1.10/ref/request-response/

从django http:

导入
from django.http import JsonResponse

并像这样使用:

return JsonResponse(context)

这样您就没有任何页面重新加载,并且您可以在javascript中使用响应。