Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Primary Key after saving to a model in Django

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
like image 753
Michael Romrell Avatar asked Oct 17 '25 07:10

Michael Romrell


2 Answers

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

like image 180
Ramez Ashraf Avatar answered Oct 19 '25 22:10

Ramez Ashraf


The return value from ModelForm.save() is the new model. Take the PK from that instead.

like image 23
Ignacio Vazquez-Abrams Avatar answered Oct 19 '25 20:10

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!