在Django中动态删除下拉选项

时间:2014-08-14 21:23:35

标签: python django

我需要在用户未经过身份验证时隐藏下拉列表中的选项。

class JobPostingListView(ListView):
    form_class = JobPostingSearchForm
    model = JobPosting
    template_name = 'recruiters/job_posting_list.html'

    def get_queryset(self):

        form = self.form = self.form_class(self.request.GET)

    ......


    def get_context_data(self, **kwargs):

        context_data = super(JobPostingListView, self).get_context_data(**kwargs)

        if not self.request.user.is_authenticated():
            del self.form.fields['date_posted'].choices[1]

        #Ok, It shows all except choice one
        print self.form.fields['date_posted'].choices 

        #It doesn't work here because it shows all the choices 
        print self.form                               

        context_data.update({
            'form': self.form                         
        })

        return context_data

注意:代码位于视图中,因为我无法访问表单中的is_authenticated

表单显示所有选项,我想隐藏选择

1 个答案:

答案 0 :(得分:0)

一位同事帮助了我。

  1. 内部get_queryset功能。
  2. 致电form.fields['date_posted'].widget.choices.pop(1)以便在没有选择的情况下显示表单。
  3. 调用form.fields['date_posted'].choices.pop(1)以避免用户修改html并在这种情况下发送无效选项。

    class JobPostingListView(ListView):
        form_class = JobPostingSearchForm
        model = JobPosting
        template_name = 'recruiters/job_posting_list.html'
    
        def get_queryset(self):
    
            form = self.form = self.form_class(self.request.GET)
            if not self.request.user.is_authenticated():
                form.fields['date_posted'].choices.pop(1)
                form.fields['date_posted'].widget.choices.pop(1)
        ...