djangodjango-modelsdjango-views

How can I change CustomUser model fields in view and forms


I am building a scoring system and I want to register a score for those who are active on the website, for example, when someone leaves a comment, get 5 points, but I didn't succeed and I tried several methods.

models.py

class CustomUser(AbstractUser):
    activity_point = models.PositiveIntegerField(default=0)

First method in 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
            }))

Second method in 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)

I expect its change the activity point to 5.


Solution

  • You didn't save the user:

    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)