只有拥有者或会员才能显示项目 [英] Show project only if owner or member

查看:83
本文介绍了只有拥有者或会员才能显示项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在项目管理应用程序中,我正在努力,如果用户是项目的管理员或项目的成员,我只想显示一个项目。

In the project management app I'm working on I want it only to be possible to show a project if the user is admin of the project or a member of the project.

下面的视图(当然)不起作用,但它显示了一种检查用户是否是项目管理员的方式。我知道如何检查用户是否是成员的一种方法是使用以下查询:

The view below doesn't (of course) work, but it shows one way of checking if the user is admin of the project. One way I know of how to check whether a user is a member or not is by using the following query:

projects = get_list_or_404(Project.objects.filter(users__id__iexact=request.user.id))

...虽然我不知道如何使用这些(如果它们被使用)检查用户是否有权限为此目的查看项目的方式,如果不是这样,则不允许访问。

...though I have no idea of how to use these (if they should be used) ways of checking if the user has permission to view the project for this purpose, and not give access if that is not the case.

如何做?

查看:

@login_required
def show_project(request, project_id):
    project = get_object_or_404(Project, pk = project_id)
    tickets = Ticket.objects.filter(project_id = project_id)

    if project.owned_by_user(request.user):
         ???
    elsif

    else:
        message = "You don't have permission to the project"

    return render(request, 'projects/show.html', {"project" : project, "tickets" : tickets, "message": message})

模型:

class Project(models.Model):
    ...other fields...
    added_by_user = models.ForeignKey(User)
    users = models.ManyToManyField(User, related_name='projects')  <-- members

    def __unicode__(self):
        return self.name

    def owned_by_user(self, user):
        return self.added_by_user == user


推荐答案

我认为你在正确的轨道上。玩这个代码 - 应该给你一些想法 -

I think you're on the right track. Have a play around with this code - should give you some ideas -

@login_required
def show_project(request, project_id):
    project = get_object_or_404(Project, pk = project_id)
    tickets = Ticket.objects.filter(project_id = project_id)
    if request.user in project.users.all or project.owned_by_user(request.user):
        return render(request, 'projects/show.html', {"project" : project, "tickets" : tickets})
    else:
        return render(request, 'projects/show.html', {"error_message": "You don't have permission to view the project"})

然后在您的模板中

{% if error_message %}
    <p>{{ error_message }}</p>
{% else %}
   {% for ticket in tickets %}
        <p>{{ ticket }}</p>
   {% endfor %}
    <div>{{ project }}</div>
{% endif %}

这篇关于只有拥有者或会员才能显示项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆