Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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})
like image 309
Edjeil Dominic B. Labra Avatar asked Nov 06 '22 07:11

Edjeil Dominic B. Labra


1 Answers

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})
like image 90
Brian Dant Avatar answered Nov 14 '22 05:11

Brian Dant