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

时间:2022-03-26 19:17:10

This is the form that the submit button is in.

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

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

And I have this code in my view:

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

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

When the subscribe button is clicked I just want to update the record and insert that in the database. But nothing happens when I click the Subscribe button. I am new in django and I don't know where the problem is.

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

1 个解决方案

#1


1  

Specify Form Action

First of all you'll need to specify the form action if the tour_sub view is not the view that rendered the template that contains the form. Also use input type submit.

首先,如果tour_sub视图不是呈现包含表单的模板的视图,则需要指定表单操作。也使用输入类型提交。

<form action="/some/url/mapped/to/tour_sub/view/">
      <input type="submit" name="subscribe" class="btn btn-primary pull-right" value="Subscribe" />
</form>

Use Conditions and Error Handling

you can also modify your tour_sub function a little and do some Error Handling so that it the method does not have silent errors as they are hard to debug.

你也可以稍微修改你的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

If Post is AJAX

if you are making the POST request using AJAX do remember you'll specifically need to add the csrf_token to the POST data. Else, you can include the following generic js file to your base template and it will take care of appending the csrf_token to all AJAX requests.

如果您使用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'));
    }   
});

#1


1  

Specify Form Action

First of all you'll need to specify the form action if the tour_sub view is not the view that rendered the template that contains the form. Also use input type submit.

首先,如果tour_sub视图不是呈现包含表单的模板的视图,则需要指定表单操作。也使用输入类型提交。

<form action="/some/url/mapped/to/tour_sub/view/">
      <input type="submit" name="subscribe" class="btn btn-primary pull-right" value="Subscribe" />
</form>

Use Conditions and Error Handling

you can also modify your tour_sub function a little and do some Error Handling so that it the method does not have silent errors as they are hard to debug.

你也可以稍微修改你的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

If Post is AJAX

if you are making the POST request using AJAX do remember you'll specifically need to add the csrf_token to the POST data. Else, you can include the following generic js file to your base template and it will take care of appending the csrf_token to all AJAX requests.

如果您使用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'));
    }   
});