Question

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
Was it helpful?

Solution

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.

OTHER TIPS

ModelForm.save() returns an object saved from the data that was put into the form, Model.save() returns an object from the data that the object was initialized with or values that were set after it was created. So when it comes to getting the data from what the user inputted on the form to a persisted object, it makes more sense to call ModelForm.save() rather than going through the work of validating the data yourself, initializing the object and then saving it because all that work is handled by the ModelForm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top