How to add a value to an integer field via a form in Django?

I'm currently trying to make a form that adds the value to the"point" model that I created but it seems to not go through. I made a form that should allow the user to put any integer value and it should add (or subtract) to the model. Can anyone point me to the right direction on what to do? Any help is appreciated.

Here is my forms.py:

class addpointForm(forms.ModelForm):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)
    class Meta:
        model = Points
        fields = ['user']

Model.py:

class Points(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    points = models.IntegerField(default=0, null=False)

    def __str__(self):
        return self.user.username

views.py:

@login_required
def pointform(request):
    if request.method=='POST':
        form = addpointForm(request.POST)
        if form.is_valid():

            instance = form.save(commit=False)
            messages.success(request, 'Success! Points has been added!')
            instance.user.points += addpointForm.add_point_field
            form.save()
        else:
            messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()
    return render (request,'users/addpoints.html',{'form':form})

Upvotes: 5

Views: 6159

Answers (1)

Brian Dant
Brian Dant

Reputation: 4149

Change your code to this:

instance.points += form.add_point_field
instance.save()

You don't actually use the user's input; instead you accidentally use addpointForm.add_point_field.

While we're at it, let's change some other things to clarify what you're doing:

Don't use a ModelForm; change your form class to inherit from forms.Form. Do this because your form does not actually modify a model; it merely accepts input from a user, which you then accept and use to modify a model. In this case, it using a Form seems to me more idiomatic and intuitive:

class addpointForm(forms.Form):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)

Then, let's clarify and simplify the view:

if request.method=='POST':
    form = addpointForm(request.POST)
    # Get the user from the request.
    user = request.user    

    if form.is_valid():
        points_instance = user.points
        points_instance.points += form.add_point_field
        points_instance.save()

        messages.success(request, 'Success! Points has been added!')

    else:
        messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()

    return render (request,'users/addpoints.html',{'form':form})

Upvotes: 1

Related Questions