I've seen the documentation here and several similar stack Overflow posts, but after saving my form I'm still unable to return the ID/PK of that new model. It keeps telling me 'ProposalForm' object has no attribute 'id'
How can I return the ID right after saving?
Here's the View:
def proposal_create_view2(request):
if request.method == 'POST':
form = ProposalForm(data=request.POST)
if form.is_valid():
form.save()
response = {}
response['proposalID'] = form.id
return response
my_saved_model = my_model_form.save()
print my_saved_model.pk
Edit:
def proposal_create_view2(request):
if request.method == 'POST':
form = ProposalForm(data=request.POST)
if form.is_valid():
mysaved_model = form.save()
response = {}
response['proposalID'] = mysaved_model.id #or .pk
return render(request , 'my_template_file.html' , response)
#return response statement is NOT valid as you need to return an HttpResponse not a dict
Review Django Docs on HttpResponses
The return value from ModelForm.save()
is the new model. Take the PK from that instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With