from django.http import JsonResponse
def post_form_api(request):
data = {}
if request.method == "POST" and request.POST.get('form_field1', None) is not None:
form_field1 = request.POST.get('form_field1')
# save the form data and indicate success
data['result'] = True
data['message'] = "Form saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
或者,如果您使用的是Django表单:
from django.http import JsonResponse
def post_form_api(request):
data = {}
if request.method == "POST":
form = MyDjangoForm(request.POST)
# save the form and indicate success or do something else with it
data['result'] = True
data['message'] = "Form saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
您可以在模板中使用JQuery Ajax并在views.py中创建一个“API视图”,这基本上只是一个常规视图,在检查验证请求是否为Ajax后返回一个
JSONResponse
。作为“API”选项的一个示例,使用JQuery:在您的URL.py中:
在模板中:
或者,您可以一次获取所有表单字段:
在your views.py中:
或者,如果您使用的是Django表单:
当您通过POST发送数据时,不要忘记传递您的CSRF令牌,如上面的示例所示。这假设您在页面上有一个表单,您可以从中获取表单,否则您可以使用类似以下的方式获取表单:
如果不想处理CSRF令牌,可以使用
@csrf_exempt
装饰器标记视图,并从模板中的Ajax调用中删除“csrfmiddlewaretoken
”数据元素,但它可能不是理想的或最安全的。例如:现在,在不知道更多的情况下,这基本上只是伪代码(加上我只是在脑海中写下了这个,所以可能会有错误)。如果你发布更多细节,我可以更新我的答案,但我认为这应该让你开始
相关问题 更多 >
编程相关推荐