【问题标题】:Django form submit with ajaxDjango 表单使用 ajax 提交
【发布时间】:2017-07-26 09:39:10
【问题描述】:

我有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,而不是视图中的渲染模板。但是在这里做这件事的正确方法是什么?如果表单无效,我不想失去显示错误的可能性。

有什么建议吗?

【问题讨论】:

    标签: jquery ajax django django-forms


    【解决方案1】:

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

    从 django http 导入:

    from django.http import JsonResponse
    

    并像这样使用:

    return JsonResponse(context)
    

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

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2019-03-24
      • 1970-01-01
      • 2011-03-13
      • 2015-12-21
      • 2020-11-24
      • 2016-08-20
      • 2018-07-22
      • 2018-09-17
      相关资源
      最近更新 更多