如何从Django中的模型创建表单域?

时间:2015-12-09 00:07:30

标签: django forms

以简单的形式,我有以下几个类:

class Upload(models.Model):
   name = models.CharField()
   groupy = models.ForeignKey('Group',null=True)
class Group(models.Model):
  slogan = models.CharField()

我现在想要创建一个同时创建两个类对象的表单。到目前为止,我的方法是:

class GroupCreate(CreateView):
  def get_form(self, form_class):
    form = super(GroupCreate, self).get_form(form_class)
    form.fields['name'] = CharField()
    return form
  def form_valid(self, form):
    response      = super(GroupCreate, self).form_valid(form)
    groupy        = form.save()
    upload        = Upload()
    upload.groupy = groupy
    upload.name   = form.instance.name
    upload.save()
    return response
  ...

这很好用。不过我的问题是,我有很多字段,我需要分别设置每个字段的选项。因此:

如何将上传模型的字段转换为表单字段,然后将它们传输到表单中?

1 个答案:

答案 0 :(得分:0)

好。我找到了解决方案。如果我导入from django.forms.models import modelform_factory,我可以使用它来创建字段:

def get_form(self, form_class):
  form = super(GroupCreate, self).get_form(form_class)
  upload_form = modelform_factory(Upload,fields=('name',))

  for field in upload_form.base_fields:
    form.fields[field] = upload_form.base_fields[field]
  return form

还必须调整form_valid功能:

  def form_valid(self, form):
    ...
    upload.name   = form.cleaned_data['name']
    ...