Django视图和表单提交按钮更新数据库

时间:2012-12-21 19:23:27

标签: database django django-forms django-views

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

<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的新手,我不知道问题出在哪里。

1 个答案:

答案 0 :(得分: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请求,请记住您特别需要将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'));
    }   
});