Reputation: 36215
I've got the following django crispy form:
class ConsultForm(forms.ModelForm):
class Meta:
model = Consults # Your User model
fields = [ 'TEMPLATE','EMAIL', 'DATE']
labels = {
'EMAIL' : 'Your Email',
'DATE' : 'Todays date',
# 'captcha': "Enter captcha"
}
helper = FormHelper()
helper.form_method = 'POST'
helper.form_action = "/contact/"
helper.form_id = 'form' # SET THIS OR BOOTSTRAP JS AND VAL.JS WILL NOT WORK
helper.add_input(Submit('Submit', 'Submit', css_class='btn-primary'))
helper.layout = Layout(
Field('TEMPLATE', type="hidden"),
Field('DATE', type="hidden"))
I want to pass a value with the hidden field TEMPLATE. I've read https://django-crispy-forms.readthedocs.io/en/latest/api_helpers.html , but can't see how to do this. How can I get this done?
Upvotes: 3
Views: 4409
Reputation: 1211
You can set Form field initial values like this:
class ConsultForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initial['TEMPLATE'] = 'my_initial_value'
You can also change the value of the field at other places in your code like:
form = ConsultForm(instance=instance)
form.initial['TEMPLATE'] = 'new_value'
With formhelper (with crispy Universal Layout Objects like Field) you set attributes as you already did, like:
Field('TEMPLATE', id="template", value="something" template="my-template.html")
If that's what you were asking for.
Or if the above does not work easy then there is a layout object called Hidden in crispy. You can create hidden input fields with that:
Hidden('name', 'value')
You use it as Hidden('TEMPLATE', 'mysomethingvalue')
Like:
Button('name', 'value')
To make it fully clear:
helper.layout = Layout(
Hidden('TEMPLATE', 'myvalue'),
Hidden('DATE', 'anydate'))
Upvotes: 4