如何在Django中使用带有JsonResponse的AJAX创建新用户? [英] How do I create a new user using AJAX with JsonResponse in Django?

查看:80
本文介绍了如何在Django中使用带有JsonResponse的AJAX创建新用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务很简单,一个人将能够输入姓名,电子邮件和密码,然后按提交",然后在表格下方显示其帐户信息,而无需刷新页面.
我不知道我要去哪里错了,尽管我在检查管理员时设法进入了Ajax成功功能,但我发现并没有创建新用户.
无论如何,在此先感谢.另外,也许有人可以为我提供一些与Ajax相关的教程或有关djangorestframework的信息.

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

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

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

推荐答案

在主URL中将"$"更改为"^ $".在ajax调用中,在dataType:'json'之后添加逗号.然后这对我有用.让我知道这是否适合您.确保在主url文件中包含您的ajaxtest url.

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')),
]

这篇关于如何在Django中使用带有JsonResponse的AJAX创建新用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆