Django:在 Object.get 之后将值设置为 None
Django: Value being set to None after Object.get
好的,这个问题源于我发布的另一个问题 (Old Post)。本质上,我有一个视图试图为新创建的对象 new_protocol
的 ForeignKey
赋值。问题是由于某种原因,该值被设置为 none
。
我不明白的是,在视图的开头我调用了 get_object_or_404
方法,因此没有理由将其设置为 none
。任何想法将不胜感激。
view.py
def add_protocol(request, study_slug):
study = get_object_or_404(Study, slug=study_slug)
if request.method == 'POST':
new_protocol = AddProtocol(request.POST, request.FILES)
if new_protocol.is_valid():
new_protocol.save(commit=False)
new_protocol.study = study
new_protocol.save()
return HttpResponseRedirect(reverse('studies:studydetails', args=(study.slug,)))
else:
return HttpResponse('Something is messed up')
else:
new_protocol = AddProtocol()
return render(request, 'studies/addprotocol.html', {'new_protocol': new_protocol, 'study': study})
如果AddProtocol
是ModelForm(命名为AddProtocolForm
不是更好吗?),那么
# ...
# I renamed new_protocol to new_protocol_form here
new_protocol_form = AddProtocol(request.POST, request.FILES)
if new_protocol_form.is_valid():
# save() method of form returns instance
new_protocol = new_protocol_form.save(commit=False)
# assigning related field
new_protocol.study = study
new_protocol.save()
# ...
在您的代码中,您将 study
分配给了表单(而非模型),因此模型的 study
获得了值 None
。
好的,这个问题源于我发布的另一个问题 (Old Post)。本质上,我有一个视图试图为新创建的对象 new_protocol
的 ForeignKey
赋值。问题是由于某种原因,该值被设置为 none
。
我不明白的是,在视图的开头我调用了 get_object_or_404
方法,因此没有理由将其设置为 none
。任何想法将不胜感激。
view.py
def add_protocol(request, study_slug):
study = get_object_or_404(Study, slug=study_slug)
if request.method == 'POST':
new_protocol = AddProtocol(request.POST, request.FILES)
if new_protocol.is_valid():
new_protocol.save(commit=False)
new_protocol.study = study
new_protocol.save()
return HttpResponseRedirect(reverse('studies:studydetails', args=(study.slug,)))
else:
return HttpResponse('Something is messed up')
else:
new_protocol = AddProtocol()
return render(request, 'studies/addprotocol.html', {'new_protocol': new_protocol, 'study': study})
如果AddProtocol
是ModelForm(命名为AddProtocolForm
不是更好吗?),那么
# ...
# I renamed new_protocol to new_protocol_form here
new_protocol_form = AddProtocol(request.POST, request.FILES)
if new_protocol_form.is_valid():
# save() method of form returns instance
new_protocol = new_protocol_form.save(commit=False)
# assigning related field
new_protocol.study = study
new_protocol.save()
# ...
在您的代码中,您将 study
分配给了表单(而非模型),因此模型的 study
获得了值 None
。