Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

jquery - Django form submit with ajax

I have new_registration view as follows :

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)

The template new_registration.html is as follows :

{% 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 %}

I'm trying to send the data with ajax and show the appropriate message.

The ajax code is as follows :

$('#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;
                }
            });
        });

I know that I need to return HttpResponse instead of the rendering template in the view. But what would be the right way to do it here? I do not want to lose possibility to show the errors if the form is not valid.

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use JsonResponse instead of render or HttpResponse. https://docs.djangoproject.com/en/1.10/ref/request-response/

Import from django http:

from django.http import JsonResponse

And use like this:

return JsonResponse(context)

This way you don't have any page reload, and you can use the response in your javascript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...