如何在Django modelform中隐藏字段? [英] How to hide a field in django modelform?

查看:635
本文介绍了如何在Django modelform中隐藏字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

class TestModel(models.Model):
    ref1 = models.ForeignKey(RefModel)
    text1 = models.TextField()

class TestModelForm(ModelForm):
    class Meta:
        model = TestModel
        fields = ('text1')

我只允许用户输入 text1 字段,但是当我重新定义时我的视图的 post方法,我还想设置 ref1 值,该怎么办?

I only allow the user to input text1 field, but when I redefine the post method of my view, I also want to set the ref1 value, how should I do that?

我希望我可以让TestModelForm具有ref1字段,但不要让用户修改它,然后我可以在post方法中修改request.POSt的值,并将其传递给TestModelForm,这有可能吗?

I wish I can let TestModelForm has the ref1 field but don't let user modify it, then I can modify the value of request.POSt in post method, and pass it to TestModelForm, is that possible?

推荐答案

您可以将 HiddenInput 用作 ref1 小部件:

class TestModelForm(ModelForm):
    class Meta:
        model = TestModel
        widgets = {
            'ref1': forms.HiddenInput(),
        }

另一个选择是使用保存表单commit 参数等于 False 。这样,您可以只在表单中包含可见字段,然后使用所需数据更新模型实例:

Another option is saving form with commit argument equal False. This way you can include only visible fields in form and then update model instance with needed data:

def some_view(request):
    # ...
    if request.method == 'POST':
        form = TestModelForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            ref = get_ref_according_to_url()
            instance.ref1 = ref
            instance.save()
            # ...

这篇关于如何在Django modelform中隐藏字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆