0
I am learning how to use Jango forms and I have been presented with two ways to save information from a form in a database. I tested both and both work with validations, but did not understand what the difference between one and the other.
The former uses functions inherited from the models class. Model, using the function "Objects.create(**form.cleaned_data)" and passing the form fields as parameter.
In the example below, I introduce the Productform class that inherits from 'Forms.Modelform' and use the function 'cleaned_data' to pass as parameter.
def product_create_view(request):
form = ProductForm()
if request.method == 'POST':
form = ProductForm(request.POST or None)
if form.is_valid():
Product.objects.create(**form.cleaned_data)
form = ProductForm()
data = {}
data['form'] = form
return render(request, 'products/product_create.html', data)
The second way instead of using the function 'Objects.create(**Dict)' uses the form.save() directly.
def product_create_view(request):
form = ProductForm()
if request.method == 'POST':
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
form = ProductForm()
data = {}
data['form'] = form
return render(request, 'products/product_create.html', data)
Briefly, I would like to know there are differences between using form.save() and using Product.objects.create(**Dict).
Your answer is not wrong but it is not enough, there are many situations in which
form.save()
not suitable, examples: Imagine that according to the user’s choice, before persisting the data you have to perform a calculation or consult an api to update a field not present in the form.– Sidon