Reputation: 211
I have this form that collects data from a user. After the data has been entered I use HttpResponseRedirect to protect from a refresh. The problem is since I am not using a database for this app, I can't work out how to render the data the user has entered.
At the moment the data I need to be rendered is stored in cd. So how can I still redirect the user after sucessful data entry and pass the data to another view, then render it? I can pass it to another class view, but rendering it is the problem, as the data is passed by MathsConfig and not through urls.
Thanks, sorry I am new to Django.
code below
views.py
class MathsConfig(View):
form_class = MathsForm
initial={'operation': "Addition",
'rows': "",
"between1": "1 - 99",
"between2": "1 - 99",
"between3": None,
"between4": None,
"between5": None,
"questions": 20,
}
template_name = 'maths/maths-config.html'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
cd = form.cleaned_data
return HttpResponseRedirect(reverse('maths:maths_success'))
return render(request, self.template_name, {'form': form})
class MathsQuestions(object):
def __init__(self):
# want to pass cd varible here and then render it.
class MathsSuccess(TemplateView):
template_name = "maths/maths-success.html"
urls.py
urlpatterns = patterns('',
url(r'^config/$', views.MathsConfig.as_view(), name='maths_config'),
url(r'^success/$', views.MathsSuccess.as_view(), name='maths_success'),
url(r'^$', views.MathsQuestions(), name='maths_display'),
)
Edit:
class MathsQuestions(Object):
def __init__(self, request):
if 'entered_form_data' in request.session.keys():
formdata = request.session['entered_form_data']
del request.session['entered_form_data']
Upvotes: 0
Views: 2405
Reputation: 5656
Store it in session.
request.session['entered_form_data'] = data
And in next view:
if 'entered_form_data' in request.session.keys():
formdata = request.session['entered_form_data']
del request.session['entered_form_data']
Edit:
def someview(request):
template = 'something.html'
form = SomeForm(request.POST) if request.method == 'POST' else SomeForm()
if request.method == 'POST':
if form.is_valid():
data = form.get_cleaned_data()
request.session['entered_form_data'] = data
return HttpResponseRedirect('/someurl/')
render_to_response(template, {'form':form}, context_instance=RequestContext(request))
def someurl_view(request):
template = 'someurl.html'
render_to_response(template, {'formdata':request.session.pop('entered_form_data', None)}, context_instance=RequestContext(request))
and of course you need to create the function, that returns data from form yourself. I mean the function which i refer to as form.get_cleaned_data(). Do it whichever way you want although i suggest you return dictionary.
Upvotes: 2