3

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Please don't ever do except Exception as e:
It's better to replace the HttpResponse with JsonResponse which should be imported from from django.http import JsonResponse. this type of response handles the json header and you don't need to include the mimetype which is not supported in every version of django
I have one question before I begin implementing this: if I send a request, will the rendering of the current page disappear? I want to save the data but also make sure there is animation without having the page to "re-render". I am just asking so that I can save some time.
0

This is a broad question...but you can easily have the JavaScript application POST the score to a URL/view when the game ends via AJAX (won't require user input). That view should point to a ModelForm to validate the data, and save() it to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.