简体   繁体   English

如何并排放置 django 表单字段

[英]How to place django form fields side by side

I have a UserCreationForm which I want the first_name and last_name to be side by side, When I try the whole fields are side to side, I want the other fields to have their own line.我有一个 UserCreationForm 我希望 first_name 和 last_name 并排,当我尝试整个字段并排时,我希望其他字段有自己的行。 form.html:表格.html:

{% csrf_token %}
{% for field in form %}
<p>
    {% if field.help_text %}
    <small style="color: grey">{{ field.help_text }}</small>
    {% endif %}
    {{ field.label_tag }}
    {{ field }}
    {% for error in field.errors %}
    <p style="color: red">{{ error }}</p>
    {% endfor %}
</p>
{% endfor %} 

forms.py: forms.py:

class AccountCreationForm(UserCreationForm):
    class Meta:
        model = Account
        fields = ('first_name','last_name', 'email')

Since you are surrounding each field with a <p> tag, they all go into a separate line each.由于您使用<p>标记围绕每个字段,因此它们都 go 每个都放在单独的行中。 You can render your fields individually to style them as you like.您可以单独渲染字段以根据需要设置它们的样式。 Also check out this article for some examples.另请查看本文以获取一些示例。

I wrote a quick snippet for your exact case.我为您的确切情况写了一个简短的片段。 Note that I render the fields individually and have both name fields in the same <p> (Paragraph) tag.请注意,我单独呈现字段并将两个名称字段都放在同一个<p> (段落)标记中。

    <p>
        {% if form.first_name.help_text %}
        <small style="color: grey">{{ form.first_name.help_text }}</small>
        {% endif %}
        {{ form.first_name.label_tag }}
        {{ form.first_name }}
        {% for error in form.first_name.errors %}
        <span style="color: red">{{ error }}</span>
        {% endfor %}
        {% if form.last_name.help_text %}
        <small style="color: grey">{{ form.last_name.help_text }}</small>
        {% endif %}
        {{ form.last_name.label_tag }}
        {{ form.last_name }}
        {% for error in form.last_name.errors %}
        <span style="color: red">{{ error }}</span>
        {% endfor %}
    </p>
    <p>
        {% if form.email.help_text %}
            <small style="color: grey">{{ form.email.help_text }}</small>
            {% endif %}
            {{ form.email.label_tag }}
            {{ form.email }}
            {% for error in form.email.errors %}
            <span style="color: red">{{ error }}</span>
            {% endfor %}
    </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM