1

在我正在开发的项目管理应用程序中,我希望只有在用户是项目管理员或项目成员时才能显示项目。

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

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

...尽管我不知道如何使用这些(如果应该使用)方法来检查用户是否有权为此目的查看项目,如果不是这样,则不授予访问权限。

怎么可能做到这一点?

看法:

@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
4

1 回答 1

0

我认为你在正确的轨道上。试一试这段代码——应该会给你一些想法——

@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 %}
于 2013-03-05T20:07:20.633 回答