NOT NULL constraint failed: KNB_balance.user_id Django

I'm trying to update a value that's stored in the database from views.py, I can't get form.save() to work I keep getting this error, I don't understand what's the problem and if Im going about this all wrong can you explain to me how I can update the value in the database by using user's input in views.

Views.py

def deposit(request):  
form = DepositForm(request.POST or None)
pk = request.session.get('pk')

if pk:        
    user = CustomUser.objects.get(pk=pk)
    balance = user.balance
    code_user = f"{user.username}: {user.balance}"
    if not request.POST:
        balance.save()
        print(balance.number)
    if request.method == "POST":
        if form.is_valid():

            
            print(balance.number)
            balance.number = balance.number + 5
            print(balance.number)

            form.save()

            return redirect('home-view')
    
return render(request, 'deposit.html')

Models.py

class Balance(models.Model):
number = models.IntegerField(blank=True, null=True)
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)

def __int__(self):
    return int(self.number)


def save(self, *args, **kwargs):
    number_int = 500
    self.number = number_int
    super().save(*args, **kwargs)

forms.py

class DepositForm(forms.ModelForm):
number = forms.IntegerField(label='balance',help_text='Please enter your deposit amount')
class Meta:
    model = Balance
    fields = ('number',)

HTML FIle

{% load crispy_forms_tags %}

{% load static %}

{% block content %}

    <form method="POST" action="#">
        {% csrf_token %}
        {{ form }}
    <input id="number" type="number" name="number" placeholder="Deposit amount">
    <button type="submit" class="hero-btn sbmt">Deposit</button>
    </form> 


</div>

{% endblock %}



Read more here: https://stackoverflow.com/questions/68462364/not-null-constraint-failed-knb-balance-user-id-django

Content Attribution

This content was originally published by Muhaa 11 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: