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

时间:2015-10-20 17:30:43

标签: django django-forms

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

Django表格,字段,视图:

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)

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

1 个答案:

答案 0 :(得分:7)

这是因为您的表单字段是静态填充的,而不是动态填充的(即不是每次实例化表单时)。您应该以{{1​​}}方法的形式指定表单queryset,如下所示:

__init__