django- why after redirecting, the form display “None”

前端 未结 2 465
情话喂你
情话喂你 2021-01-18 18:51

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.

2条回答
  •  长情又很酷
    2021-01-18 19:20

    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())])
    

提交回复
热议问题