Django ModelChoiceField没有使用新数据进行更新

Han*_*ank 3 django django-forms

使用Django 1.7,我有一个ModelChoiceField在更新基础数据时不会更新.要显示新数据行,我需要重新启动Web服务器.

Django Form,Field,View:

class JobsModelChoiceField(forms.ModelChoiceField):

    def __init__(self, *args, **kwargs):
        super(JobsModelChoiceField, self).__init__(*args, **kwargs)
        groups = groupby(sorted(kwargs['queryset'], key=attrgetter('company')), attrgetter('company'))
        self.choices = [(company, [(t.id, self.label_from_instance(t)) for t in title])
                        for company, title in groups]

    def label_from_instance(self, job):
        return u'{} {}'.format(job.id, job.title)

class NewApplicationForm(forms.Form):
    id = JobsModelChoiceField(queryset=Job.objects.all(),
                                widget=forms.Select(attrs={'class':'chosen-select'}))
    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name')
    email = forms.EmailField(label='Email')
    phone_number = forms.CharField(label='Phone Number', max_length=42, required=False)
    resume = forms.FileField()

    def save(self):
        # save data

class NewApplicationView(SuccessMessageMixin, FormView):

    template_name = 'applicants/new_application.html'
    form_class = NewApplicationForm
    success_url = reverse_lazy('applicants:add')
    success_message = "Job Application was created successfully"

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.save()
        return super(NewApplicationView, self).form_valid(form)
Run Code Online (Sandbox Code Playgroud)

我得到的一个问题是,如果我在jobs表中添加一个新行,那么在我重新启动Web服务器之前,新行不会显示在表单选择字段中.

FSp*_*FSp 7

这是因为表单的字段是静态填充的,而不是动态填充的(即不是每次实例化表单时).您应该在表单__init__方法中指定表单queryset ,如下所示:

class NewApplicationForm(forms.Form):
    id = JobsModelChoiceField(queryset=Job.objects.none(), ...)

...


    def __init__(self, *args, **kwargs):
        super(NewApplicationForm, self).__init__(*args, **kwargs)
        self.fields['id'].queryset = Job.objects.all()
Run Code Online (Sandbox Code Playgroud)