【问题标题】:Manage User Data on Django HTML with passing data通过传递数据管理 Django HTML 上的用户数据
【发布时间】:2022-07-22 21:50:48
【问题描述】:

我正在做 Django 的小示例项目。我正在写博客。

在views.py中,我可以通过将帖子字典传递给渲染函数的第三个参数来渲染index.html和帖子,如下所示。

def home(request):
    posts = post.objects.all() 
    return render(request, 'index.html', {'posts':posts})

通过这样做,我可以使用 HTML 上的帖子数据,如下所示

{% for post in posts %}

<a href="{% url 'detail' post.id %}">
    <h3>{{ post.title }}</h3>
    <h4>{{ post.id }}</h4>
</a>
<p>{{ post.date }}</p>

然而,当我的导师教我如何实现登录/注销功能时,我发现他没有传递用户数据,但他可以管理 HTML 上的“用户”数据,如下所示

{% if user.is_authenticated %}
{{ user.username }}님
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}
def login(request):
    if request.method=='POST':
        username = request.POST['username']
        password = request.POST['password']

        user = auth.authenticate(request, username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html')

    else:
        return render(request, 'login.html')

if user_is_authenticated 如何在不通过views.py 传递“用户”数据的情况下在HTML 上成功呈现?

【问题讨论】:

标签: django


【解决方案1】:

User 上下文对象由设置文件中定义的 django.contrib.auth.context_processors.auth 上下文处理器提供给模板。

https://docs.djangoproject.com/en/2.2/_modules/django/contrib/auth/context_processors/

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2010-11-29
    • 2018-02-13
    相关资源
    最近更新 更多