I am using class-based views (FormView) and I would like to save the search keyword after submitting the form (POST request). I tried this in the form_valid method:
def form_valid(self, form): self.initial['search'] = form.data['search'] ...
but it will show it to all users. This is a fairly common solution for many forms of web search (not to mention Google search), so I wonder how this can be done in Django.
Update: Mon Jun 19 13:18:42 UTC 2017
Based on some answers below, I will have to rephrase my question.
I have a simple form with several input fields, after submitting the form, it will request other sites to get results based on a search query. I would like to save some results in the database, mainly for creating statistics, redisplaying the form with the selected fields and displaying the results.
Currently, data is stored on the class object and passed from POST to GET. This is not a good solution for obvious security reasons:
class SearchView(FormView): ... data = dict() def form_valid(self, form): .... self.data['results'] = results def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['data'] = self.data.pop('results', None) return context
Question:
What would be the best way to display the form (with the selected fields) and the results on the same page, preferably without sessions or storing them in a database between POST and GET.
Points that I have already reviewed:
Do not redirect the user (visualize the template with the current context immediately, while we still have the response object). I don't like the fact that the page refresh will resubmit the form.
Save the answer in some key value storage, for example Redis, and redirect the user to something like the results / {result_id}, where we can get a response from the database to pre-fill the form with data and show the results - this sounds reasonable, but I will need to add another component to pass the POST results to GET.
Use GET for this type of form - I realized that we must use POST to modify the data
source share