简体   繁体   English

如何访问和修改Django模板上下文变量

[英]How to access & modify Django template context variables

In my urls.py, I map the url accounts/login/ to the login module, with a reference to the template i want to use: 在我的urls.py中,我将url account / login /映射到登录模块,并引用了要使用的模板:

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

This works fine, but I want to change the value of the next property, which specified where the user ought to be redirected after a successful login. 这可以正常工作,但是我想更改next属性的值,该属性指定在成功登录后应将用户重定向到的位置。 How can I access these variables and print their values, and more importantly, how can I modify them? 如何访问这些变量并打印它们的值,更重要的是,如何修改它们?

Thanks! 谢谢!

Direct the url to a view: 将网址定向到视图:

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

Then handle redirection in your view code: 然后在您的视图代码中处理重定向:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM