JohnnyCash
JohnnyCash

Reputation: 1261

Django Update Form

I'm creating a form in one page, then in another page I'm trying to pull out the form (populated with the data saved in it already) and would like to make changes to it so that when I save it it overwrites the instance instead of creating another one.

def edit(request):

    a = request.session.get('a',  None)
    form = Name_Form(request.POST, instance=a)
    if form.is_valid():
            j = form.save( commit=False )
            j.save()

This seems to work but it doesn't prepopulate the form. Instead it start with a blank form that has already been "submitted" blank (you see all the errors telling you about the mandatory fields)

I also tried using

form = Name_Form(initial={'id':a.id})

to prepopulate the form. But if I do this instead of the form = Name_Form(request.POST, instance=a)line it won't overwrite the instance, it will create a new one.

I can't seem to combine both features.

Any help is appreciated

Upvotes: 5

Views: 6786

Answers (2)

alex
alex

Reputation: 1229

If you setup the form with request.POST, it will fill all the form fields with values that in finds inside the POST data. If you do this on a GET request (where request.POST is empty), you fill it with empty values.

Try:

def edit(request):

    a = request.session.get('a',  None)

    if a is None:
        raise Http404('a was not found')

    if request.method == 'POST':
        form = Name_Form(request.POST, instance=a)
        if form.is_valid():
            j = form.save( commit=False )
            j.save()
    else:
        form = Name_Form( instance = a )

Upvotes: 6

Gwilym Humphreys
Gwilym Humphreys

Reputation: 231

Don't add request.POST unless it's actually there:

def edit(request):

    a = request.session.get('a',  None)
    if request.method == 'POST':
        form = Name_Form(request.POST, instance=a)
        if form.is_valid():
                j = form.save( commit=False )
                j.save()
    else:
        form = Name_Form(instance=a)

Upvotes: 3

Related Questions