0

Can someone say where I did mistake?

I have 2 models: Project and Purpose.

class Purpose(models.Model):
    code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    text = models.TextField(_('Text'))
    comments = models.ManyToManyField("Comment")

Every project has only one purpose. So in project_detail page I want to show purpose_add button only if that project dont have any other purpose object. Why I dont see button when there is no Purpose object with the same project_code?

views.py:

def project_detail(request, project_code):
 ***
 purpose_is_not_exist = Purpose.objects.exclude(project=project_code).exists()
 ***

project_detail.html:

{% if purpose_is_not_exist %}
   <button id="purpose-add-button"></button>
{% endif %}
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

2 Answers2

2
{% if not purpose_is_not_exist %}

You should negate the False bool.

Andrey Shipilov
  • 1,986
  • 12
  • 14
2

The confusion is caused by the variable name purpose_is_not_exist.

Purpose.objects.exclude(project=project_code).exists()

Above statement returns whether the Purpose object exists. You shall rename the variable to purpose_exists to avoid any confusion.

And, in the template when you want to add the button if it doesn't exist then negate the variable:

{% if not purpose_exists %}

Alternatively, if you would like to keep using the original name for the variable, then just negate in the view itself.

purpose_is_not_exist = not Purpose.objects.exclude(project=project_code).exists()
AKS
  • 18,983
  • 3
  • 43
  • 54