在我的Django应用程序中,我对某些模型进行了一些CRUD操作,我想只能由创建该行的用户访问它。这里不是基于角色的授权,因为所有用户都是相同的,我希望它们由创建它的用户识别。
我尝试过类似的事情:
class someModel(models.Model):
user = models.ForeignKey(User, db_index=True)
....
在我的观点中,我会通过以下方式进行检查:
def view(request, id):
model = somemodel.objects.get(id=id, user=request.user)
if model.user = request.user:
...
这是否是最简单但却是行级授权的正确方法?
答案 0 :(得分:1)
理想情况下,需要检查使用是否经过身份验证的视图可以包含login_required装饰器。然后你可以使用try,除了if而不是因为那更加pythonic
@login_required
def view(request, id):
try:
model = somemodel.objects.get(id=id, user=request.user) #this will raise an exception if not found
except Somemodel.DoesnotExist:
return HttpResponseRedirect('/login')
这当然开始像锅炉板一样。这就是基于类的视图进入图片的地方。或者,您可以使用
减少锅炉板代码@login_required
def view(request, id):
my_object = get_object_or_404(SomeModel, pk=1, user=request.user)
# get_object_or_404 also throws a MultipleObjectsReturned exception
# when more then one object is returned, so catch it if needed.
答案 1 :(得分:0)
您甚至可以减少一行检查if model.user = request.user:
,因为您已使用model = somemodel.objects.get(id=id, user=request.user)
中的登录用户过滤了数据
答案 2 :(得分:0)
class getUserData(APIView):
def get(self, request, format=None):
userName = request.data['userName']
try:
checkUserLoggedIn = YourAuthenticationModel.objects.get(id=id, user=userName)
getRow = someModel.objects.filter(user=userName)
except ObjectDoesNotExist:
print "User does not exist or logged In"