问题
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.
How could this be done?
view:
@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})
model:
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
回答1:
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"})
Then in your template
{% if error_message %}
<p>{{ error_message }}</p>
{% else %}
{% for ticket in tickets %}
<p>{{ ticket }}</p>
{% endfor %}
<div>{{ project }}</div>
{% endif %}
来源:https://stackoverflow.com/questions/15232954/show-project-only-if-owner-or-member