【问题标题】:How to access & modify Django template context variables如何访问和修改 Django 模板上下文变量
【发布时间】:2011-03-08 01:48:23
【问题描述】:

在我的 urls.py 中,我将 url accounts/login/ 映射到登录模块,并引用了我要使用的模板:

url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'templates/login.html'})

这很好用,但我想更改next 属性的值,该属性指定用户在成功登录后应重定向到的位置。如何访问这些变量并打印它们的值,更重要的是如何修改它们?

谢谢!

【问题讨论】:

  • 您实际阅读了 Django 文档的哪一部分?尝试阅读有关docs.djangoproject.com/en/1.2/ref/templates/api/… 的信息,然后更新您的问题以更具体。
  • culov,你试图在你的 urls.py 中做太多事情。没有办法在那里指定模板。

标签: python django django-templates


【解决方案1】:

将 url 指向一个视图:

(r'^accounts/login/', 'myproj.login.views.mylogin')

然后在你的视图代码中处理重定向:

def mylogin(request, **kwargs):
    if request.user.is_authenticated():
        if 'next_url' in request.session:
            url = request.session['next_url']
            del request.session['next_url']  # Cleaning next_url val
            return HttpResponseRedirect('/%s' % url)
        else:
            return HttpResponseRedirect('/')
    return login(request, **kwargs)

@csrf_protect
def login(request, template_name='registration/login.html'):
    """Displays the login form and handles the login action."""
    retval = django.contrib.auth.views.login(request, template_name)
    clear_session_data(request.session)
    return retval

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2019-12-05
    • 2017-01-29
    • 2013-09-18
    相关资源
    最近更新 更多