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