Skip to content
Advertisement

I would like to limit the borrowing objects in my Django app

I have an app that displays games and users can borrow them. I want to limit the amount of borrowed games for each user to max 3 games. I created two models borrow and games. The methods work well except for the max borrowing.

Advertisement

Answer

You can check whether he has borrowed more than 3 games in form.is_valid() if like so:

if form.is_valid():
    borrowed_count = Borrow.objects.filter(owner=request.user).count()
    if borrowed_count < 4:
        form.save()
    else:
        print("You've borrowed 3 games already") # or whatever

Also that default in your owner field is specifying the user.pk not the games, you should change that.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement