如何更好地设计混合 django 形式

How to style mixed django form better

我有这两种形式:

class InitialForm(Form):
    trn = IntegerField(widget=NumberInput, required = False)
    klient = ChoiceField(choices=KLIENTS, required = False)

class SecondForm(Form):
    faktura = CharField(max_length = 200, required=False)

在表格中,我混合了 django 表格和纯 html select(因为我需要从数据库中提取一些数据)

<form method="POST" novalidate>
        {% csrf_token %}

        <label for="{{ form.klient.id_for_label }}">Klient:&nbsp;&nbsp;&nbsp;&nbsp;</label>
        {{ form.klient }}
        <br><br>

        <label for="programs">Program: </label>
        <select id="programselect" name="programs">
        {% for option in options %}
            <option value="{{ option.0}}">{{ option.1 }}</option>
        {% endfor %}
        </select>
        <br><br>

        <label for="{{ form.trn.id_for_label }}">Trn:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </label>
        {{ form.trn }}
        <br><br>

        <label for="{{ form2.faktura.id_for_label }}">Faktura:&nbsp;&nbsp;</label>
        {{ form2.faktura }}
        <br>

        <button type="submit" class="btn btn-secondary">Search</button>
</form>

到目前为止,我尝试使用 &nbsp& 来让 inputs 相互叠加。

CSS 你认为如何更好地设计它?

假设您正在使用 crispy 模板包进行样式设置,您可以创建一个模型表单 class 并从数据库中为 programs 字段提供初始“选项”,使用任何查询您存储“选项”的模型。这是一个示例,使用了一些关于您的数据库架构的假设:

        class ProgramForm(forms.ModelForm):
            class Meta: 
                fields = ['program']
                model = MyRecord

            def __init__(self, *args, **kwargs):
                super(ProgramForm, self).__init__(*args, **kwargs)
                self.fields['program'].queryset = Option.objects.filter(some_field=True).order_by("option_name")

使用这种解决方案,您将使用后端模型表单 class 来处理传递“选项”数据,并在 html 中使用 crispy 进行所有样式设置。请注意,如果您使用两个单独的表单,请使用不同的名称将它们传递给您的模板,例如:

{{form.klient|as_crispy_field}}
{{program_form.program|as_crispy_field}}

此外,您可以使用 Django 的小部件为您的选项添加功能 select 或者,例如,如果您想要复选框而不是下拉菜单 select(比方说,ForeignKey 与 M2M)。

如果您可以做到 none 并且必须使用这种 HTML 结构和后端方法,您仍然可以使用 CSS 来定位表单,例如:

<style>
#this-label span {

        margin-right: 100px;
    }

</style>

<label for="{{ form.trn.id_for_label }}" id="this-label"> <span>Trn:</span> </label>

...将在“Trn:”的右侧添加 space。这只是这样做的一种方法,但您可以将 class 添加到 span 元素并定位多个此类标记。