django - 无法从 django 中的会话字典的键中提取值
问题描述
我有一个会话变量,用于从用户输入表单保存在我的 django 视图中的公司名称。当我尝试在以后的视图中使用它时,无论我尝试什么,它都会拉出 {key: value} 对而不仅仅是值
意见:
def start(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = QuizTakerForm(request.POST )
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
post = form.save(commit=False)
post.user = request.user
post.save()
request.session['obj_id'] = post.id
request.session['company_name'] = form.cleaned_data
# redirect to a new URL:
return HttpResponseRedirect('industry/')
....
def Gov_q1(request):
company_name = request.session.get('company_name')
print(company_name)
question = Question.objects.get(pk=24)
context = {'question': question, 'company_name': company_name}
return render(request, 'ImpactCheck/detail.html', context)
html:
<h1> Hi my name is {{ company_name }} </h1>
<h1>{{ question.text }}</h1>
<form action="." method="post">
{% for answer in question.answer_set.all %}
<input type="radio" name="answer" id="answer" value="{{ answer.id }}">
<label for="answer">{{ answer.answer_text }}</label><br>
{% endfor %}
<input type="submit" value="Submit">
</form>
我也尝试过 company_name=request.session['company_name'],但两者都呈现为 {'company_name': 'test_company'} 而不是 test_company。
解决方案
仅供参考,如果有人有类似的问题,我已经绕过使用
def Gov_q1(request):
id=request.session.get('obj_id')
company_name= QuizTakers.objects.get(pk=id)
question = Question.objects.get(pk=24)
context = {'question': question, 'company_name': company_name, 'cn': cn}
return render(request, 'ImpactCheck/detail.html', context)
推荐阅读
- amazon-web-services - EMR_EC2_DefaultRole 和 EMR_DefaultRole 有什么不同?
- java - 如何在 Java Reactor 中设置完全背压驱动的通量?
- laravel - 运行 php artisan queue 时出错:在服务器上工作
- lotus-notes - 如何从 Lotus Script 中的 NotesDateTime 数组计算平均时间
- c# - 如何验证用户在 c# 中输入两个特定字母
- python - 对相似值进行分组
- windows - 是否可以在文件中搜索字符串并将文件名批量显示为变量
- c# - 向 JWT Token 验证添加自定义函数
- mysql - 在现有列之后添加新列并使用一条语句 DROP 现有列 MYSQL
- java - 获取 Timestamp.valueOf 的不同值