Django Admin 并非用于此目的
只有当用户可以完全访问数据库中的所有内容时,才应该使用 Django Admin。他们可以编辑的内容可以受到限制,但通常他们可以看到的内容不应该受到限制。
就只允许访问某些数据位而言,它并不打算允许太多。建议您为此目的构建自定义前端,这样很容易进行此类限制。
这种限制在views 和templates 中很容易实现。使用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 %}