Reputation: 45
I have a Django form all working fine, however I need to update one filed after the user has posted the form, I was thinking this should be done in the view? My code is below for the view definition in question.
def edit_change(request, change_id):
change = get_object_or_404(Change, id=int(change_id))
form = ChangeForm(request.POST or None, instance=change)
change_id = Change.objects.get(id=int(change_id))
context = dict(change=change, id=change_id,form=form)
if form.is_valid():
if form['change_id'] = ""
form.['change_id'] = "TEST_NUM"
cmodel = form.save()
cmodel.save()
return redirect(changes)
return render_to_response('editchange.html',context, context_instance=RequestContext(request))
Basically I want to see if the change_id has a value, if not add a value (date + (number of changes for that day + 1)), the continue to save the data.
Upvotes: 3
Views: 2319
Reputation: 22808
def edit_change(request, change_id):
............
if form.is_valid():
change_id = form.cleaned_data['change_id']
cmodel = form.save()
if not change_id:
cmodel.change_id = "TEST_NUM"
cmodel.save()
return redirect(changes)
return render_to_response('editchange.html',context, context_instance=RequestContext(request)
Upvotes: 3
Reputation: 2509
When you form.is_valid()
, you create a form.data
dict which form.save()
then passes into the model
associated with the form
. If you add the in-between step of model_object = form.save(commit=False)
, you create a model instance, populated with all the form.data
values. You can change and save this model instance as you need. E.g. model_object.change_id = "TEST_NUM"
. When you are done, you can finish with model_object.save()
, never having need to use form.save()
More detail here: https://stackoverflow.com/questions/14982699/django-using-savecommit-false-to-add-user-id-to-a-form-dont-modify-save-or
Upvotes: 1
Reputation: 10162
I would redefine the clean method of the form, so that it makes the modification in the cleaned_data dict.
Upvotes: 0