Django:在基于类的视图GET请求中更改URL

时间:2018-04-11 14:40:01

标签: python django url

您好我有两种形式渲染到同一个模板。

当我提交runsearchform时,它会将我带到页面:

 localhost/reporting/?run=2&submit=Search+for+run

其中2是我的运行PK id

如何将此网址修改为

 localhost/reporting/run_name

其中run_name =我的运行模型中不是主键的唯一字段

的观点:

class ReportView(View):

    runsearchform = RunSearchForm
    samplesearchform = SampleSearchForm

    def get(self, request, *args, **kwargs):

        runsearchform = self.runsearchform()
        context = {'runsearchform': runsearchform}

        if 'run' in request.GET:
            samplesearchform = self.samplesearchform(request.GET)
            context = {'samplesearchform': samplesearchform}


        return render(request, 'results/reporting.html', context)



    def post(self, request, *args, **kwargs):

        """ do stuff with samples...
        """

1 个答案:

答案 0 :(得分:0)

您可以在run_name中指定urls.py,例如:

url(r'^(?i)reporting/(?P<run_name>[a-z0-9]+)/$', myapp.views.ReportView.as_view())

然后您的视图可以接收参数,例如:

class ReportView(View):

    runsearchform = RunSearchForm
    samplesearchform = SampleSearchForm

    def get(self, request, run_name):
        # Load the report based on the run_name, and do something with it

当请求例如localhost/reporting/myreportrun_name参数将设置为myreport