指定窗體操作
所有你需要的,如果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
如果帖子是AJAX
如果您正在使用AJAX記得你特別需要的csrf_token
添加到POST數據使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'));
}
});
表單缺少'action'和'method'屬性。然後'tour'是一個查詢集。在這種情況下,您可能想要使用'get()'而不是'filter()'。 – arie
@arie我改變了表單以包含方法和操作,還有{%csrf_token%},但是我得到了CSRF驗證失敗。請求中止。 – user1855165
你使用ajax來更新它嗎? – Amyth