简体   繁体   English

如何在Django中使用Post_save

[英]How to use Post_save in Django

I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. 我在尝试使用Django评论框架提交评论后向用户的个人资料添加点数。 I think I need to use a post_save but am not sure to be perfectly honest. 我认为我需要使用post_save,但不确定是否完全诚实。

Here is what I have as a method in my models.py: 这是我在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. 从我发现的post_save的示例中,这与所显示的相去甚远-所以我认为我远远没有实现。

Thank you for your help. 谢谢您的帮助。

Unfortunately this makes no sense at all. 不幸的是,这根本没有任何意义。

Firstly, this can't be a method, as it doesn't have self as the first parameter. 首先,这不是一种方法,因为它没有self作为第一个参数。

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). 第三, post_save不是该模型的方法(除非您自己定义了一个方法)。 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. 最后,您将添加2的配置文件实例不一定与您在第二行中保存的配置文件实例相同,因为Django模型实例没有身份。 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. Comments框架定义自己可以使用的信号 ,而不是通用的post_save。 So, what you actually need is to register a signal handler on comment_was_posted. 所以,你真正需要的是在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM