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