我正在尝试一起使用 autocomplete_light 和 django-dynamic-formset: 两者都单独工作,但我不能让它们一起工作......让我们从代码开始......
模型.py:
class Tmp_User(models.Model):
userName = models.CharField(max_length=200, blank=True, null=True,)
firstName = models.CharField(max_length=200, blank=True, null=True,)
lastName = models.CharField(max_length=200, blank=True, null=True,)
...
class Project(models.Model):
title = models.CharField()
...
class Segment_in_Project(models.Model):
name = models.CharField()
the_project = models.ForeignKey('Project')
translator = models.ForeignKey('Tmp_User')
...
表格.py
autocomplete_light.autodiscover()
class AddProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddProjectForm, self).__init__(*args, **kwargs)
class Meta:
model = Project
fields = '__all__'
class AddSegmentForm(autocomplete_light.ModelForm):
def __init__(self, *args, **kwargs):
super(AddSegmentForm, self).__init__(*args, **kwargs)
class Meta:
model = Segment_in_Project
autocomplete_exclude = ['the_project']
fields = '__all__'
SegmentFormSet = formset_factory(AddSegmentForm)
autocomplete_light_registry.py
autocomplete_light.register(Tmp_User,
search_fields=['^firstName', 'lastName'])
和views.py
class ProjectCreateView(CreateView):
model = Project
template_name = 'home/formset-table.html'
form_class = AddProjectForm
success_url = '/admin'
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
formset = SegmentFormSet()
return self.render_to_response(
self.get_context_data(
form_Project=form,
formset_Segment=formset))
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
formset = SegmentFormSet(self.request.POST)
if (form.is_valid() and formset.is_valid()):
return self.form_valid(form, formset)
else:
return self.form_invalid(form, formset)
def form_valid(self, form, formset):
self.object = form.save()
self.object.save()
formset.instance = self.object
formset.save()
return super(ProjectCreateView, self).form_valid(form)
def form_invalid(self, form, formset):
return self.render_to_response(
self.get_context_data(
form_Project=form, formset_Segment=formset))
问题是formset实例没有“绑定”到Project模型并且验证失败:错误告诉the_project
未定义......我尝试先保存表单,获取新保存项目的ID并传递它当我建立表单集时,将表单集与 request.POST 一起发送到表单集......但它没有用......
另一方面,使用inlineformset_factory(Project,Segment_in_Project)
而不是formset_factory
破坏 autocomplete_light 功能......(我不知道如何使用autocomplete_light.ModelForm
Segment_in_Project 表单集)
关于如何做的任何想法或建议?谢谢