指定表单操作
首先,如果tour_sub
视图不是呈现包含表单的模板的视图,您需要指定表单操作。也使用input
类型提交。
<form action="/some/url/mapped/to/tour_sub/view/">
<input type="submit" name="subscribe" class="btn btn-primary pull-right" value="Subscribe" />
</form>
使用条件和错误处理
您还可以tour_sub
稍微修改您的函数并进行一些错误处理,以便该方法不会出现静默错误,因为它们很难调试。
def tour_sub(request):
tour = get_object_or_404(Tour, pk=1)
if (request.method == "POST") and ("subscribe" in request.POST):
tour.subscribers.add(user)
tour.save()
# Send a Success Message to the User
else:
# Do something in case of a GET request
如果 Post 是 AJAX
如果您使用 AJAX 发出 POST 请求,请记住您特别需要将 POST 数据添加csrf_token
到 POST 数据中。否则,您可以在基本模板中包含以下通用js
文件,它将负责将 附加csrf_token
到所有 AJAX 请求。
$(document).ajaxSend(function(event, xhr, settings) {
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 = jQuery.trim(cookies[i]);
// 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;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});