动态django表单的问题

时间:2013-01-14 00:46:33

标签: python django django-models django-forms

我正在编写一个程序来管理电子元件数据库。用户需要能够将组件组织到组中。每组都有一组不同的场(电阻器与电容器等不同),尽管有些是常见的。我还希望用户能够创建新组并指定该组的特定字段。而不是处理真正动态的领域,这是我提出的:

以下是相关模型:

class ComponentGroup(models.Model):
   name = models.CharField(max_length=200)
   code = models.CharField(max_length=3, unique=True)

class GroupField(models.Model):
   name = models.CharField(max_length=200)
   group = models.ForeignKey(ComponentGroup, related_name='fields')

class Part(models.Model):
   group = models.ForeignKey(ComponentGroup)
   fields = models.ManyToManyField(GroupField, through='Parameter')
   # ... some "static" fields

class Parameter(models.Model):
   field = models.ForeignKey(GroupField)
   part = models.ForeignKey(Part)

   value = models.CharField(max_length=200)


class ParameterForm(forms.ModelForm):
   class Meta:
      model = Parameter
      fields = ('value',)

class PartForm(forms.ModelForm):
   class Meta:
      model = Part
      exclude = ('fields', 'group')

因此,任何给定的组都有一组GroupField个,每个都有一个名字。 Parameter指定与Part所属的GroupField中的ComponentGroup对应的特定Part的值。

我正在尝试为用户创建一种从给定组创建新Part的方法。我认为“django方式”接近这是使用formset。是对的吗?处理这个问题的“正确”方法是什么?

修改

这是我编写的视图,用于生成“静态”字段的表单和ComponentGroup指定的字段的表单集,但它有几个问题 - 请参阅注释。我不确定如何解决它们。有什么建议吗?

def part_add(request, code):
   thisgroup = get_object_or_404(ComponentGroup, code=code)
   thispart = Part()
   thispart.group = thisgroup
   thispart.save() ### don't want to do this here, but sort of need to to generate ID
                   # creates the problem that if form is not submitted, now have a 
                   # completely blank Part 

   for field in thisgroup.fields.all():
      p = Parameter()
      p.field = field
      p.part = thispart
      p.save() # would like to save the parameters at the same time as the Part is saved,
               # when the form is submitted but if they're not saved, they will not show 
               # up on the formset


   ParametersInlineFormset = inlineformset_factory(CEIPart, Parameter, form=ParameterForm, extra=0, can_delete=False)

   if request.POST:
      form = PartForm(request.POST, group=thisgroup, instance=thispart)
      formset = ParametersInlineFormset(request.POST, request.FILES, instance=thispart)
      if form.is_valid():
         form.save()
      if formset.is_valid():
         formset.save()

      return HttpResponseRedirect(reverse('ceiparts.views.part_detail', args = (thispart.CEIPN,)))
   else:
      form = PartForm(group=thisgroup, instance=thispart)
      formset = ParametersInlineFormset(instance=thispart)

   return render(request, 'ceiparts/ceiparts_add.html',
 { 'form' : form,
    'formset' : formset,
    'ceipart' : thispart,
    'componentgroup' : thisgroup }
 )

0 个答案:

没有答案