【问题标题】:Create cookies when user clicks a button当用户单击按钮时创建 cookie
【发布时间】:2015-06-01 07:09:07
【问题描述】:

我希望当一个人点击我页面上的按钮时,调用视图中的一个函数,该函数在用户的机器上创建 cookie,然后将 cookie id 存储在我的模型中。

模板(HTML 页面):

<form action="#" method="get">
        <p style="text-align: center;"> 
            <input type="submit" class="optOutButton" value="Opt-Out" name="optOutButton"> </p>
    </form>

Views.py

class UserOptOut(TemplateView):
    template_name = 'debug/opt-out-child.html'    

    def user_opt_out(request):
        if(request.GET.get('optOutButton')):
            response = HttpResponse('Hahahaha')
            response.set_cookie('id', 1)
            return response
        if request.COOKIES.has_key( 'id' ):
            value = request.COOKIES[ 'id' ]
        return render_to_response(debug/opt-out-child.html)

但是,当我单击按钮时,什么也没有发生。有人可以帮我解决我做错了什么吗?

【问题讨论】:

  • 可能 GET # 被浏览器视为空操作,什么都不做。尝试使用 action="?R={{random}}"。否则在我看来它应该可以工作。

标签: python django cookies


【解决方案1】:

user_opt_out 不是在 TemplateView 中自动调用的方法。你应该把它放在get 方法中。

尽管你显式渲染并从你的方法返回一个完整的响应,但我不知道你为什么使用基于类的视图:只使用普通的视图函数。

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多