Reputation: 594
I try to create a counter inside session but I fail. the session is print out the result I added once and it doesn't increment the process when I want to add a new comment again. the comment will be added but counter is still equal to one so, how can I do increment into session:
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})
Upvotes: 0
Views: 251
Reputation: 3327
Django automatically saves to the session database when the session has been modified, so you won't bother to save it manually, take a look:when session are stored[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
Also you could use try...except
pattern as follows:
def post(request, ...):
try:
request.session['notify_counts'] +=1
except KeyError:
request.session['notify_counts'] = 1
Upvotes: 1