[英]how to hide column in django form and set foreign key value
I want to hide the column bh in the html page so I am hiding it by exclude in forms.py and trying to set foreign key column bh with request.user.username in the views but it is giving me this error: Cannot assign "]>": "Bed.bh" must be a "Hospital" instance. 我想在html页面中隐藏bh列,所以我通过在forms.py中排除而将其隐藏,并尝试在视图中使用request.user.username设置外键列bh,但这给了我这个错误:无法分配“ ]>“:“ Bed.bh”必须是“医院”实例。
Is there any way to resolve the issue. 有什么办法可以解决问题。 Please help!
请帮忙!
`#forms.py
class BedForm(forms.ModelForm):
class Meta:
model=Bed
fields = ('bed_id','bed_type','created_date','bh',)
exclude=('bh',)
if request.method == "POST":
form = BedForm(request.POST)
if form.is_valid():
bed = form.save(commit=False)
bed.created_date = timezone.now()
hh = Hospital.objects.filter(hospital_id=request.user.username)
bed.bh=hh
bed.save()
b = Bed.objects.filter(bh=request.user.username)
` `
This is because Hospital.objects.filter()
is returning a QuerySet
, not an instance of Hospital
. 这是因为
Hospital.objects.filter()
返回的是QuerySet
,而不是Hospital
的实例。
You want something like: 您想要类似的东西:
hh = Hospital.objects.filter(hospital_id=request.user.username)[0]
or 要么
hh = Hospital.objects.get(hospital_id=request.user.username)
In both cases, however you will have to either check that the object exists before retrieving it, or catch the exception, then figure out what to do next. 但是,在这两种情况下,您都必须在检索对象之前检查该对象是否存在,或者捕获异常,然后弄清楚下一步该怎么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.