我使用一个ClassBasedView,并要求Django移除自动生成的表单中的一些字段(释放: owner / owner_card_nb ):
class BristolCreateView(LoginRequiredMixin, CreateView):
model = Bristol
fields = [ "catalogue" ,
"recommanded_age" ,
"title" ,
"url" ,
"path_illustration" ,
"description" ] #letting out : owner / owner_card_nb
当表单发送到服务器时,我必须计算字段owner_car_nb。
owner_card_nb= Bristol.objects.filter(owner=self.request.user)
如何将这些数据推入已显示在html中的表单中,而没有所有者,也没有owner_car_nb值?
我尝试了几种方法:
类BristolCreateView(LoginRequiredMixin,CreateView):def get_initial(self):返回{'owner':self.request.user.id,'owner_card_nb':1}
但是网页仍然失败:
IntegrityError at /bristol/create
NOT NULL constraint failed: bristol_bristol.owner_id
使用
def Bristol.objects.filter(owner=self.request.user) form_valid(self,form):form.instance.created_by = self.request.user form.instance.owner_card_nb=返回超级(BristolCreateView,self).form_valid(form) )
但是网页仍然失败:
IntegrityError at /bristol/create
NOT NULL constraint failed: bristol_bristol.owner_id
我做错什么了?如何在CBV表单中为未显示的字段设置值?
发布于 2020-11-14 11:40:06
错误在form_valid
中:我把created_by
而不是owner
.
https://stackoverflow.com/questions/64837790
复制