我想提交表单F,清除其字段,但仍显示其中一个字段。 F提交到一个视图,该视图呈现首先显示它的模板
为此,我返回一个HttpResponseRedirect
对象,而不是使用请求呈现模板:
def home(request):
if request.method == 'POST':
form = New_mini_url_form(request.POST)
if form.is_valid():
if (MiniUrl.objects.filter(url=form.cleaned_data['url']).count() == 0):
code = form.cleaned_data['code']
request.session["code"] = code
[... stuff ...]
return HttpResponseRedirect(reverse(home))
else:
code = form.cleaned_data['code']
request.session["code"] = code
[... stuff ...]
return HttpResponseRedirect(reverse(home))
else:
return render(request, 'mini_url/home.html', locals())
else:
form = New_mini_url_form()
return render(request, 'mini_url/home.html', locals())
我的模板中有{{ request.session.code}}
以下是project / settings.py
的摘录TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request"
)
谢谢!
答案 0 :(得分:1)
您可以在会话中设置code
变量。然后使用模板中的request.session.code
访问它。
def home(request):
if request.method == 'POST':
form = New_mini_url_form(request.POST)
if form.is_valid():
if (MiniUrl.objects.filter(url=form.cleaned_data['url']).count() == 0):
code = form.cleaned_data['code']
request.session['code'] = code # set code in the session
[... stuff ...]
return HttpResponseRedirect(reverse(home))
else:
code = form.cleaned_data['code']
request.session['code'] = code # set code in the session
[... stuff ...]
return HttpResponseRedirect(reverse(home))
else:
return render(request, 'mini_url/home.html', locals())
else:
form = New_mini_url_form()
return render(request, 'mini_url/home.html', locals())
然后在您的模板中,您可以通过以下方式访问code
{{request.session.code}} # display code in the template
您必须在设置中加入django.core.context_processors.request
。
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request', # will pass request in the template
...
)
来自request context processor的Django 1.7文档:
django.core.context_processors.request
如果TEMPLATE_CONTEXT_PROCESSORS包含此处理器,则每个 RequestContext将包含一个变量请求,它是当前的 HttpRequest的。请注意,默认情况下不启用此处理器; 你必须激活它。