gpt4 book ai didi

python - cookie 中的执行错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:55 25 4
gpt4 key购买 nike

更新:我已经用图片更新了我的帖子,请现在看看我到底想要什么:

我的首页:

enter image description here

用户输入了“姓名”这个词。

enter image description here

用户按下搜索后,用户将获得列表和图表,但您可以看到“名称”一词更多地保留在搜索栏中,但我希望它在那里。

现在你明白我的问题了吗?

我的views.py文件代码:

#!/usr/bin/python 

from django.core.context_processors import csrf
from django.template import loader, RequestContext, Context
from django.http import HttpResponse
from search.models import Keywords
from django.shortcuts import render_to_response as rr
import Cookie

def front_page(request):

if request.method == 'POST' :
from skey import find_root_tags, count, sorting_list
str1 = request.POST['word']
str1 = str1.encode('utf-8')
list = []
for i in range(count.__len__()):
count[i] = 0
path = '/home/pooja/Desktop/'
fo = open("/home/pooja/Desktop/xml.txt","r")

for i in range(count.__len__()):

file = fo.readline()
file = file.rstrip('\n')
find_root_tags(path+file,str1,i)
list.append((file,count[i]))

for name, count1 in list:
s = Keywords(file_name=name,frequency_count=count1)
s.save()
fo.close()

list1 = Keywords.objects.all().order_by('-frequency_count')
t = loader.get_template('search/front_page.html')
c = RequestContext(request, {'list1':list1,
})
c.update(csrf(request))
response = t.render(c)
response.set_cookie('word',request.POST['word'])
return HttpResponse(response)

else :
str1 = ''
template = loader.get_template('search/front_page.html')
c = RequestContext(request)
response = template.render(c)
return HttpResponse(response)

我使用 django 搜索创建了一个应用程序,该应用程序在 10 个 xml 文档中搜索关键字并返回每个文件的关键字出现频率,这些文件显示为 xml 文档的超链接列表及其各自的计数和图表。

在服务器上运行应用程序时,当用户在搜索栏中输入单词时,结果会完美地显示在同一页面上,但当用户按下搜索选项卡时,该单词不会保留在搜索栏中。为此,我使用了 cookie,但它给出了错误

'SafeUnicode' object has no attribute 'set_cookie'

为什么?我是 django 的新手,所以请帮忙

最佳答案

我猜您想使用 cookie,这应该可以帮助您入门:https://docs.djangoproject.com/en/dev/topics/http/sessions/?from=olddocs/#using-cookie-based-sessions

然后我们有这个Django Cookies, how can I set them?

从根本上设置您需要的 cookie:

 resp = HttpResponse(response)
resp.set_cookie('word', request.POST['word'])

要获取 cookie,您只需要 request.COOKIES['word'] 或者更安全的方法是 request.COOKIES.get('word', None)

from django.shortcuts import render_to_response
...

c = {}
c.update(csrf(request))
c.update({'list1':list1, 'word':request.POST['word']})
return render_to_response('search/front_page.html', 
      c,
      context_instance=RequestContext(request))

在您的模板上,您应该更新搜索栏字段:

<input type="text" name="word" value="{{ word }}" />

请在有机会时仔细阅读整个文档,是的,我知道它们相当广泛,但它们非常值得......

关于python - cookie 中的执行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11426038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com