Hi all,
I’m using django-crispy-forms with the crispy-bootstrap5 package. (As far as I know, I need the latter one for using the newest bootstrap version 5. If the impression I gained from some google results is wrong - or there is any other best practice -, please let me know.)
I’m not able to change the type-attribute from text to e.g. date or range in the following scenario:
views.py
class PresentationForm(ModelForm):
class Meta:
model = PreviewEntry
fields = ["name", "first_day", "second_day", "starttime", "endtime"]
@property
def helper(self):
helper = FormHelper()
helper.layout = Layout(
Field('name', wrapper_class='mt-3 row'),
# =====> type='date' is later rendered as type='text'
Field('first_day', wrapper_class='mt-3 row', type='date'),
Field('second_day', wrapper_class='mt-3 row', type='date'),
# starttime and endtime are left out
class CreateEntry(generic.CreateView):
model = PreviewEntry
template_name = "mytemplate.html"
form_class = PresentationForm
success_url = 'success.html'
settings.py:
INSTALLED_APPS = [
...
'crispy_forms',
'crispy_bootstrap5',
]
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
mytemplate.html
{% extends base.html %}
{% block content %}
{% crispy form %}
{% endblock %}
This works perfectly except of the fact that the type-field of my “first_day” and “second_day” element are rendered as type=‘text’ instead of type=‘date’ (where the browser would provide a datepicker).
<input type="text" name="first_day" class="dateinput form-control" required="" id="id_first_day">
Later in the form I would like to use type=“range”. This is also not possible.
Of course I could do something like this:
helper.layout = Layout(
...
HTML('''
<div id="div_id_starttime" class="mb-3 row">
<label for="id_starttime" class="form-label col-4 requiredField">Starttime<span class="asteriskField"></span> </label>
<div class="col-8">
<input class="col-10" name="starttime" id="id_starttime" type="range" value="8" min="0" max="24" oninput="this.nextElementSibling.value = this.value + ' Uhr' ">
<output>8 Uhr</output>
</div>
</div>
'''),
)
...
This approach works really fine. But I doubt that there isn’t a better way to do.
Any ideas on what is best practice to change the type in a crispy-form? Already searched the documentation [2] but didn’t find anything about that.
[1] crispy-bootstrap5 · PyPI
[2] Search — django-crispy-forms 1.11.1 documentation