【问题标题】:How to add permissions to edit own in django admin based on value in model?如何根据模型中的值在 django admin 中添加编辑自己的权限?
【发布时间】:2020-02-07 00:48:08
【问题描述】:

我有一个关于 Django-Admin 的问题。我的 Django 管理员中的每个项目都有“EngagementManager”字段,其中包含人名。当您登录 Django 时,您的用户名与我之前提到的字段相同。

当“EngagementManager”字段与登录用户匹配时,我需要实现登录用户只能更改/编辑项目的功能。谁能给我一段代码和一些小指南,请把它放在哪里?

【问题讨论】:

  • 到目前为止您尝试过什么? Stack Overflow 不是代码编写服务,您需要尝试一下,以便我们帮助您修复它。
  • 不多,因为基本上我不知道从哪里开始。一种选择是在 admin.py 中添加如下内容: if obj and obj.EngagementManager == 'XY: 但我不知道这是否是正确的方法。

标签: django django-admin django-permissions


【解决方案1】:

Django Admin 并非用于此目的

只有当用户可以完全访问数据库中的所有内容时,才应该使用 Django Admin。他们可以编辑的内容可以受到限制,但通常他们可以看到的内容不应该受到限制。

就只允许访问某些数据位而言,它并不打算允许太多。建议您为此目的构建自定义前端,这样很容易进行此类限制。

这种限制在viewstemplates 中很容易实现。使用request.user

我现在正在使用手机,但如果您愿意,我可以发布一些示例代码来执行此操作。只需在下面发表评论。

这些是来自我拥有的updateprofile 方法的示例。

这里的核心概念是发送到表单的唯一数据是当前登录帐户的用户的数据。您可能希望实现此类功能。

views.py 检查正确的用户

@login_required(login_url='/login')
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        if user_form.is_valid():
            user_form.save()
            return redirect('/accounts/{}'.format(request.user.username), request.user.username)
        else:
            print("Something broke")
    else:
        user_form = UserForm(instance=request.user) #grabbing the data from that specific user, making sure that is all that is passed. 
    return render(request, 'profile_update.html', {
        'user_form': user_form,
    })

在模板中,if 语句检查页面的用户是否是登录帐户的所有者(并检查他们是否被盗到他们的帐户中),如果是,则向他们显示信息。

用于检查正确用户的模板代码

    {% if page_username == user.username and user.is_authenticated %}
<p>Whatever content you wanted to show to the user who owned the page and was logged in.</p>

{% else %}
<p>Whatever you want to say to users who are not authorized to view the data on the page, if anything.</p>

{% endif %}

【讨论】:

  • @webmourek,检查我的更新,看看它是否满足您的需求。
【解决方案2】:

Django Admin 仅适用于受信任的管理员和内容编辑者,而非普通用户。

如果您需要限制用户只能查看他们自己的内容,那么您应该自己构建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2016-04-01
    • 2011-12-05
    • 2014-06-18
    • 1970-01-01
    • 2018-03-04
    • 2021-07-01
    相关资源
    最近更新 更多