I’m trying to understand the difference between Django’s ModelForm save method and saving the Model instance directly.
Personally, I find saving directly more intuitive and more clearly shows when the data is saved. Plus, if I need to modify the instance before saving, then I have to use the Model save method as the Django documentation explains here.
So, once the form is validated, what is the difference? Would there be a difference if the form used multiple models or some other more complex use case?
I’m using Django version 1.4 if that matters. And below is some code showing how I tend to save validated form data.
Thanks in advance!
# models.py
class Project(models.Model):
project_name = models.CharField(unique=True, null=False, blank=False)
# views.py
def add_project(request):
if request.method == 'POST':
project = Project()
form = ProjectForm(request.POST, instance=project)
if form.is_valid():
project.save() ### <-- project.save() vs form.save() ###
return HttpResponseRedirect(reverse('view_project', args=(project.id,)))
else:
form = ProjectForm()
return render_to_response(
'add_project.html',
{
'form': form,
},
context_instance=RequestContext(request)
)
# forms.py
class ProjectForm(ModelForm):
class Meta:
model = Project
In the commented line you have,
project.save()simply won’t do anything. The instance has not been updated with the form data, it is simply the empty instance you created two lines before. The only way to update an existing instance is by saving its form.