我的权限类有问题-我不知道为什么向用户添加权限无法按我的意愿工作。我喜欢它如何工作->在单击带有用户列表的站点中的按钮后,他获得了查看下载特定文件的权限。
提供权限的类(在views.py中):
class GiveBetaPermission(LoginRequiredMixin, AccountTypeRequiredMixin, RedirectView):
model = BetaSoftware
account_type_required = ['admin', ]
url = reverse_lazy('accounts:client-list')
success_message = _("Permission granted.")
def get(self, request, *args, **kwargs):
user = get_object_or_404(User, pk=kwargs.get('pk'))
perm_name = 'softwares.view_beta'
perm = Permission.objects.get(
content_type=ContentType.objects.get_for_model(BetaSoftware),
codename='view_beta')
assert perm_name == '{}.{}'.format(perm.content_type.app_label, perm.codename)
print('check before add:', user.has_perm(perm))
user.user_permissions.add(perm)
user.save()
user = get_object_or_404(User, pk=kwargs.get('pk'))
print('check after add:', user.has_perm(perm))
return super(GiveBetaPermission, self).get(request, *args, **kwargs)
型号:
class BetaSoftware(models.Model):
(some working download code)
class Meta:
permissions = (
("view_beta","view_beta"),
)
表格操作代码(提供访问权限的按钮)
{% if user.account_type == 'admin' %}
{% if not softwares.view_beta %}
<a href="{% url 'softwares:beta-permission' pk=record.pk %}" data-toggle="tooltip" data-placement="bottom" title="{% trans "Beta test access" %}"><i class="fa fa-fw fa-bold"></i></a>
{% endif %}
{% endif %}
经许可即可使用的HTML代码:
{% if softwares.view_beta %}
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> {% trans "Beta Software" %}
</div>
<div class="card-body">
{% if user_has_licences %}
<div class="form-group row align-items-center">
<div class="col-sm-3">{% trans "Download the beta software:" %}</div>
<div class="col-sm-9">
<a href="{% url 'softwares:betadownload' %}" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title=""
data-original-title="Download software"><i class="fa fa-fw fa-download"></i> {% trans "Download" %}</a>
</div>
</div>
{% else %}
<div class="form-group row">
<div class="col-sm-8">{% trans "No available beta software, user have no licenses." %}</div>
</div>
{% endif %}
</div>
</div>
{% endif %}
Django版本:1.1 Python版本:3.6 谢谢你的帮助!