Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data to ModelForm object before saving

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?

like image 857
Joker Avatar asked Jun 15 '13 19:06

Joker


People also ask

How does Django save clean data?

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.

What does form Save () do in Django?

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 ).


2 Answers

form = CreateASomething(request.POST) if form.is_valid():     obj = form.save(commit=False)     obj.field1 = request.user     obj.save() 
like image 170
Daniel Roseman Avatar answered Sep 22 '22 21:09

Daniel Roseman


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) 
like image 24
Emmanuel Osimosu Avatar answered Sep 20 '22 21:09

Emmanuel Osimosu