提问人:Emmanuel Sofolawe 提问时间:11/15/2023 最后编辑:SamSparxEmmanuel Sofolawe 更新时间:11/15/2023 访问量:25
有没有办法在 Django 中使外键只读并且仍然提交表单而不会出现任何错误?
is there way to make a foreign key in django readonly and still submit the form without any error?
问:
我一直在尝试从我的 django 表单中使外键只读,我正在创建一个具有系统控制的 Web 应用程序,我不希望某些用户编辑提交的字段
class ApproveForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ApproveForm, self).__init__(*args, **kwargs)
# Filter the queryset for the 'category' field to only include active categories
self.fields['category'].queryset = Category.objects.filter(status='active')
# Filter the queryset for the 'category' field to only include active categories
self.fields['location'].queryset = Location.objects.filter(status='active')
self.fields['location'].widget.attrs['readonly'] = True
class Meta:
model = Request
fields = ('item','category','location','quantity','comments' )
widgets = {
'item':forms.Select(attrs={
'class':'form-control',
}),
'category':forms.Select(attrs={
'class':'form-control',
}),
'location':forms.Select(attrs={
'class':'form-control',
}),
'quantity':forms.NumberInput(attrs={
'class':'form-control', 'min':'0', 'readonly':'readonly'
}),
'comments': forms.Textarea(attrs={
'rows':4,'cols':5, 'class':'form-control'
})
}
它不起作用,我尝试使用隐藏,它隐藏了所有完整的值,使标签显示
答:
0赞
Vinita Sonakiya
11/15/2023
#1
如果您只想在只读模式下向用户显示现有对象的值,则可以从表单中删除该字段,并像这样通过表单实例直接访问。
从表单中删除字段
字段 = ('item','category','quantity','comments' )
通过实例访问 html 中的字段值。
{{form.instance.location}}
评论