Home > OS >  How to send new form fields with data from Django views.py?
How to send new form fields with data from Django views.py?

Time:10-21

I am adding a new field named "user" to the "order" model. I did make migrations. (Bonus question is: why in the sql3db column "user_id" was made, instead of "user"? But ok, I change form.fields['user'] to form.fields['user_id'], as the machine wants...)

I remove unneeded fields from the form in forms.py, and I try to add this fields in views.py (because I don't know how to send "user" to the forms.py, and I think it more secure like this).

And as I can understand - my new fields is absent for "order", when I use form.save(). This field can't be null by design.

screenshot

CodePudding user response:

Your form has no user field, hence that will not work. What you can do is alter the object wrapped in the form with:

if form.is_valid():
    form.instance.user = request.user
    form.instance.email = request.user.email
    order = form.save()
  • Related