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

Time:12-27

I have an app that displays games and user 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.

# Method display borrowed games
@login_required
def borrows(request):
    borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed')
    context = {'borrows':borrows}
    return render(request, 'gameapp/borrows.html', context)`

# Methos allow the user borrow single game
@login_required
def borrow(request, boardgame_id):
    boardgame = Boardgame.objects.get(id=boardgame_id)
    if request.method != 'POST':
        form = BorrowForm()
    else:
        form = BorrowForm(data = request.POST)
        if form.is_valid():
            borrow_boardgame = form.save(commit = False)
            borrow_boardgame.owner = request.user
            # Replace the borrow varibale from borrow Model to main game
            borrow_boardgame.borrow = boardgame
            form.save()
            return redirect('gameapp:borrows')
    
    context = {'boardgame': boardgame, 'form':form}
    return render(request, 'gameapp/borrow.html', context)

I also used limit [:3] but this will keep the user sending data to the database in the backend.


# A model for the game
class Boardgame(models.Model):
    name = models.CharField(max_length=50)
    date_added = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now_add=True)

    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

# A model for borrowing a game
class Borrow(models.Model):
    borrow = models.ForeignKey(Boardgame, on_delete=models.CASCADE)
    date_borrowed = models.DateTimeField(auto_now_add=True)
    date_returned = models.DateTimeField(auto_now_add=True)

    owner = models.ForeignKey(User, on_delete=models.CASCADE, default=3)

    def __str__(self):
        return str(self.borrow)```

CodePudding user response:

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.

  • Related