Reputation: 107
I am building a blog application, and I am trying to get all the Booleans of the Profile
model. I tried to make a list of Booleans before, but then it was not meeting the requirements.
File 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)
File 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 am I trying to do? -
I am trying to get all the Boolean fields of Profile Model
of request.user
But how can I do it ?
Upvotes: 0
Views: 605
Reputation: 476594
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 theUser
model [Django-doc] directly.
For more information, you can see the referencing the User
model section of the documentation.
Upvotes: 1