user1855165
user1855165

Reputation: 289

Django views and forms submit button update database

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.

Upvotes: 1

Views: 4337

Answers (1)

Amyth
Amyth

Reputation: 32949

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.

<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.

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.

$(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'));
    }   
});

Upvotes: 1

Related Questions