我正在建立一个评分系统,我想为那些在网站上活跃的人登记一个分数,例如,当有人发表评论时,获得5分,但我没有成功,我尝试了几种方法。
模型.py
class CustomUser(AbstractUser):
activity_point = models.PositiveIntegerField(default=0)
views.py中的第一个方法
class NewsDetailView(generic.DetailView):
model = News
template_name = 'news/news_details.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
if self.request.user.is_authenticated:
context['comment_form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
news = self.get_object()
form.instance.author = request.user
form.instance.news = news
self.request.user.activity_point += 5 # Here
form.save()
return redirect(reverse('news_detail', kwargs={
'pk': news.uid
}))
views.py中的第二种方法
class CitizenNewsCreateView(mixins.LoginRequiredMixin, generic.CreateView):
model = News
template_name = 'news/news_create.html'
form_class = CitizenReporterForm
success_url = reverse_lazy('citizen_report_list')
def get_queryset(self): # Here
user = CustomUser.objects.filter(username=self.request.user.username)
change_activity_point = user.activity_point + 5
return change_activity_point
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.active = False
form.instance.citizen = True
return super(CitizenNewsCreateView, self).form_valid(form)
我预计它会将活动点更改为 5。
class NewsDetailView(generic.DetailView):
model = News
template_name = 'news/news_details.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
if self.request.user.is_authenticated:
context['comment_form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
news = self.get_object()
form.instance.author = request.user
form.instance.news = news
form.save()
user = self.request.user
user.activity_point = F('activity_point') + 5
user.save()
return redirect('news_detail'pk=news.uid)