如何在 Django 中增加内部会话?

How to increment inside session in Django?

我尝试在会话中创建一个计数器,但我失败了。会话打印出我添加一次的结果,当我想再次添加新评论时它不会增加过程。评论将被添加,但计数器仍然等于 1,所以我怎样才能增加到会话中:

def post(self, request, user_slug, *args, **kwargs):
    my_question = UserAsking.objects.get(ask_slug=user_slug)
    userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
    comment_form = CommentForm(request.POST, instance=request.user)
    name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
    username = self.request.user.username
    logo = self.request.user.userprofile.logo.url
    if comment_form.is_valid():
        comment_request = self.request.POST.get('comment', None)
        comment_form = Comment.objects.create(comment=comment_request,
                                              userasking_id=my_question.id,
                                              userprofile_id=userprof.id,
                                              name=name,
                                              username=username,
                                              logo=logo,
                                              comment_slug=my_question.ask_slug
                                              )
        q = UserAsking.objects.get(ask_slug=my_question.ask_slug)
        c = comment_form
        u = comment_form.userprofile
        if 'notify_counts' in request.session:
            counter = request.session.get('notify_counts', 0)
            request.session['notify_counts'] = counter + 1
            request.session.save()
            print('%s is commented your post: %s and comment is (%s) notify = %i'
                  %(u, q, c, counter))
        return redirect('community:question_view', user_slug)
        # return redirect('community:question_view', comment_form.userasking.ask_slug)
    return render(request, 'community/question_view.html', {'comment_form': comment_form})

Django会在session修改后自动保存到session数据库中,不用手动保存,看看:session保存时[Django-Doc].

def post(request,...):
   ...
   notify_counts = request.session.get('notify_counts')
   if notify_counts is None:
       request.session['notify_counts'] = 1
   else:
       request.session['notify_counts'] +=1

也可以使用try...except模式如下:

def post(request, ...):
    try:
        request.session['notify_counts'] +=1
    except KeyError:
        request.session['notify_counts'] = 1