我正在使用表单生成器在w中创建一个应用程序。我添加了documentation中概述的自定义表单提交模型。我正在将自定义表单提交模型作为另一个模型(这里称为BridgeModel)中的外键,该模型还将存储其他外键。提交表单时,我也希望桥模型也自动更新(创建新行)。我最大的挑战是访问提交模型的当前主键,以便将其保存到桥模型。概念证明在下面
class FormBuilderField(AbstractFormField):
form_builder_page = ParentalKey('FormBuilderPage', on_delete=models.CASCADE, related_name='form_fields')
class FormBuilderPage(AbstractEmailForm):
content_panels = AbstractEmailForm.content_panels + [
FormSubmissionsPanel(),
InlinePanel('form_fields', label="Form fields"),
]
def get_submission_class(self):
return FormBuilderSubmission
def process_form_submission(self, form):
self.get_submission_class().objects.create(form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),page=self)
class FormBuilderSubmission(AbstractFormSubmission):
def get_data(self):
form_data = json.loads(self.form_data)
form_data.update({
'submit_time': self.submit_time,
})
#Tried this, doesn't work.
submission_id = FormBuilderSubmission.objects.get(id=self.id)
update_bridge = BridgeModel.objects.create(form_builder=submission_id)
process_update = update_bridge.save()
return form_data
class BridgeModel(models.Model):
form_builder = models.ForeignKey('FormBuilderSubmission', default=1, on_delete=models.CASCADE)
#other foreign keys here
答案 0 :(得分:0)
我已经开始工作了。使用全局变量并覆盖process_form_submission函数,有点hacky。
class FormBuilderPage(AbstractEmailForm):
content_panels = AbstractEmailForm.content_panels + [
FormSubmissionsPanel(),
InlinePanel('form_fields', label="Form fields"),
]
def get_submission_class(self):
return FormBuilderSubmission
def process_form_submission(self, form):
create_submission = self.get_submission_class().objects.create(form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),page=self)
#grabs the primary key from the submission model row just created
get_submission = self.get_submission_class().objects.filter(pk=create_submission.id).values('id')
global get_primary
get_primary = [id['id'] for id in get_submission]
现在从任何模型中,您都可以访问该主键以将其另存为外键
update_bridge = BridgeModel(form_builder_id=get_primary[0])
update_bridge.save()
我敢肯定有更好的方法可以做到这一点,但是到目前为止,它可以满足我的需求。