简体   繁体   English

如何在 django 模型中隐藏一个字段?

[英]How to hide a field in django modelform?

For example:例如:

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

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

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

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

You can use HiddenInput as ref1 widget: 您可以将HiddenInput用作ref1小部件:

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

Another option is saving form with commit argument equal False . 另一种选择是保存commit参数等于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()
            # ...

NOTE: I am using (Django 3.2)注意:我正在使用(Django 3.2)

I tried to add a widget and it did not work for me, but I solved it in a simpler way without using widgets.我尝试添加一个小部件,但它对我不起作用,但我在不使用小部件的情况下以更简单的方式解决了它。

class TestModelForm(ModelForm):
    ref1 = forms.CharField (widget = forms.Textarea(
        attrs = {
            'hidden': '',
        }
    ))

I hope this helps you or others ;)我希望这可以帮助您或其他人;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM