【问题标题】:How to split form to two columns?如何将表格拆分为两列?
【发布时间】:2013-01-24 13:14:48
【问题描述】:

我有模特:

class Post(models.Model):
    path = 'images' + str(datetime.now().year) + '/' + str(datetime.now().month)
    image = models.ImageField(upload_to=path, null=True)
    recommended = models.BooleanField(default = False)
    promoted = models.BooleanField(default = False)
    title = models.TextField(blank = True)
    intro = RichTextField(config_name='full_ck', blank = True)
    text = RichTextField(config_name='full_ck', blank = True)

,形式:

class Form(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=Post.objects.all(), widget=forms.HiddenInput())

    class Meta:
        model = Post

和模板:

<table cellpadding="0" cellspacing="0">
<formset>
{% for field in form %}
    {% if field.is_hidden %}
        {{ field }}
    {% else %}
        <div class="fieldWrapper">
             {% if field.errors %}<div class="errorbox">{% endif %}
                <p>{{ field.label_tag }}</p>
                <p>{{ field }}{% block formextrafields %}{% endblock %}</p>
                <p></p>
            {% if field.errors %}<p>{{ field.errors }}</p></div>{% endif %}
        </div>
    {% endif %}
{% endfor %}
</formset>
</table>

但我想将表格分成两列。第一个可能是介绍、文本和标题字段,第二个可能是其他字段。怎么做?

【问题讨论】:

标签: django django-forms django-templates


【解决方案1】:

我在视图中使用这个:

form = list(form)

,在模型中我设置顺序:

class Meta:
    model = Post
    fields = (my fields in order)

在模板中:

<!-- first -->
<table cellpadding="0" cellspacing="0">
<formset>
{% for field in form|slice:":3" %}
    [...]
{% endfor %}
</formset>
</table>

<!-- second -->
<table cellpadding="0" cellspacing="0">
<formset>
{% for field in form|slice:"3:" %}
    [...]
{% endfor %}
</formset>
</table>

而且它有效。

【讨论】:

  • 它确实有效,我在整个项目中一直在寻找这个,我避免使用表单,因为它们看起来很乏味,这里的答案就在我眼前谢谢你陌生人。
【解决方案2】:

您可以使用清晰的表单进行布局并添加 css 类:https://github.com/maraujop/django-crispy-forms

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2021-12-31
    • 2021-01-29
    相关资源
    最近更新 更多