简体   繁体   English

如何在Django中使用AJAX和JsonResponse创建新用户?

[英]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. 我不知道我要去哪里错了,尽管我在检查管理员时设法进入了Ajax成功功能,但我发现并没有创建新用户。
Anyway, thanks in advance. 无论如何,预先感谢。 Also, perhaps someone can offer me some ajax related tutorials or some information about djangorestframework. 另外,也许有人可以为我提供一些与Ajax相关的教程或有关djangorestframework的信息。

models.py models.py

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

urls.py 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 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 的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. 在ajax调用中,在dataType:'json'之后添加逗号。 This then worked for me. 然后这对我有用。 Let me know if this works for you. 如果这对您有用,请告诉我。 Make sure to include your ajaxtest urls in main urls file. 确保在主url文件中包含ajaxtest url。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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