Django Update Form

I create a form on one page, and then on another page I try to pull out a form (filled with the data already stored in it), and would like to make changes to it so that when I save it, it overwrites the instance instead of creating another.

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 does not out-form. Instead, it starts with an empty form that has already been “submitted” empty (you see all errors informing you of the required fields)

I also tried using

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

to pre-fill the form. But if I do this instead of a string form = Name_Form(request.POST, instance=a), it will not overwrite the instance, it will create a new one.

I can not combine both functions.

Any help is appreciated

+5
source share
2

.POST, , POST. GET ( request.POST ), .

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 )
+6

request.POST, :

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)
+3

All Articles