[Django]-Add data to ModelForm object before saving

90👍

form = CreateASomething(request.POST)
if form.is_valid():
    obj = form.save(commit=False)
    obj.field1 = request.user
    obj.save()

7👍

Sometimes, the field might be required which means you can’t make it past form.is_valid(). In that case, you can pass a dict object containing all fields to the form.

   if request.method == 'POST':
       data = {
        'fields1': request.user,
        'fields2': additional_data,
       }
       form = CreateASomethingForm(data)

    if form.is_valid():
        form.commit(save)

2👍

There are two ways given by Django official
LINK : https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/

Method 1]

author = Author(title='Mr')
form = PartialAuthorForm(request.POST, instance=author)
form.save()

Method 2]

form = PartialAuthorForm(request.POST)
author = form.save(commit=False)
author.title = 'Mr'
author.save()

1👍

Here is a more suitable way to add data especially used during testing:

First convert an existing entry into a dictionary with the model_to_dict function

from django.forms.models import model_to_dict

...

valid_data = model_to_dict(entry)

Then add the new data into this dictionary

valid_data['finish_time'] = '18:44'

This works better than setting the value in the form

update_form.finish_time = '18:44'

Create the form with the valid data and the instance

update_form = UserEntryForm(valid_data, instance=entry)

Do any assertions you require:

self.assertTrue(update_form.is_valid())
entry = update_form.save()
self.assertEqual(
    entry.status,
    1
)
👤tread

1👍

To add an answer that works for Class Based View considering the amount of answers out there related to old method view – I felt the simplicity of this approach should be out there.

Let’s take the generic UpdateView – and should also work for the generic CreateView

# Edit my_app/views.py

from django.views.generic import UpdateView
from my_app.models import MyModel

class MyUpdateView(UpdateView):
    model = MyModel
    ...

    def form_valid(self, form):
        # Note the instance after form.
        # Simply assigning the field on the form won't work.
        # nothing will complain, but it will not save. 
        # Assign the data to form.instance
        form.instance.updated_by_user = self.request.user
        super().form_valid(form)
👤S.D.

Leave a comment