Pythonic Django 表单 Charfield CSS

Pythonic Django Form Charfield CSS

我有一个 Django Charfield 表单,我想通过 CSS 更改它。我想用两种方式改变它。

 1. Width = 300 (solution below)
 2. Submit button inline with the input field (no idea)

forms.py:

class SheetForm(forms.Form):
    sheet_lookup = forms.CharField(max_length=30)

在我的 index.html 模板中提供:

{% extends "check/base.html" %}
{% block content %}

<div>
<form method="POST" class="post-form">
    {% csrf_token %}
    <h1>Scan Here:</h1>{{ form.as_p }}
    <button type="submit" class="save btn btn-default">Scan</button>

</form>
</div>
{% endblock %}

我的base.html:

{% load staticfiles %}
<html>
<head>
    <title>Sheet Checker</title>
    <link href="http://fonts.googleapis.com/css?family=Francois+One" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

    <link rel="stylesheet" href="{% static "css/main.css" %}">
</head>
<body>
    <div>
        <h1><a href="{% url 'index' %}">Sheet Check</a></h1>
    </div>
    <div>
        {% block content %}
        {% endblock %}
    </div>
</body>
</html>

我有一个 forms.py 有效:

class SheetForm(forms.Form):
    sheet_lookup = forms.CharField(
                         max_length=30, 
                         widget=forms.TextInput(attrs={'style':'width:300;'}))

但我认为这不是影响宽度变化的正确方法。

此外,我完全坚持让按钮与输入字段内联

对于宽度,您可以执行您提到的操作,即在表单中设置小部件属性,或者您可以在下面给出的模板中执行此操作-


index.html

{% extends "check/base.html" %}
{% block content %}

<div>
<form method="POST" class="post-form">
    {% csrf_token %}
    <h1>Scan Here:</h1>
    {% for field in form %}
        {{ field.errors }}
        {{ field.label_tag }}
        <input type="text" maxlength="30" style="width:300;" id="{{ field.auto_id }}" name="{{ field.html_name }}"/>
    {% endfor %}
    <button type="submit" class="save btn btn-default">Scan</button>
</form>
</div>
{% endblock %}

This will help you understand it.

编辑(对 css sheet 做同样的事情)- 您只需使用 class 而不是内联样式。

{% extends "check/base.html" %}
{% block content %}

<div>
<form method="POST" class="post-form">
    {% csrf_token %}
    <h1>Scan Here:</h1>
    {% for field in form %}
        {{ field.errors }}
        {{ field.label_tag }}
        <input type="text" maxlength="30" class="fixed-width" id="{{ field.auto_id }}" name="{{ field.html_name }}"/>
    {% endfor %}
    <button type="submit" class="save btn btn-default">Scan</button>
</form>
</div>
{% endblock %}

在你身上style.css

.fixed-width {
    width: 300px,
}

OP Edit - 修复了从 {% field.errors %}{{ field.errors }}{% field.label_tag %}{{field.label_tag}} 的格式以在 Django 中工作1.8