N
N
nurzhannogerbek2017-03-08 19:14:41
Django
nurzhannogerbek, 2017-03-08 19:14:41

How to display something in the template depending on the value of the model field (choices)?

Faced the following problem. The site has two pages: 'project_list'(Project List Page) and 'project_detail'(Project Detail Page). Each project has team members (users) with different roles in this particular project (For example: manager, developer, etc.). How to display something in the template (in project_detail) depending on the role of the current user in this project. For example, if the current user in this particular project is manager, show a button, if developer then a text message. The model looks like this:
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,})

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

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

  <!--НЕ РАБОТАЕТ-->
  {% if request.user.project.membership__role == 'manager' %}
      <button>Create</button>
   {% endif %}
{%endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Bryukhanov, 2017-03-08
@drupa

{% for user in request.user.membership_set.all %}
  {{user.role}}
{% endfor %}

if you used OneToOneField
class Membership(models.Model):
    user = models.OneToOneField(User, 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,)

then it could be done
like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question