Django来自“通用相关”模型

时间:2012-08-26 12:48:45

标签: python django django-forms

我有一些模型,与GenericForeignKey

相关联
Class Main(models.Model)
    filed_1      = models.CharField(max_length=20)
    object_id    = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    object       = generic.GenericForeignKey('content_type', 'object_id')

Class Additional_1(models.Model):
    f_1 = models.CharField(max_length=20)
    f_2 = models.CharField(max_length=20)

Class Additional_2(models.Model):
    d_1 = models.CharField(max_length=20)
    d_2 = models.CharField(max_length=20)

此模型的表格:

Class MainForm(forms.ModelForm):
      class Meta:
           model  = Main
           fields = ('filed_1', 'object_id', 'content_type')

           widgets = {
               'object_id': forms.HiddenInput,
               'content_type': forms.HiddenInput
           }

Class Additional_1Form(forms.ModelForm):
    class Meta:
        model  = Additional_1
        fields = ('f1', 'f2')

Class Additional_2Form(forms.ModelForm):
    class Meta:
        model  = Additional_2
        fields = ('d1', 'd2')

如何在一个html表单中使用一个提交按钮(MainForm + Additional_iFormMainForm +制作由Additional_1Form + Main字段组成的表单Additional_2Form)并提供正确的创建和编辑。有办法使用标准的Django组件,比如ForeignKey的内联formset?

P.S。我认为这个问题的答案应该包含在文档的这一部分中,但是要回答的信息太少了。 https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations-in-forms-and-admin

EDITION#1

# This is always false, because of 'object_id' in main_form
if main_form.is_valid() and additional_1_form.is_valid():
    additional = additional_1_form.save()
    main_form.object_id = additional .id # I need something like this to set object_id 
    main_form.save()

1 个答案:

答案 0 :(得分:1)

创建一个表单标记:

<form action="..." method="POST">
{{ main_form }}    
{{ additional_form_1 }}    
{{ additional_form_2 }}
<input type="submit" value="Submit!">
</form>

其中{{ mainform }}{{ additional_form_1 }}{{ additional_form_2 }}是Django为每个表单生成的HTML。您可以使用JavaScript添加编辑反馈或其他功能(例如,当用户为特定字段选择特定值时填写值。)

在后端,您可以检查每个表单是否有效:

if (main_form.is_valid() and
   additional_form_1.is_valid() and
   additional_form_2.is_valid()):
   pass

如果没有,您可以再次在表单页面中显示错误。