【问题标题】:Django Generic CreateView - how to populate fields but not display themDjango Generic CreateView - 如何填充字段但不显示它们
【发布时间】:2013-11-28 20:07:38
【问题描述】:

我想创建使用通用 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"]

在视图内?

回答 否 - 但自定义模型表单只需要几行。给出视图中字段的完整列表。:

class FootprintForm(ModelForm):

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

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    因为我现在无法在 CBV 中做你想做的事,我认为没有理由在 View 中做这件事。表单逻辑应该封装在Form中,用ModelForm和几行代码就可以轻松搞定

    【讨论】:

    • 很高兴知道。使用上面的表格添加了解决方案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多