【问题标题】:Question in one of Cory Schafer's tutorials for DjangoCory Schafer 的 Django 教程之一中的问题
【发布时间】:2021-08-07 04:11:57
【问题描述】:

我正在尝试通过观看 Cory Schafer 的 Django 课程来学习 Django,但我只是对 Cory 在注册过程后使用重定向的部分感到困惑。

    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {'form': form})

他使用return redirect('blog-home') 并设法在模板中显示消息Account created for {username}。但我不确定他是如何设法访问模板中的该消息,而无需像我们使用渲染方法所做的那样传递它。

我学到的渲染方法的例子如下,它总是传递第三个参数,这样我们就可以在模板中访问它。但我不知道消息是如何通过重定向方法传递的。

return render(request, 'blog/home.html', context)

【问题讨论】:

  • 您可以将消息视为全局上下文,因此它自动成为上下文的一部分。你可以阅读更多here
  • 消息存储在用户会话或 cookie 中,因此它们在请求中持续存在。当显示消息时,消息存储将被清除
  • @IainShelvington 谢谢,这就解释了为什么只要存储它就可以从任何地方访问。

标签: python django


【解决方案1】:

Django 有一些内置的上下文处理器,它们应用在上下文数据之上,并且在每个模板中普遍可用。 django.contrib.messages.context_processors.messages 就是这样一个。

因此,每个模板都可以普遍访问这些消息。你可以在这里阅读更多内容https://docs.djangoproject.com/en/3.2/ref/templates/api/#django.template.Context。此外,您可以在模板选项中的 settings.py 文件中找到所有上下文处理器的列表 -


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

在这里您可以看到消息上下文处理器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2011-06-10
    • 2015-09-16
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多