Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send form data from views to template

Edit:
I want the 'success_url' (ie, result.html) to display the 'data' from 'form.process()'. The following code obviously doesn't work. Can anyone please tell me what's wrong with it or suggest another way to basically view the context 'data' in a template (either in the form of list or dict), ie a better way to display data to the user after a form has been submitted.
Many thanks in advance.

-- urls.py --
url(r'^$', view='main_view'),
url(r'^result/$', view='result_view'),

-- views.py --
class ResultView(TemplateView):
    template_name = "result.html"

class MainView(FormView):
    template_name = 'index.html'
    form_class = UserInputForm
    success_url = 'result/'

    def form_valid(self, form):
        data = form.process()
        return super(MainView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(MainView, self).get_context_data(**kwargs)
        context['data'] = data
        return context

main_view = MainView.as_view()
result_view = ResultView.as_view()
like image 759
DGT Avatar asked Dec 20 '22 15:12

DGT


2 Answers

As far as I understood your question, you want to show the contents of the user submitted form in the result view. Is that correct?

In this case the method get_context_data won't help you at all, because it will only store data in the current context which is in MainView.

The form_valid method of FormView will make a HttpResponseRedirect to the success_url. So the question now is, how can we give the data to this view.

As explained in Django return redirect() with parameters the easiest way would be to put the data into the session. In the result.html-template you could then access this data as explained in Django: accessing session variables from within a template?

Here is the code:

class ResultView(TemplateView):
    template_name = "result.html"

class MainView(FormView):
    template_name = 'index.html'
    form_class = UserInputForm
    success_url = 'result/'

    def form_valid(self, form):
        self.request.session['temp_data'] = form.cleaned_data
        return super(MainView, self).form_valid(form)

in the result.html template you could then access this temp_data so:

{{ request.session.temp_data }}
like image 53
DanEEStar Avatar answered Dec 28 '22 07:12

DanEEStar


As suggested above, you can override get_context_data.

For example, you can do something like the below:

def get_context_data(self, **kwargs):
    context = super(MainView, self).get_context_data(**kwargs)
    #set some more context below.
    context['foo'] = bar
    ...
    return context
like image 26
kranthi jajula Avatar answered Dec 28 '22 07:12

kranthi jajula