Home > Software engineering >  Get all the Booleans of Model accordingly
Get all the Booleans of Model accordingly

Time:11-06

I am building a Blog App and I am trying to get all the Booleans of Profile Model. I tried to make a list of Booleans before but then it was not meeting the requirements.

models.py

class Profile (models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    name = models.CharField(max_length=30)
    first_boolean = models.BooleanField(default=False)
    second_boolean = models.BooleanField(default=False)
    third_boolean = models.BooleanField(default=False)

views.py

def page(request):
    All_Booleans = Profile.objects.filter()

    context = {'Booleans_List'}
    return render(request, 'page.html', context)

I also tried F of from django.db.models import F like :-

All_Booleans = Profile.objects.filter(F(first_boolean=request.user) | F(second_boolean=request.user))

But It is showing __init__() got an unexpected keyword argument 'first_boolean'

What i am trying to do ? :-

I am trying to get all the Boolean fields of Profile Model of request.user

But I have no idea, how can I do it.

Any help would be greatly Appreciated. Thank You in Advance

CodePudding user response:

You can fetch the Profile for the logged in user with:

from django.contrib.auth.decorators import login_required

@login_required
def page(request):
    profile = Profile.objects.get(user=request.user)
    return render(request, 'page.html', {'profile': profile})

in the template you can then render the boolean fields of that profile with:

one: {{ profile.first_boolean }}
two: {{ profile.second_boolean }}
three: {{ profile.third_boolean }}

you can add the booleans to a list and use these in the template as well with:

@login_required
def page(request):
    profile = Profile.objects.get(user=request.user)
    data = [profile.first_boolean, profile.second_boolean, profile.third_boolean]
    return render(request, 'page.html', {'profile': profile, 'data': data})

then you can for example render this with:

{% for item in data %}
    {{ item }}
{% endfor %}

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related