Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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?

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading