現在、djangoフォームに小さな(しかし厄介な)問題があります。
私が使用しているもの:
- ツイッターブートストラップ
- django floppyforms(html5ウィジェット専用)
- django crispy-forms(テンプレートタグとレンダリング用)
- 私のフォームはすべてModelFormsであり、可能であれば変更しないでください
Web全体を検索して多くのことを試しましたが、コードにhelp_text="いくつかのランダムなヘルプテキスト"を挿入できる場所がわかりません。だからここに私のコードがあります(正気の理由で省略されています):
#forms.py:
import floppyforms as forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from courses.models import *
class CourseForm(forms.ModelForm):
class Meta:
model = Course
widgets = {
'title': forms.TextInput, # This is a floppyforms widget
...
}
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_id = ''
self.helper.form_class = 'form-horizontal'
self.helper.form_action = '' # redirect in the view
self.helper.form_tag = True
self.helper.help_text_inline = True # means that I want <span> elements
self.helper.layout = Layout(
Fieldset('Create a new course', # fieldset label
Field('title', placeholder="Something...", css_class="span4"),
...
),
FormActions(
Submit(
'submit',
'Submit',
css_class="btn-primary"
)
),
)
super(CourseForm, self).__init__(*args, **kwargs)
'attrs' dictとしてウィジェットに、attrとしてフィールドに挿入しようとしました。
forms.TextInput(attrs={'help_text': 'Some help text'})
Field('title', help_text="Some help text", css_class="span4")
言うまでもなく、うまくいきませんでした。ヘルプテキストを、入力ウィジェットではなく、controls-div内の「span」または「p」に配置するためのフックが必要です。
私のテンプレートは非常に最小限であり、可能であればそのままにしておく必要があります。フォームフィールドを繰り返し処理したくありません。
#create_course.html
{% extends 'base.html'%}
{% load crispy_forms_tags %}
{% block content%}
{% crispy form %}
{% endblock content%}
これは次のhtmlとしてレンダリングされます。
<div id="div_id_title" class="clearfix control-group">
<label class="control-label requiredField" for="id_title">
Title
<span class="asteriskField">*</span>
</label>
<div class="controls">
<input id="id_title" class="span4 textinput textInput" type="text" placeholder="Something..." maxlength="60" required="" name="title">
</div>
</div>
ヘルプテキストを使用すると、次のようになります。
<div id="div_id_title" class="clearfix control-group">
<label class="control-label requiredField" for="id_title">
Title
<span class="asteriskField">*</span>
</label>
<div class="controls">
<input id="id_title" class="span4 textinput textInput" type="text" placeholder="Something..." maxlength="60" required="" name="title">
**<span class="help-inline">Supporting help text</span>**
</div>
</div>
どんな助けでも大歓迎です!私はviews.pyを介してフォームにコードを挿入しようとはしていませんが、それを実行しても意味がありません。正しいフックと構文を使用してforms.pyでそれを行うことが可能であるはずです。
このような単純な問題の長いテキストで申し訳ありません;)