Add data to ModelForm object before saving

痞子三分冷 提交于 2019-11-28 21:12:30
form = CreateASomething(request.POST)
if form.is_valid():
    obj = form.save(commit=False)
    obj.field1 = request.user
    obj.save()

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)

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
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!