) user = request.user.username host1.timezone = get_timezone(用户=用户) host1.save() 返回host1
类Meta: 模型 </跨度> = 主办 </跨度> 小部件= { ‘user ’:forms.HiddenInput(), ‘timezone’:forms.HiddenInput() }
timezone是一个输入隐藏字段 主办 </跨度> 模型 </跨度> 在model.py中定义。
get_timezone方法:(定义如下)
def
timezone = timezone.filter(user=user) return timezone.timezone
timezone.filter(...) 将返回一个查询集,你不能打电话 .timezone 在查询集上。您必须使用以获取相关对象 get :
timezone.filter(...)
.timezone
get
timezone = timezone.get(user=user)
或通过列表切片:
timezone = timezone.filter(user=user)[0]
更新:好的,我只是注意到了。
问题是,您无法将请求对象传递给表单 save 方法。处理问题的最佳方法是在视图层中执行此操作。
save
在你看来:
my_form = HostCreateForm(request.POST): if my_form.is_valid(): #do the validation my_inst = my_form.save(commit=False) #pass the form values to a new model instance without saving. my_inst.timezone = request.user.username #set the user or do whhatever you want eith the form data. my_inst.save() #that will call your save methhod that you override.
并删除设置用户的部分 save 方法。