loremIpsum1771
loremIpsum1771

Reputation: 2527

How to run Django view function once a button is clicked in a template

I've made a webpage that displays the results of the query for concert data based on the parameters submitted by the user in a POST request through an api. Users of the web app need to be able to add the concerts to their list of concerts or to send invites to other users for a concert. This would require sending the information for each concert back to the server where it can be stored in the model for a user.

In each list element of the results list, I have two buttons that when clicked would send POST requests to the server with the concert information using an ajax call. Currently I only have the shell for these two functions as I'm not to clear on how to go about sending the data for the current list item and then initiating the corresponding function in the view. Here is what I currently have for the client side:

var venues = {{venues|safe}};
var dates = {{raw_dts|safe}};
var ticket_statuses = {{ticket_statuses|safe}};
var ticket_urls = {{ticket_urls|safe}};
console.log("length of artist list" + venues.length);
var $list = $("<ul  class='list-group'>");
for(var i = 0; i < venues.length; i++){

    $list.append("<li class='list-group-item'>Artist: {{form_artistSelect}}  Location: " + venues[i].city + ', ' + venues[i].region +' Venue: ' + venues[i].name + 
       "Date: " + dates[i] + "tickets status: " + ticket_statuses[i] + "<br><a href = '" + ticket_urls[i] +"'" + "> ticket link</a> " + "<button id ='invite'type='button' class='btn btn-primary-outline'>Invite a friend</button>  <button id = 'save' type='button' class='btn btn-primary-outline'> Save concert</button> </li>"); 
}
// var $resultObj = $('<div id = "inviteObj" style="margin:100px"></div>');
// $resultObj.append($divline);
$list.appendTo($("#container"));
$("#save").click(function() {
    $.ajax({
        url: your_url,
        method: 'POST',
        data: {
            name: value,
            click: True
        }
        success:function(data){
        }
    });
});

$("#invite").click(function() {
    $.ajax({
        url: your_url,
        method: 'POST',
        data: {
            name: value,
            click: True
        }
        success:function(data){

        }
    });
});  

Inside of views.py I have one view function that handles getting the JSON response and passing it to the client side based on the user input it gets from the form request. Here is the view:

def search(request):
    form = SearchForm(request.POST or None)
    if form.is_valid():
        form_artistSelect = urllib2.quote(form.cleaned_data.get("artist_select"))
        form_city =   urllib2.quote(form.cleaned_data.get("city"))
        form_state = urllib2.quote(form.cleaned_data.get("state"))
        mile_radius = urllib2.quote(form.cleaned_data.get("radius"))
        #print "testing"
        url = "http://api.bandsintown.com/events/search?artists[]=" + form_artistSelect + "&location=" +form_city+","+ form_state+"&radius="+ mile_radius + "&format=json&app_id=YOUR_APP_ID"
        data = json.load(urllib2.urlopen(url))

        #titles = [ i.get("title") for i in data]
        raw_dts = json.dumps([i.get("datetime") for i in data])

        #formatted_dts = [i.get("formatted_datetime") for i in data]
        ticket_urls = json.dumps([i.get("ticket_url").encode("utf-8") for i in data])
        ticket_statuses = json.dumps([i.get("ticket_status").encode("utf-8") for i in data])
        venues = json.dumps([i["venue"] for i in data])
    context = {
            "form" : form,
            "form_artistSelect" : form_artistSelect,
            "raw_dts" : raw_dts,
            "ticket_urls" : ticket_urls,
            "ticket_statuses" : ticket_statuses,
            "venues" : venues,
        }
    else:
        context = {
            "form" : form   

        }
    return render(request,"searchform.html" , context)

So specifically, I have a couple of questions

As this view is the only one I have for the page, should I add other view functions for each button click event? Also, would be the proper way to send data for each concert list item to python on the server side where it can be saved for each user?

Upvotes: 0

Views: 1327

Answers (1)

Galia Ladiray Weiss
Galia Ladiray Weiss

Reputation: 452

I would add two views

  • invite_concert
  • save_concert

At each click, you use the correct URL for that view, the view can return an empty HttpResponse, if you don't need any answer back. For the parameters, I like sometimes to add the parameters I need to the HTML of the item, something like

data-concert-id=venues[i].id

But maybe you already have all the required data in your list item. Anyway, you can then retrieve them and use them easily in the data object of your ajax call, like:

{concert-id : $(this).attr('data-concert-id')

Upvotes: 1

Related Questions