相应地获取模型的所有布尔值

Get all the Booleans of Model accordingly

我正在构建一个 博客应用程序 ,我正在尝试获取 Profile 模型的所有布尔值。之前试过做一个布尔列表,后来发现不符合要求

文件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)

我也试过 F of from django.db.models import F 像:

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

但是显示:

init() got an unexpected keyword argument 'first_boolean'

我想做什么? -

我正在尝试获取 request.user

Profile Model 的所有布尔字段

但是我该怎么做呢?

您可以通过以下方式获取已登录用户的 Profile

from django.contrib.auth.decorators import login_required

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

然后您可以在模板中呈现 profile 的布尔字段:

one: {{ <strong>profile.first_boolean</strong> }}
two: {{ <strong>profile.second_boolean</strong> }}
three: {{ <strong>profile.third_boolean</strong> }}

您可以将布尔值添加到列表中并在模板中使用它们:

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

然后你可以,例如,渲染这个:

{% for <b>item in data</b> %}
    {{ 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.

更多信息,您可以查看referencing the User model section of the documentation.