你好,我对django很新,抱歉。我尝试使用django.contrib.auth.model的User类创建用户对象我尝试使用ajax将数据从jQuery传输到views.py。出于某种原因,当我添加数据类型时:' JSON'它停止执行ajax,当我删除它时,HttpResponse只给了我整个html文件。不是创建用户的单个实例。
HTML
<form action = "" method="post">
{% csrf_token %}
<p class="label" id="l1"> Name: </p>
<input type="text" class="textbox" id="name"><br>
<p class="label" id="l2"> Username: </p>
<input type="text" class="textbox" id="username"><br>
<p class="label" id="l3"> Password: </p>
<input type="password" class="textbox" id="password"><br>
<p class="label" id="l4"> Confirm Password: </p>
<input type="password" class="textbox" id="confirm"><br>
<button id="signupbutton">Sign Up</button>
</form>
的jQuery
$("#signupbutton").click(function () {
var username = $("#username").val();
var password = $("#password").val();
var confirm = $("#confirm").val();
var name = $("#name").val();
errorval = errorCheck();
if (errorval == 0) {
// transform data input to dictionary
const infoset = {
"name": name,
"username": username,
"password": password
};
console.log(infoset);
var csrftoken = $.cookie('csrftoken');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "create_user/",
type: "POST",
dataType: 'JSON',
data: JSON.stringify(infoset),
success: function (data) {
console.log(JSON.parse(data));
},
fail: function (data) {
console.log("everything went to shit");
}
});
$("#errormsg").text('creation successful');
}
views.py
def create_user(request: HttpRequest) -> HttpResponse :
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
response_data = {}
user = User(username=username, password=password)
user.save()
response_data['result'] = 'Create post successful!'
response_data['userpk'] = user.pk
response_data['username'] = user.username
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
urls.py
from django.conf.urls import url
from django.contrib import admin
from bartr import views
urlpatterns = [
url(r'^admin/', admin.site.urls, name="admin"),
url(r'^$', views.home, ),
url(r'^home/', views.home, name="home"),
url(r'^sign_up/', views.sign_up, name="sign_up"),
url(r'^marketplace/', views.marketplace, name="marketplace"),
url(r'^create_user/', views.create_user, name="create_user")
]
答案 0 :(得分:0)
请勿使用JSON.stringfy
。
data: infoset,
答案 1 :(得分:0)
问题在于你的网址;在urls.py中的模式中,以及在将Ajax发布到的URL中。
您需要终止所有模式:
url(r'^home/$', views.home, name="home"),
url(r'^sign_up/$', views.sign_up, name="sign_up"),
url(r'^marketplace/$', views.marketplace, name="marketplace"),
url(r'^create_user/$', views.create_user, name="create_user")
您需要将Ajax发布到绝对URL:
$.ajax({
url: "/create_user/",
...
});
更好的是,你会在那里使用{% url %}
标签;你不能在外部JS文件中这样做,所以更好的解决方案是给表单一个动作值,然后在你的JS中使用它:
<form action="{% url 'create_user' %}" id="create_user">
...
var url = $('#create_user').attr('action');
$.ajax({
url: url,
...
});
(此外,它不会对此产生任何影响,但您绝对不希望在const
的声明中使用infoset
;它根本不是常量。)
答案 2 :(得分:0)
解决问题的第一步确实是修正你的网址定义,正如Daniel Roseman在其他答案中提到的那样。
好吧,关于你的Jquery代码
您不需要设置dataType值,而且根本不需要使用JSON.stringify(infoset)
要将数据传递给视图,您可以使用Jquery的serialize方法,因为您还必须将csrf令牌传递给您的视图(因此您会收到内部服务器错误)
修复网址定义后,您可以按照以下方式设置ajax:
$.ajax{
url: "/create_user/",
type: "POST",
data: $("#your-form-id").serialize(),
success: function (data) {
console.log(data);
},
fail: function (data) {
console.log("everything went to shit");
}
});
在您的视图中,您可以使用JsonResponse而不是返回HttpResponse( json.dumps(RESPONSE_DATA), CONTENT_TYPE =&#34;应用/ JSON&#34; )
你也可以这样做:
return JsonResponse(response_data)
我想推荐你这篇关于用Django谈论ajax submition的帖子,我发现对我很有帮助 Django Ajax Form Submition
此致
答案 3 :(得分:0)
像这样编辑您的视图,
if request.method == 'POST':
data = json.loads(request.POST)
username = data.get('username')
password = data.get('password')
response_data = {}
user = User(username=username, password=password)
user.save()
response_data['result'] = 'Create post successful!'
response_data['userpk'] = user.pk
response_data['username'] = user.username
return JsonResponse(response_data)
else:
return JsonResponse({"nothing to see": "this isn't happening"})
还从ajax请求中删除JSON.parse,
$.ajax({
url: "create_user/",
type: "POST",
data: JSON.stringify(infoset),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log("everything went to shit");
}