简体   繁体   中英

To determine the user's role in the project

In my django website I have pages like 'project_list' and 'project_detail'. Every project has members with different roles (developer, manager, etc). I want to show different buttons depending on the current user's role in the project in template. I need ideas how to realise it. Lets say something like that in template:

{% if request.user.role_in_the_current_project = 'manager' %} SOW SOMETHING {% endif %}

models.py

class Project(models.Model):
    name = models.CharField(max_length=250,)
    slug = models.SlugField(max_length=250, unique_for_date='publication_date',)
    *Other fields*

    def get_absolute_url(self):
        return reverse('project:project_detail', args=[self.slug])

class Membership (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    project = models.ForeignKey(Project, on_delete=models.CASCADE)

    ROLE_CHOICES = (
        ('manager', 'Manager'),
        ('developer', 'Developer'),
        ('business_analyst', 'Business analyst'),
        ('system_analysts', 'System analysts'),
    )

    role = models.CharField(max_length=20, choices=ROLE_CHOICES,)

view.py

def project_detail(request, slug):
    project = get_object_or_404(Project, slug=slug, status='public')
    return render(request, 'project/project_detail.html', {'project': project,})

project_detail.html

{% block content %}
   <h1>{{ project.name }}</h1>
   <p>{{ project.description|linebreaks }}</p>
{%endblock %}

urls.py

urlpatterns = [
    url(r'^project/(?P<slug>[-\w]+)/$', project_detail, name='project_detail'),
]

You can use the concept of choices inside a model field and then by using these you can make decisions inside your templates (or to your views) to show appropriate content.

Let me know if you need more info on this.

[EDIT]: So, what you want is to check each time the value of role . Right?

In your views.py write:

project = get_object_or_404(Project, slug=slug, status='public')
memberships = project.membership_set.all()

Then because one project can have many Membership records you should iterate over the memberships to get each time the role .

So, in your template:

{% for membership in memberships %}
    {% if membership.role == 'Manager' %} Do stuff here {% endif %}
{% endfor %}

Note that .role will give you back the second value of the ROLE_CHOICES sub-tuple which is capitalized, while the first one is that will be shown in the user if you use the function get_role_display()

Well, after all I found solusion. In view I add:

is_manager = project.membership_set.filter(user=request.user, role='Manager').exists()

Then in template I add:

{% if is_manager %}
    <button>Create</button>
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM