在我正在处理的项目管理应用程序中,如果用户是项目的管理员或项目的成员,我希望它只能显示项目。
下面的视图(当然)不起作用,但它显示了一种检查用户是否是项目管理员的方法。我知道如何检查用户是否是成员的一种方法是使用以下查询:
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
答案 0 :(得分: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 %}