django-两个def在同一个views.py中如何传递数据

时间:2022-12-20 20:29:17

In the same views.py, if I have 2 "def", how can I pass the data entry result in the 1st def to the 2nd def for filtering database?

在相同的views.py中,如果我有2个“def”,如何将第一个def中的数据输入结果传递给第二个def用于过滤数据库?

Take an example:

举个例子:

def input(request):
    if request.method == 'POST':
        form = InputForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            age = form.cleaned_data['age']

            return redirect('result')
       else:
            print form.errors
   else:
       form=InputForm()             
   return render_to_response('inputform.html',{'form': form},context_instance=RequestContext(request))


class ResultView():
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    # Here how can I get the form entry (name/age)from above def to filter the result?                    
    queryset=Result.filter(name=name,age=age)
    scor=Result.objects.filter(queryset)
    subject.Result.objects.filter(queryset)

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)

        return context

url

网址

url(r'^result_list/$',ResultView.as_view(),name='result'),
url(r'^input', 'result.views.input',name='input'),

In the above code, the queryset=Result.filter(name=name,...),here it cannot get the form data from the "def input". Your help is much appreciated, thanks.

在上面的代码中,queryset = Result.filter(name = name,...),这里它无法从“def input”获取表单数据。非常感谢您的帮助,谢谢。

1 个解决方案

#1


1  

class ResultView(ListView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        if self.request.method == 'POST':
            form = InputForm(self.request.POST)
            if form.is_valid():
                name = form.cleaned_data['name']
                age = form.cleaned_data['age']
                return Result.filter(name=name, age=age)
        return super(ResultView, self).get_queryset()

#1


1  

class ResultView(ListView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        if self.request.method == 'POST':
            form = InputForm(self.request.POST)
            if form.is_valid():
                name = form.cleaned_data['name']
                age = form.cleaned_data['age']
                return Result.filter(name=name, age=age)
        return super(ResultView, self).get_queryset()