如何在Django中使用带有JsonResponse的AJAX创建新用户?

时间:2016-02-13 07:32:56

标签: jquery python ajax django

任务很简单,一个人可以输入姓名,电子邮件和密码按“提交”。并在表单下方显示其帐户信息,而不需要刷新页面 我不知道自己哪里出错了,即使我在检查管理员时设法转到ajax成功功能我发现没有新用户创建。
无论如何,提前谢谢。此外,也许有人可以提供一些与ajax相关的教程或关于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 %}

1 个答案:

答案 0 :(得分:0)

在主网址中将“$”更改为“^ $”。在ajax调用中在dataType:'json'之后添加逗号。这对我有用。如果这对您有用,请告诉我。确保在主网址文件中包含您的ajaxtest网址。

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