gpt4 book ai didi

Django ModelChoiceField 未使用新数据更新

转载 作者:行者123 更新时间:2023-12-01 09:53:32 28 4
gpt4 key购买 nike

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

Django 表单、字段、 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)

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

最佳答案

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

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()

关于Django ModelChoiceField 未使用新数据更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33243098/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com