How to insert hidden input value into database in django
I have created a form using a model. And I created the hidden input manually in django form with below syntax
<input type="hidden" value="123" name="fourth" />
My django html page looks like this
first.html
<form action="" method="POST">
{{form.first}}
{{form.second}}
{{form.third}}
<input type="hidden" value="123" name="fourth"/>
</form>
The problem is when the form submission I can get the value of the first, second, third and can insert the value using form.save () . But I cannot insert the value of the fourth. Because I created the hidden input value manually . How can I insert the fourth value into the database. Plz help me to do this.
My table column: first second third fourth
source to share
There are two different form variables here:
- Django form fields (first, second, third)
- original form fields (fourth)
To get the Django form fields, I assume you use something like:
if form.is_valid():
field_name = form.cleaned_data['field_name'].
To get the raw fourth field, you need to access the request. POST like:
yourVar = request.POST['fourth']
# I'm used to the 'get' method like
yourVar = request.POST.get('fourth', '')
The last command is request.POST.get('fourth', '')
used to avoid an error if inrequest.POST
EDIT: add an unformatted field to the database
I am assuming you are using some kind of model form and you want to instantiate when you do form.save()
, but you need to add a fourth hidden field to the instance to do this, you can do it like:
instance = form.save()
instance.fourth_field = request.POST.get('fourth', '')
instance.save()
I think it might return an error, if in the model it is required fourth_field
to avoid this you could do something like:
if form.is_valid(): # This statement cleans all fields
field1 = form.cleaned_data['first']
field2 = form.cleaned_data['second']
field3 = form.cleaned_data['third']
field4 = request.POST.get('fourth', '')
instance = YourModel(first=first, second=second, third=third, fourth=fourth)
instance.save()
source to share