Rileywiley
Rileywiley

Reputation: 139

Django: Value being set to None after Object.get

Ok so this question stems from another one that I posted (Old Post). Essentially I have a view that is trying to assign a value to a ForeignKey of a newly created object new_protocol. The problem is that for some reason that value is being set to none.

What I don't understand is that at the beginning of the view I call the get_object_or_404method so there is not reason for that to be set to none. Any thoughts would be appreciated.

The 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})

Upvotes: 0

Views: 44

Answers (1)

vsd
vsd

Reputation: 1473

If AddProtocol is the ModelForm (wouldn't it be better to name it AddProtocolForm?), then

# ...
# 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

In your code you assigned study to form (not model), so model's study got value None.

Upvotes: 2

Related Questions