1

这是提交按钮所在的表单。

<form>
          <button type="submit" name="subscribe" class="btn btn-primary pull-right">Subscribe</button></h5>
        </form>

在我看来,我有这段代码:

def tour_sub(request):
    tour = Tour.objects.filter(id=1)
    if 'subscribe' in request.POST:
        tour.subscribers.add(user) 
        tour.save()

单击订阅按钮时,我只想更新记录并将其插入数据库。但是当我单击订阅按钮时没有任何反应。我是 django 的新手,我不知道问题出在哪里。

4

1 回答 1

1

指定表单操作

首先,如果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'));
    }   
});
于 2012-12-21T22:22:18.867 回答