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

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

问题描述

例如:

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

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

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

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 小部件:

You can use HiddenInput as ref1 widget:

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 模型中隐藏一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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