我想檢查user.profile是否有權根據成員包查看所有利益對象。 (如果用戶沒有訪問權限,他應該能夠看到對象的某些字段(名稱和包)檢查用戶是否有權訪問對象
如果用戶有成員包Package1
並且正在查看Package1
中的權益,他應該能夠看到body
領域。如果用戶memberpackage Package2
他不應該能夠看到body
領域。
這是可能的嗎?也許這可以用templatetag做?{% if user_has_access_to_benfit %}
,它會返回true或false。
類似這樣的:
{{ object.name }}
{% if user_has_access_to_benfit %}
{{ object.body }}
{% else %}
<p>Sorry! You don't have access to this object.</p>
{% endif %}
-
這是我曾經嘗試過,根據答案:
class Profile(models.Model):
user = models.OneToOneField(User)
memberpackage = models.ForeignKey(Package, blank=True, null=True)
class Package(models.Model):
name = models.CharField(max_length=200)
class Benefit(models.Model):
PUBLISHED = 'P'
DRAFT = 'U'
PULLED = 'X'
name = models.CharField(max_length=200)
body = models.TextField(blank=True, null=True, help_text="Only visible to those members in the same memberpackage")
package = models.ManyToManyField(Package, blank=True, null=True, related_name="in_package")
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=DRAFT)
def is_viewable_by(self, user):
return self.package.filter(id=user.profile.memberpackage_id).exists()
編輯:
如果我這樣做(與效益的資本B)
#View for listing one benefit
class BenefitDetailView(DetailView):
template_name_field = 'template_name'
model = Benefit
queryset = Benefit.objects.exclude(status="X")
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
context['user_has_access_to_benfit'] = Benefit.is_viewable_by(request.user)
我收到此錯誤:
unbound method is_viewable_by() must be called with Benefit instance as first argument (got User instance instead)
編輯2:
嘗試另一種方式
#View for listing one benefit
class BenefitDetailView(DetailView):
template_name_field = 'template_name'
model = Benefit
queryset = Benefit.objects.exclude(status="X")
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
user_has_access_to_benfit = Benefit.objects.filter(package = request.user.profile.memberpackage).exists() #Hoping this function returns true or false
#The user is not logged in, user_has_access_to_benfit should be set to False
else:
user_has_access_to_benfit = False
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(BenefitDetailView, self).get_context_data(**kwargs)
# Add in a extra context
context['user_has_access_to_benfit'] = user_has_access_to_benfit
return context
但我得到的錯誤:The view app.views.BenefitDetailView didn't return an HttpResponse object.
不知道是否存在的DetailView獲得request.user.is_authenticated()
的另一種方式?
這是完美的!謝謝。當我被允許時,我會獎賞你的賞金。 –