在“同一行”上显示Django表单字段

时间:2017-03-01 11:19:28

标签: python html css django django-templates

我想在同一行显示两个表单字段,而不是在另一行之后显示每个表单字段。

目前,我得到了:

Choice a theme :
   . Datasystems
   . Cameroun

但我想显示这样的表格:

Choice a theme:
       . Datasystems                    . Cameroun

我的 .html文件如下所示:

{% extends 'Base_Configurations.html' %} 
{% load staticfiles %} 
{% load static %} 
{% block title %}
    <h3> <span class="glyphicon glyphicon-file"></span> Choix du thème DatasystemsEC </align> </h3>
{% endblock %}

{% block content %}

    <form class="form" method='POST' action=''> {% csrf_token %}
        <br></br>
        {{ form }}
        <br></br>
        <input class="button" type="submit" value="Valider le thème" />
    </form>

{% endblock %}

我还有 .css文件

.form-fields {
    border-radius: 4px;
    margin-right: auto;
    width:50%;
    background-color: #f5f5f5;

    }

.form {
    padding-left:8vw;

}

label {
        width: 35%;
        border-radius: 8px; 
        margin-bottom: -20px;
        list-style: none;
}

目前,我找不到解决问题的方法。我查看了一些教程或StackOverflow问题,但到目前为止还没有。

你对这个处理有什么想法吗?

4 个答案:

答案 0 :(得分:2)

不要使用{{form}},而是手动打开表单字段。

  {% for field in form  %}
    {{ field.errors }}
    <li> {{ field.label_tag }} {{ field }} </li> 
  {% endfor %}

CSS -

li {
    list-style-type: none; 
    display : inline;
    }

我认为它会起作用。如果有,请告诉我。

答案 1 :(得分:1)

您可以通过 Bootstrap 网格系统执行此操作。正如问题中所建议的,每行上会有两个字段。

试试这个:

  <div class="container">
    <div class="row">
    {% for field in form  %}
      <div class="col-sm-6">
        <b>{{ field.label_tag }}</b> - {{ field }} 
      </div>
    {% endfor %}
    </div>  
  </div>

答案 2 :(得分:0)

您可以在此处查看https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates

如果您使用的是bootstrap,则可以在forms.py

中添加所需的类

像:

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

或:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

答案 3 :(得分:0)

内联脆皮形式: 每行2列。

<form method="post" id="id_form" class="mx-auto text-left">
    {% csrf_token %}
    <div class="row">
        {% for field in form %}
            <div class="col-sm-6 ">
                {{ field|as_crispy_field }}
            </div>
        {% endfor %}
    </div>

    <button type="submit" class=" d-block btn btn-lg btn-success mt-4 w-50 mx-auto">
        Save
    </button>
</form>
相关问题