Reputation: 14744
I'd like to submit a form F, clear its fields, but still display one of its fields. F submits to a view that renders the very template that first displayed it
To do so, I return a HttpResponseRedirect
object instead of rendering a template with the request :
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())
and I have {{ request.session.code}}
in my template
Here is an extracts of 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"
)
Thanks!
Upvotes: 0
Views: 37
Reputation: 47876
You can set the code
variable in the session. Then access it using request.session.code
in your template.
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())
Then in your template, you can access code
by:
{{request.session.code}} # display code in the template
You must include django.core.context_processors.request
in the settings.
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request', # will pass request in the template
...
)
From Django 1.7 docs on request context processor:
django.core.context_processors.request
If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain a variable request, which is the current HttpRequest. Note that this processor is not enabled by default; you’ll have to activate it.
Upvotes: 1