I have a form, after entering the information, based on infomation it filters the database and do some calculation and finally displays the result to a redirected url.
Your code should work if you change your get_queryset
method to:
def get_queryset(self):
# You are sending GET params here, not POST
form = InputForm(self.request.GET)
if form.is_valid():
company = form.cleaned_data['company']
region = form.cleaned_data['region']
queryset=Result.objects.filter(region=region)
return queryset
return Result.objects.all()
and your get_context_data
method to:
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context["sales"] = self.get_queryset().aggregate(Sum('sales'))
# Your variables are in GET, not POST
context["company"] = self.request.GET.get("company")
context["region"] = self.request.GET.get("region")
return context
That said, your code could do with some refactoring. Do you really need the FormView
that accepts a POST request? You could instead have a form that submits directly via GET to your result view.
With your current approach you are actually processing the form twice - once in each of your views.
Edit: also, they way you are generating your redirect url isn't safe. You should so something like this instead:
import urllib
def get_success_url(self):
params = {
'company': self.request.POST.get('company'),
'region': self.request.POST.get('region')
}
return ''.join([reverse('result'), '?', urllib.urlencode(params.items())])
If you make POST request, and after that you're redirecting user, the next request will have empty POST (since now it it another request). So, it is not a surprising behaviour. If you want to save this data between session, you can save it in the user session, for example.
You can modify some of you views (which making redirect, I believe) by adding this code:
Setting a cookie:
def your_view_which_makes_redirect(request):
#.. here is your code
response = HttpResponse( 'blah' )
request_form_data = request.POST #you need to sanitize/clear this data
response.set_cookie('form_data', request_form_data)
Getting cookie:
def your_view_which_renders_page_after_rediret(request):
if request.COOKIES.has_key('form_data'):
value = request.COOKIES['form_data'] #this data also should be sanitized
1) Also you can move name of this cookie to the settings because now they are hardcoded and it is now very good practice. Something like settings.SAVED_FORM_NAME_COOIKE_TOKEN 2) You also have to sanitize data from request.POST and request.COOKIES, because user can place there some malicious data (SQL injection and so on).