Django Generic CreateView - 如何填充字段但不显示它们

时间:2013-11-15 12:19:58

标签: django django-views

我想创建使用通用CreateView填充前或后填充的隐藏字段,但据我所知,我只有两个选项,不需要指定表单。

这将显示预先填充的字段:

class FootCreate(CreateView):
    model = Footprint
    fields = ["source","size","notes", "parent", "created_by"]
    success_url = reverse_lazy('home')

    def get_initial(self):
        parent = Object.objects.get(id=self.kwargs['obj_id'])
        return { 'parent': parent, 'created_by': self.request.user }

或者从字段列表中删除我不想显示的字段:

    fields = ["source","size","notes"]

但现在表格中没有填充字段,因此无法验证。

我知道我可以通过子类化表单或使用javascript来隐藏表单上的字段来处理这个问题,但我想知道是否有一个选项可以使用相应的:

    fields = ["source","size","notes", "parent", "created_by"]
    hidden_fields = ["parent", "created_by"]

在视图中?

ANSWER 不 - 但自定义模型表单只需几行。在视图中提供完整的字段列表。:

class FootprintForm(ModelForm):

    class Meta:
        model = Footprint
        widgets = {'created_by': forms.HiddenInput, "object": forms.HiddenInput}

1 个答案:

答案 0 :(得分:2)

我现在没有办法在CBV中做你想做的事情,我认为没有理由在视图中做到这一点。表单逻辑应该封装在表单中,您可以使用ModelForm和几行代码

轻松完成
相关问题