开发者

Django - Ajax hidden Model Form

I have these 2 models:

class Exercis开发者_开发知识库e(models.Model):
  text = models.TextField()

class Score(models.Model):
  user = models.ForeignKey(User)
  exercise = models.ForeignKey(Exercise)
  score = models.IntegerField()
  class Meta:
    unique_together = (('user', 'exercise',),)

A template displays an exercise that a user can complete. The user gets a score at the end.

I'd like to send the score to the database with ajax.

I prepared a view to get the scores

def scoresexo(request):
  if request.method == 'POST':
    ret = {'type': 'info'}
    score, created = Score.objects.get_or_create(
      user = request.user
    , exercise_id = request.POST['exo']
    )
    score.score = request.POST['score']
    try:
      score.save()
    except:
      ret['type'] = 'error'
      ret['msg'] = 'error saving'
    return HttpResponse(json.dumps(ret), mimetype='application/json')

Should I use a hidden ModelForm or a manual Form/View ?

And what would it be like ?


Why do you need form here? Send get / post request with score and exercise to some view and save the results there.

And don't forget that anyone can make request with any data, so you need to think about some validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜