Issue
I want the user to fill some form, then add the user's id and user's branch(from another table, by releation) to add to the form data before saving it. the form has other fields like {type, serialno, model, date}, after it is submitted i want to add userid and branchid to that form value and submit it to database
This is my view.py enter image description here
I tried to overide the form data as you can see in the picture. But, it keeps showing me an error message of "TypeError"
Solution
You should work with form.save(commit=False)
, this method is used when you want to create or update a model instance using the data from a form but do not want to save it to the database immediately. This is particularly useful when you need to perform additional processing or validations before saving the data.
Example:
if form.is_valid():
user = request.user
instance = form.save(commit=False)
instance.sent_by = user
instance.branch = Branch.objects.filter(code=user.first_name)
instance.save()
Answered By - Oth Mane
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.