0

I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. I think I need to use a post_save but am not sure to be perfectly honest.

Here is what I have as a method in my models.py:

 def add_points(request, Comment):
    if Comment.post_save():
        request.user.get_profile().points += 2
        request.user.get_profile().save()

From the examples of post_save I've found, this is far from what is shown - so I think I am way off the mark.

Thank you for your help.

Emile
  • 3,464
  • 8
  • 46
  • 77

1 Answers1

2

Unfortunately this makes no sense at all.

Firstly, this can't be a method, as it doesn't have self as the first parameter.

Secondly, it seems to be taking the class, not an instance. You can't save the class itself, only an instance of it.

Thirdly, post_save is not a method of the model (unless you've defined one yourself). It's a signal, and you don't call a signal, you attach a signal handler to it and do logic there. You can't return data from a signal to a method, either.

And finally, the profile instance that you add 2 to will not necessarily be the same as the one you save in the second line, because Django model instances don't have identity. Get it once and put it into a variable, then save that.

The Comments framework defines its own signals that you can use instead of the generic post_save. So, what you actually need is to register a signal handler on comment_was_posted. Inside that handler, you'll need to get the user's profile, and update that.

def comment_handler(sender, comment, request, **kwargs):
    profile = request.user.get_profile()
    profile.points += 2
    profile.save()

from django.contrib.comments.signals import comment_was_posted
comment_was_posted.connect(comment_handler, sender=Comment)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Yeah I was way off the mark...I used what you posted, and got an AssertionError: Signal receivers must be callable. It looks like this post got the same error : http://stackoverflow.com/questions/2310676/django-signal-via-decorator-on-model-method – Emile Nov 18 '10 at 15:06
  • Sorry, had the connect call the wrong way round: edited, try it now. – Daniel Roseman Nov 18 '10 at 15:45
  • Thanks, it now doesn't throw an error, but still doesn't seem to update the get_profile().points . I'm not sure if its getting called. Any other suggestions? Thanks again for the help. – Emile Nov 18 '10 at 16:14
  • Got it ...took out sender=Comment and works great..Thanks Daniel – Emile Nov 18 '10 at 16:31
  • Turns out it actually runs twice : https://gist.github.com/40e5b0f0e530f0d53c48 works great..except executing twice. – Emile Nov 18 '10 at 16:44