program story

Django Forms 및 Bootstrap-CSS 클래스 및

inputbox 2020. 11. 13. 08:10
반응형

Django Forms 및 Bootstrap-CSS 클래스 및


Django와 함께 Twitter Bootstrap사용하여 양식을 렌더링하고 있습니다.

BootstrapCSS예상 되는 클래스가 포함되어 있으면 양식을 매우 멋지게 형식화 할 수 있습니다.

그러나 내 문제는 Django에서 생성 된 양식 {{ form.as_p }}이 이러한 클래스가 없기 때문에 Bootstrap에서 잘 렌더링되지 않는다는 것입니다.

예를 들어 Django의 출력은 다음과 같습니다.

    <form class="horizontal-form" action="/contact/" method="post">
        <div style='display:none'>
            <input type='hidden' name='csrfmiddlewaretoken' 
                   value='26c39ab41e38cf6061367750ea8c2ea8'/>
        </div>
        <p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="FOOBAR" maxlength="20" /></p>
        <p><label for="id_directory">Directory:</label> <input id="id_directory" type="text" name="directory" value="FOOBAR" maxlength="60" /></p>
       <p><label for="id_comment">Comment:</label> <textarea id="id_comment" rows="10" cols="40" name="comment">Lorem ipsum dolor sic amet.</textarea></p>
       <p>
           <label for="id_server">Server:</label>
           <select name="server" id="id_server">
               <option value="">---------</option>
               <option value="1" 
                   selected="selected">sydeqexcd01.au.db.com</option>
               <option value="2">server1</option>
               <option value="3">server2</option>
               <option value="4">server3</option>
           </select>
       </p>
       <input type="submit" value="Submit" />
    </form>

내가 말할 수있는 건, 부트 스트랩은 양식이있다 것을 요구 <fieldset class="control-group">, 각각 <label>class="control-label", 각이 <input>A의 싸여있다 <div>:

<fieldset class="control-group">
    <label class="control-label" for="input01">Text input</label>
    <div class="controls">
        <input type="text" class="xlarge" name="input01">
        <p class="help-text">Help text here. Be sure to fill this out like so, or else!</p>
    </div>
</fieldset>

그러나 Django의 모든 양식 필드에 사용자 정의 CSS 레이블을 추가하는 것은 다소 고통 스럽습니다.

Django label_tag () 출력에 클래스 추가

{{ form.as_p }}수동으로 항목을 지정하지 않고도을 사용 하거나 필드를 반복 하는 더 현명한 방법이 있습니까?

건배, 빅터


저는 django-uni-form의 후속 제품인 "django-crispy-forms" 를 사용하고 싶습니다 . 훌륭한 작은 API이며 Bootstrap을 크게 지원합니다.

이전 코드와 빠른 양식을 빠르게 이식하기 위해 템플릿 필터를 사용하고 렌더링을 더 많이 제어해야 할 때 템플릿 태그를 사용하는 경향이 있습니다.


이것이 내가 생각 해낸 것입니다.

<form class="form-horizontal" method="post">{% csrf_token %}
    <fieldset>
        <legend>{{ title }}</legend>
        {% for field in form %}
            {% if field.errors %}
                <div class="control-group error">
                    <label class="control-label">{{ field.label }}</label> 
                    <div class="controls">{{ field }}
                        <span class="help-inline">
                            {% for error in  field.errors %}{{ error }}{% endfor %}
                        </span>
                    </div>
                </div>
            {% else %}
                <div class="control-group">
                    <label class="control-label">{{ field.label }}</label> 
                    <div class="controls">{{ field }}
                        {% if field.help_text %}
                            <p class="help-inline"><small>{{ field.help_text }}</small></p>
                        {% endif %}
                    </div>
                </div>
            {% endif %}
        {% endfor %}
    </fieldset>
    <div class="form-actions">
        <button type="submit" class="btn btn-primary" >Submit</button>
    </div>
</form>

django-crispy-forms사용할 수 없습니다 (템플릿 취급 형태의 개별적으로 각 필드는 예를 들어 경우), jcmrgo의 대답은 갈 수있는 유일한 방법입니다. 그의 답변을 바탕으로 Bootstrap 3 (Boostrap 2에 대한 그의 버전은 남겨 둠) 및 템플릿 내부의 필드 클래스 조정에 대한 솔루션이 있습니다. Django의 표준 라이브러리 (다른 솔루션에서 추가 양식 또는 템플릿 태그로 이어짐)를 사용하여 템플릿 내에서 필드 클래스에 도달 할 수는 없지만 템플릿 외부에서 코딩 할 필요없이 올바른 클래스를 필드 태그로 설정하는 솔루션은 다음과 같습니다.

{% load i18n widget_tweaks %}

<form class="form-horizontal" role="form" action="." method="post">
    {% csrf_token %}
    {% for field in form %}
        {% if field.errors %}
            <div class="form-group has-error">
                <label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
                <div class="col-sm-10">
                    {{ field|attr:"class:form-control" }}
                    <span class="help-block">
                        {% for error in  field.errors %}{{ error }}{% endfor %}
                    </span>
                </div>
            </div>
        {% else %}
            <div class="form-group">
                <label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
                <div class="col-sm-10">
                    {{ field|attr:"class:form-control" }}
                    {% if field.help_text %}
                        <p class="help-block"><small>{{ field.help_text }}</small></p>
                    {% endif %}
                </div>
            </div>
        {% endif %}
    {% endfor %}
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary">{% trans "Submit" %}</button>
        </div>
    </div>
</form>

이 파일을 django-widget-tweaks설치하고에 widget_tweaks추가해야 INSTALLED_APPS합니다.


다음과 같이 할 수 있습니다.

{% for field in form %}
<fieldset class="control-group">
    <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label>
    <div class="controls">
        {{ field }}
        <p class="help-text">{{ field.help_text }} </p>
    </div>
</fieldset>
{% endfor %}

Django 생성 양식에 CSS 속성을 추가하려면 forms.py에서 다음 코드를 사용하면됩니다.

Recepient = forms.ChoiceField(label=u'Recepient', widget=forms.Select(attrs={'id':'combobox'}))

It will produce the following HTML code:

<label for="id_Recepient">Recepient</label>
<select id="combobox" name="Recepient">

I definitely recommend https://github.com/dyve/django-bootstrap-toolkit


For Example, you could created a class which defines the attributes the way you want and just call it accordingly.

class ContactForm(ModelForm):
    class Meta:
      model = Contact
      created = MyDatePicker()

class Uniform(forms):
  def __init__(self, *args, **kwargs):
      attrs = kwargs.pop("attrs",{})
      attrs["class"] = "span3"
      kwargs["attrs"] = attrs
      super(Uniform, self).__init__(*args, **kwargs)

class MyDatePicker(Uniform,forms.DateInput)
  def __init__(self, *args, **kwargs):
      attrs = kwargs.pop("attrs",{})
      attrs["class"] = "datepick" 
      attrs["id"] =kwargs.get('datetag', '')
      kwargs["attrs"] = attrs
      super(MyDatePicker, self).__init__(*args, **kwargs)

Bootstrap styles forms with <div>s rather than <p>s. So, if you want it to look nice, you need to go bootstrap way 100% IMHO. And here is my preferred way of doing it:

Use django-bootstrap3 app. Example:

{% load bootstrap3 %}

<form class="signup form-horizontal" id="signup_form" method="post" action="{% url 'account_signup' %}">
    {% csrf_token %}
    {% bootstrap_form form layout="horizontal" %}
    {% buttons submit='Sign Up &raquo;' reset='Reset Form' layout='horizontal' %}{% endbuttons %}
</form>

Notice the horizontal in 1) form class attribute 2) bootstrap_form layout and 3) buttons layout.


Here is my version using django_tweaks with a better looking result. I find render_field lighter to use than adding filters. I have also added bootstrap formatted alert messages and turned off navigator validation (with novalidate). I am relatively new to Django so don't hesitate to comment if you find any non-sense

<form class="large" method="post" action="/suscript/" novalidate>
    {% csrf_token %}
    <fieldset>
        <legend>{{ title }}</legend>
        {% for field in form %}
            <div class="control-group {%if field.errors %}error{%endif%}">
                <div class="input-group controls">
                    <label class="input-group-addon control-label" id="{{field.label|safe}}">{{ field.label }}</label>
                    {% render_field field type="text" class="form-control" placeholder="" aria-describedby="field.label|safe" %}
                </div>
                    {% for error in field.errors %}
                         <div class="alert alert-danger">
                            <strong>{{ error|escape }}</strong>
                         </div>
                    {% endfor %}

                    {% if field.help_text %}
                        <p class="help-inline">{{ field.help_text|safe }}</p>
                    {% endif %}
            </div>

        {% endfor %}
    </fieldset>
    <div class="form-actions">
        <button type="submit" class="btn btn-primary" >Submit</button>
    </div>
</form>

The fastest and easiest way would be to define your own base class that extends the Django Form class, and redefine its as_p method to output in the format Bootstrap requires. Then change your forms to inherit from your new Form class instead of Django's.


besides what other friends said, I would recommend using 'django-widget-tweaks'.

the answer would be sth like this:

{% for field in form %}
      <label for="{{ field.label }}">{{ field.label }}</label>
      {{ field|add_class:"form-control" }}
      <span class="error-block">{{ field.errors }}</span>
{% endfor %}

참고URL : https://stackoverflow.com/questions/8474409/django-forms-and-bootstrap-css-classes-and-divs

반응형