问题描述
例如:
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中隐藏字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!