So I'm building a battleships game using Django. What I want to do is, once a game is finished, create a new Game object in my DB with the score and the current user. My Game model looks like this:
class Game(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField(default=0)
date = models.DateTimeField(auto_now_add=True)
win = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.score < 0:
self.score = 0
super(Game, self).save(*args, **kwargs)
def __unicode__(self):
return unicode(self.date)
The actual game is written in JS and you and the AI keep taking turns until one of you wins, at which point your score is calculated. This is where I would like to update my DB with the new game, but I have no idea how to go about it. I was thinking of putting in a submit button and making the view create a new game object on a POST request, but I don't know how I can pass the score & win/loss variables to it. Any help would be appreciated.
Well, there are many ways of achieving this, but I'll put here a simple example
Start with an url:
url(r'^end-game/?','your_app.views.end_game', name='end-game'),
Then on your_app.views
import datetime
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from your_app.models import Game
@login_required(redirect_field_name=None, login_url='login')
def end_game(request):
# Get the post variables
score = request.POST['score']
win = request.POST['win']
# You may want to validate data here
# Create the game object
try:
game = Game.objects.create(
user = request.user.id,
score = score,
win = win,
date = datetime.datetime.now()
)
game.save()
# Setting output
response = {
'status': 1,
'message': 'Game saved'
}
except Exception as e:
# Something went wrong
response = {
'status': 0,
'message': 'Something went wrong - ' +str(e)
}
return HttpResponse(response, mimetype='application/json')
javascript (in html file):
$.post( "{% url 'end-game' %}",
{
csrfmiddlewaretoken: '{{ csrf_token}}' ,
score : score, //pass the score here
win: win // pass the win value here
},
function(data) {
if(data.status == 1){
// success! Do something
}
else{
// error! Do something
}
});
You could also use a form, keep it hidden and submit it when the game finishes. There are some advantages in doing it, like having validation and saving functions on the form itself, but since you only need two variables, the above should be ok.
Also, you should use something like
if request.method is POST:
before you do anything and check if the POST values are set before trying to read them...
if 'score' in request.POST:
It's just example, not tested, but should work as is
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With