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 Something
class 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?
save() it is already be matched and the clean data is saved. But you are using basic Form then you have to manually match each cleaned_data to its database place and then save the instance to the database not the form. NOTE: If the form pass from is_valid() stage then there is no any unvalidated data.
form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With