Add data to ModelForm object before saving

不想你离开。 提交于 2019-11-27 13:34:59

问题


Say I have a form that looks like this:

forms.py

class CreateASomethingForm(ModelForm):
    class Meta:
        model = Something
        fields = ['field2', 'field3', 'field4']

I want the form to have these three fields. However my Somethingclass also has field1. My question is - how do I add data to field1, if I am not using the ModelForm to collect the data. I tried doing something like this, but it isn't working and I am unsure on the proper way to solve this:

views.py

def create_something_view(request):
    if (request.method == 'POST'):
        # Create an object of the form based on POST data
        obj = CreateASomething(request.POST)
        # ** Add data into the blank field1 ** (Throwing an error)
        obj['field1'] = request.user
        # ... validate, save, then redirect 

The error I receive is:

TypeError: 'CreateAClassForm' object does not support item assignment

In Django, what is the proper way to assign data to a ModelForm object before saving?


回答1:


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



回答2:


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)



回答3:


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
)


来源:https://stackoverflow.com/questions/17126983/add-data-to-modelform-object-before-saving

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