Home > database >  How to fetch a boolean value from models for a specific user in Django?
How to fetch a boolean value from models for a specific user in Django?

Time:10-21

I have an extended user model and I want to check it to see if the logged-in user has completed_application as per the model:

Models.py:

class Completed(models.Model):
class Meta:  
    verbose_name_plural = 'Completed Application'
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
completed_application = models.BooleanField(default=False)

def __str__(self):
    return f'{self.completed_application}'

Views.py:

@login_required
def dashboard(request):
    if Completed.objects.get(completed_application = True):
        completed = True
    else:
        completed = False
        
    return render(request, 'dashboard.html', {'section': 'dashboard', 'completed' : completed})

HTML:

{% if completed %}
<!-- You already completed an application! -->
<h1> Already completed </h1>
{% else %}
<!-- Show the application form -->
<h1> Render model form here </h1>
{% endif %}

The code above is not working for me as it returns True every time. I read quite a few posts on here but they don't seem to be user specific such as: How to show data from django models whose boolean field is true?

CodePudding user response:

Hi the problem is you have to change your queryset

Completed.objects.get(completed_application ...etc

To:

Completed.objects.filter(completed_application=True,user=request.user).exists()
  • Related