Reputation: 1932
I am having a difficult time understanding the Django docs on this one. I have also come across some other threads with the same question, but I cannot seem to get the suggested answers to work for me. I think it is because I am posting text, and it is not considered "clean" data?
I want to autofill two form fields, then when the user hits the submit button, it saves. But for some reason only the boolean value is working, not the text value. Any ideas?
You will also see the fields are hidden from my template. When I show these fields, the initial values are set correctly as I expected, but when I hit submit, only the boolean is saved to database correctly.
EDIT
It works fine when I don't hide the form fields using {{ form }}
in my template.
It does not work when I hide the fields using {{ form.field.as_hidden }}
Boolean field is accepted, but the text field is not.
I am trying to autofill this field with a text value, hide it, and submit this value when the submit button is pressed...
views.py
class BuildStopView(LoginRequiredMixin,UpdateView):
model = Build
form_class = StopBuild
template_name = 'build_stop.html'
login_url = 'login'
forms.py
class StopBuild(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(StopBuild, self).__init__(*args, **kwargs)
self.initial['buildEndType'] = 'manuallyStopped'
self.initial['buildActive'] = False
class Meta:
model = Build
fields = ['buildEndType','buildActive']
(template) stop_build.html
{% extends 'base.html' %}
{% block body %}
<style>
div.a {
text-align: center;
}
</style>
<div class = "a">
<h3>Are you sure you want to stop this build manually?</h3>
</div>
<form action="" method="post">{% csrf_token %}
{{ form.field.as_hidden }}
<button class="btn btn-danger ml-2" type="submit">Stop Build Manually</button>
</form>
{% endblock %}
Upvotes: 0
Views: 130
Reputation: 599946
form.field.as_hidden
does not output the fields as hidden, in fact it does not do anything at all because you don't have a field called field
in your form. You need to refer to the actual fields:
{{ form.buildEndType.as_hidden }}
{{ form.buildActive.as_hidden }}
However, if you want these to always be shown as hidden, you should probably do it in your form definition, by declaring them with HiddenInput
widgets.
Upvotes: 2