I want to give users ten coins each time they fill out one form

Viewed 35

I want to give users ten coins each time they fill out one form , so i tried this code above and show this error

TypeError at /profile
unsupported operand type(s) for +=: 'DeferredAttribute' and 'int'
error in views.py in line += 10

models.py

class User(AbstractUser):
    user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True)
    coins = models.IntegerField(default=100)
    def gives_user_coins_after_create(sender, instance, created, **kwargs):
        if created:
            profile = instance.User.profile
            profile.coins += 10
            profile.save()

views.py

@login_required(login_url='accounts/login/')
def profile(request):
    # Gives the user 10 coins for fill up one form
    profile = get_user_model()
    profile.coins += 10
    profile.save()

    return render(request,'account/profile.html')

i tried many code but nothing work , any idea or help please

1 Answers

If the User model you show above is your AUTH_USER_MODEL then all you really need is

def give_coins(user, count):
    user.coins = F('coins') + count
    user.save(update_fields=('coins',))
    user.refresh_from_db(fields=('coins',))

(which is using F() to avoid (some) race conditions); there is no .profile you'd need to access.

You can then call this in e.g. your FormView's form_valid:

class MoneyFormView(FormView):
    # ...

    def form_valid(self, request):
        give_coins(request.user, 10)
        return super().form_valid(request)
Related