在Django中,我有一个名为Loans的模型。我希望用户能够编辑其他人创建的贷款,但是如果他们自己创建,则不能。
作为奖励,我希望工作人员不能编辑属于其他工作人员的贷款。
我该怎么做?我真的不知道。我尝试创建自定义验证,然后尝试了如下方式:
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()
我似乎并没有阻止用户为自己创建贷款并进行编辑!
答案 0 :(得分:0)
在视图中使用混合。下面的示例应检查当前用户是否是贷款对象的借款人。如果它们相同,则会阻止访问。
class MyLoanMixin (object):
permission_denied_message = "You may not modify your own loan"
def dispatch (self, request, *args, **kwargs):
if self.get_object().borrower == request.user:
raise PermissionDenied(self.get_permission_denied_message())
return super().dispatch(request, *args, **kwargs)
def get_permission_denied_message(self):
"""
Override this method to override the permission_denied_message attribute.
"""
return self.permission_denied_message
def handle_no_permission(self):
if self.raise_exception:
raise PermissionDenied(self.get_permission_denied_message())
return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())