问题
I have a Song
model with a votes
attribute. I have a Vote as Favourite
button displayed below each Song
object. I want when a user clicks on the Vote as Favourite
button the votes
attribute associated with that Song
object should increment by 1 and all the Vote as Favourite
buttons should be disabled.
HTML
{% for song in dj_song_list %}
<div>
<p class="song"><h3><strong>{{ song.name }}</strong></h3></p>
<p><strong>Artist: </strong>{{ song.artists}}</p>
<button type="button" class="btn btn-default btn-custom" id='vote' onclick="Dajaxice.hunt.disable_button(Dajax.process)">Vote as Favourite</button>
</div>
{% endfor %}
I'm using dajaxice/dajax for my AJAX call. This is what I've come up with as my ajax.py
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from dajax.core import Dajax
@dajaxice_register
def disable_button(request):
dajax = Dajax()
dajax.assign('#vote', 'disabled', 'disabled')
return dajax.json()
@dajaxice_register(method="POST")
def update_votes(request, song):
song.votes += 1
song.save()
return simplejson.dumps({'message':'Thank you for voting'})
JS
function callback(data){
alert(data.message);
}
How do I get the value of Song
object to send to update_votes()
?
The disable_button()
disables only the first vote button. How can I disable all the vote buttons?
How can I call both update_votes()
and disable_button()
using the same buttons onclick attribute?
回答1:
Here's how you can update the votes. You don't need update_votes to be an ajax function.
def update_votes(song_id):
song = Song.objects.get(id=song_id)
song.votes += 1
song.save()
You can then call this function from within disable_button.
@dajaxice_register
def disable_button(request, song_id):
update_votes(song_id)
#disable the buttons
return #whatever
And are you sure you're using the right selector to disable your buttons?
来源:https://stackoverflow.com/questions/20731943/getting-object-value-for-ajax-call-using-dajaxice