Skip to main content
 首页 » 编程设计

python之进行重定向时如何传递模板值

2025年05月04日19zhwl

我使用 blobstoreuploadhandler,因此必须返回一个 self.redirect,但我需要将值传递给我的模板。我该怎么做?如果我不能使用模板值,那么我想我可以使用 session 变量,并且我已经包含了烧杯 session 库,但我不明白如何访问 Django 模板中的 session 变量。知道我应该怎么做吗?

我将默认的内置 django 与谷歌应用引擎一起使用,我可以使用请求处理程序访问 session 变量,但我不知道如何在模板中执行此操作:

class Sessiontest(webapp.RequestHandler): 
    def get(self): 
        # Get the session object from the environ 
        self.session = self.request.environ['beaker.session'] 
 
        # Check to see if a value is in the session 
        if 'counter' in self.session: 
            counter = self.session['counter'] + 1 
            self.session['counter'] = counter 
 
        else: 
            self.session['counter'] = 1 
            counter = 1 
        self.session.save() 
        self.response.out.write('counter: %d' % counter) 

谢谢

更新/编辑:我的问题几乎就是这样Accessing session variable in Django template with Google App Engine (Webapp) - Python但是用图书馆烧杯而不是 gaeutilities

更新:这是一些代码。我们看到使用 HTTP GET 传递值不会很好,因为有一个反垃圾邮件测试应该隐藏值:

def post(self, view): 
    message = '' 
    challenge = self.request.get('recaptcha_challenge_field').encode('utf-8') 
    response  = self.request.get('recaptcha_response_field').encode('utf-8') 
    remoteip  = os.environ['REMOTE_ADDR'] 
    cResponse = captcha.submit( 
                 challenge, 
                 response, 
                 CAPTCHA_PRV_KEY, 
                 remoteip) 
    if cResponse.is_valid: 
        isHuman=True 
    else:#failed anti-spam test and can try again 
        isHuman=False 
        #Reprint the form 
        import util 
        template_values = {'isHuman':isHuman,'user' : users.get_current_user(),} 
        template_values.update(dict(current_user=self.current_user, facebook_app_id=FACEBOOK_APP_ID)) 
        template_values.update(dict(capture=captcha.displayhtml(public_key = CAPTCHA_PUB_KEY, use_ssl = False, error = None))) 
        path = os.path.join(os.path.dirname(__file__), 'market', 'market_insert.html') 
        self.redirect("/ai") # Here the values aren't passed on and I must make a redirect 

请您参考如下方法:

如果您正在进行重定向,您可能必须使用您希望保留在 GET 字符串中的变量进行重定向。所以你从

重定向
/myview/ 

到

/myview2/?variable1=value 

但是,我认为您真的应该看看为什么要进行重定向。我倾向于在 POST 到表单后执行它们,如果用户需要登录,我会使用

重定向到登录屏幕
/authentication/login/?next=/view/they/wanted/to/see 

否则您可以将内容保存在 cookie 中,但这不是继续进行的最佳方式。