简体   繁体   中英

How do I create a new user using AJAX with JsonResponse in Django?

The task is simple, a person is to be able to enter a name, email and password press 'Submit' and have his account info displayed beneath the form without the page needing to be refreshed.
I don't know where I'm going wrong, even though I've managed to go to ajax success function when I check the admin I see that there is no new user created.
Anyway, thanks in advance. Also, perhaps someone can offer me some ajax related tutorials or some information about djangorestframework.

models.py

class User(models.Model):
  name = models.CharField(max_length=255)
  email = models.EmailField()
  password = models.CharField(max_length=255)

urls.py

from django.conf.urls import url, include
from ajaxtest import views
urlpatterns = [
  url(r'$', views.home, name='home'),
  url(r'user/create/$', views.userCreate, name='create'),
]

views.py

def home(request):
users = User.objects.all()
return render(request, 'ajaxtest/index.html', {'users': users})

def userCreate(request):
  if request.method == 'POST':
    name = request.POST.get('ajaxName', '')
    email = request.POST.get('ajaxEmail', '')
    password = request.POST.get('ajaxPassword', '')

    User.objects.create(
        name = name,
        email = email,
        password = password,
    )
    response_data = {}
    return JsonResponse(response_data)

index.html

{% extends 'ajaxtest/base.html' %} {% load staticfiles %} {% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4 text-center bg-info">
            <h3>Form</h3>
        <form id="user_form">
            {% csrf_token %}
            <label for="labelName">Name</label>
            <input type="text" class="form-control" id="inputName" placeholder="Enter name">
            <label for="labelEmail">Email address</label>
            <input type="email" class="form-control" id="inputEmail" placeholder="Enter email">
            <label for="labelPassword">Password</label>
            <input type="password" class="form-control" id="inputPassword" placeholder="Enter password">
            <br>
            <button type="submit" class="btn btn-primary btn-block">Submit</button>
        </form>
        <br>
        <div id="allUsers">
            <ol>
                {% for user in users %}
                <li>{{user.name}} - {{user.email}} - {{user.password}}</li>
                {% endfor %}
            </ol>
        </div>
    </div>
    <div class="col-md-4"></div>
</div>

<script type="text/javascript">
$(document).on('submit', '#user_form', function(event) {
    event.preventDefault();
    $.ajaxSettings.traditional = true;
    $.ajax({
    type: 'POST',
    url: '{% url "create" %}',
    dataType: 'json'
    data: {
        ajaxName: $('#inputName').val(),
        ajaxEmail: $('#inputEmail').val(),
        ajaxPassword: $('#inputPassword').val(),
        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
    },
    success: function(response) {
        alert($('#inputName').val() +" Account Created!");
    }
    });
})

{% endblock content %}

Change "$" to "^$" in home url. Add comma after dataType: 'json', in ajax call. This then worked for me. Let me know if this works for you. Make sure to include your ajaxtest urls in main urls file.

urlpatterns = [
    url(r'^', include('ajaxtest.urls')),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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