【问题标题】:Django: Value being set to None after Object.getDjango:在 Object.get 之后将值设置为 None
【发布时间】:2016-02-11 02:28:45
【问题描述】:

好的,这个问题源于我发布的另一个问题 (Old Post)。本质上,我有一个试图为新创建的对象new_protocolForeignKey 赋值的视图。问题是由于某种原因该值被设置为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})

【问题讨论】:

    标签: python django modelform


    【解决方案1】:

    如果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()
    # ...
    

    save() method

    在您的代码中,您将 study 分配给了表单(不是模型),因此模型的 study 得到了值 None

    【讨论】:

    • 我也知道。我不知道为什么我试图用另一种方式来做。谢谢你的第二双眼睛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2014-03-20
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多