In Django I have model called Loans. I want users to be able to edit a loan created by someone else, but not if they created it themselves.
As a bonus, I would like staff members not to be able to edit loans that belong to other staff.
How can I do this? I really have no idea. I tried creating custom validation, then I tried a manger like this:
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from core.models import User
class LoanManager(models.Manager):
def create_loan(self, request, borrower, approved, start_date, term_in_months, principal, interest_rate_pa, **extra_fields):
"""Creates and saves a new loan"""
print('USER========================================', request.user)
if borrower != request.user:
raise ValueError("Staff may not lend to themselves or other staff")
return super(LoanManager, self).create(borrower=borrower, approved=approved, start_date=start_date, term_in_months=term_in_months, principal=principal, interest_rate_pa=interest_rate_pa,**extra_fields)
class Loans(models.Model):
borrower = models.ForeignKey(User, on_delete=models.CASCADE)
approved = models.BooleanField(default=False)
start_date = models.DateField(auto_now_add=True)
term_in_months = models.IntegerField(validators=[
MaxValueValidator(360),
MinValueValidator(24)
])
principal = models.IntegerField(validators=[
MaxValueValidator(1000000),
MinValueValidator(2000)
])
interest_rate_pa = models.DecimalField(max_digits=5, decimal_places=2)
objects = LoanManager()
Nothing I do seems to prevent users creating loans for themselves and editing them!