Django 表单中的 CSS 样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5827590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:25:41  来源:igfitidea点击:

CSS styling in Django forms

cssdjangodjango-forms

提问by David542

I would like to style the following:

我想设计以下样式:

forms.py:

表格.py:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

contact_form.html:

contact_form.html:

<form action="" method="post">
  <table>
    {{ form.as_table }}
  </table>
  <input type="submit" value="Submit">
</form>

For example, how do I set a classor IDfor the subject, email, messageto provide an external style sheet to?

例如,如何设置一个IDsubjectemailmessage以提供外部样式表到?

回答by shadfc

Taken from my answer to: How to markup form fields with <div class='field_type'> in Django

摘自我的回答: 如何在 Django 中使用 <div class='field_type'> 标记表单字段

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

or

或者

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

or

或者

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

--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented

--- 编辑---
以上是对原始问题代码进行的最简单的更改,以完成所要求的内容。如果您在其他地方重复使用该表格,它还可以防止您重复自己;如果您使用 Django 的 as_table/as_ul/as_p 表单方法,您的类或其他属性就可以工作。如果您需要完全控制完全自定义的渲染,这有明确记录

-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.

-- 编辑 2 ---
添加了一种更新的方法来为 ModelForm 指定小部件和属性。

回答by Charlesthk

This can be done using a custom template filter. Consider rendering your form this way:

这可以使用自定义模板过滤器来完成。考虑以这种方式呈现您的表单:

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subjectis an instance of BoundFieldwhich has the as_widget()method.

form.subject是一个BoundField具有as_widget()方法的实例。

You can create a custom filter addclassin my_app/templatetags/myfilters.py:

您可以addclassmy_app/templatetags/myfilters.py 中创建自定义过滤器:

from django import template

register = template.Library()

@register.filter(name='addclass')
def addclass(value, arg):
    return value.as_widget(attrs={'class': arg})

And then apply your filter:

然后应用您的过滤器:

{% load myfilters %}

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject|addclass:'MyClass' }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subjectswill then be rendered with the MyClassCSS class.

form.subjects然后将使用MyClassCSS 类呈现。

回答by John C

If you don't want to add anycode to the form (as mentioned in the comments to @shadfc's Answer), it is certainly possible, here are two options.

如果您不想在表单中添加任何代码(如@shadfc 的答案的评论中所述),当然可以,这里有两个选项。

First, you just reference the fields individuallyin the HTML, rather than the entire form at once:

首先,您只需在 HTML 中单独引用字段,而不是一次引用整个表单:

<form action="" method="post">
    <ul class="contactList">
        <li id="subject" class="contact">{{ form.subject }}</li>
        <li id="email" class="contact">{{ form.email }}</li>
        <li id="message" class="contact">{{ form.message }}</li>
    </ul>
    <input type="submit" value="Submit">
</form>

(Note that I also changed it to a unsorted list.)

(请注意,我也将其更改为 unsorted list。)

Second, note in the docs on outputting forms as HTML, Django:

其次,在将表单输出为 HTML,Django的文档中注意:

The Field id, is generated by prepending 'id_' to the Field name. The id attributes and tags are included in the output by default.

字段 id 是通过在字段名称前加上“id_”来生成的。id 属性和标签默认包含在输出中。

All of your form fields already have a unique id. So you would reference id_subjectin your CSS file to style the subjectfield. I should note, this is how the form behaves when you take the defaultHTML, which requires just printing the form, not the individual fields:

您所有的表单字段都已经有一个唯一的id。因此,您将在 CSS 文件中引用id_subject来设置主题字段的样式。我应该注意,这是当您采用默认HTML时表单的行为方式,它只需要打印表单,而不是单个字段:

<ul class="contactList">
    {{ form }}  # Will auto-generate HTML with id_subject, id_email, email_message 
    {{ form.as_ul }} # might also work, haven't tested
</ul>

See the previous link for other options when outputting forms (you can do tables, etc).

输出表单时,请参阅上一个链接以了解其他选项(您可以制作表格等)。

Note - I realize this isn't the same as adding a classto each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by idin your CSS like this:

注意 - 我意识到这与为每个元素添加一个不同(如果你向表单添加了一个字段,你还需要更新 CSS) - 但是通过id引用所有字段很容易在你的 CSS 中是这样的:

#id_subject, #id_email, #email_message 
{color: red;}

回答by aashanand

Per thisblog post, you can add css classes to your fields using a custom template filter.

根据这篇博文,您可以使用自定义模板过滤器将 css 类添加到您的字段中。

from django import template
register = template.Library()

@register.filter(name='addcss')
def addcss(field, css):
    return field.as_widget(attrs={"class":css})

Put this in your app's templatetags/ folder and you can now do

把它放在你的应用程序的 templatetags/ 文件夹中,你现在可以做

{{field|addcss:"form-control"}}

回答by Ignas But?nas

You can do like this:

你可以这样做:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    subject.widget.attrs.update({'id' : 'your_id'})

Hope that works.

希望有效。

Ignas

伊格纳斯

回答by Eamonn Faherty

You could use this library: https://pypi.python.org/pypi/django-widget-tweaks

你可以使用这个库:https: //pypi.python.org/pypi/django-widget-tweaks

It allows you to do the following:

它允许您执行以下操作:

{% load widget_tweaks %}
<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}

回答by Torsten Engelbrecht

You can do:

你可以做:

<form action="" method="post">
    <table>
        {% for field in form %}
        <tr><td>{{field}}</td></tr>
        {% endfor %}
    </table>
    <input type="submit" value="Submit">
</form>

Then you can add classes/id's to for example the <td>tag. You can of course use any others tags you want. Check Working with Django formsas an example what is available for each fieldin the form ({{field}}for example is just outputting the input tag, not the label and so on).

然后您可以将类/ID 添加到例如<td>标签中。您当然可以使用您想要的任何其他标签。以使用 Django 表单为例,检查表单中每个field表单的可用内容({{field}}例如只是输出输入标签,而不是标签等)。

回答by Simon Feltman

One solution is to use JavaScript to add the required CSS classes after the page is ready. For example, styling django form output with bootstrap classes (jQuery used for brevity):

一种解决方案是在页面准备好后使用 JavaScript 添加所需的 CSS 类。例如,使用引导类(jQuery 用于简洁)设置 django 表单输出的样式:

<script type="text/javascript">
    $(document).ready(function() {
        $('#some_django_form_id').find("input[type='text'], select, textarea").each(function(index, element) {
            $(element).addClass("form-control");
        });
    });
</script>

This avoids the ugliness of mixing styling specifics with your business logic.

这避免了将样式细节与您的业务逻辑混合在一起的丑陋之处。

回答by Arturo Alam Téllez

There is a very easy to install and great tool made for Django that I use for styling and it can be used for every frontend framework like Bootstrap, Materialize, Foundation, etc. It is called widget-tweaks Documentation: Widget Tweaks

有一个非常易于安装和为 Django 制作的很棒的工具,我用它来设计样式,它可以用于每个前端框架,如 Bootstrap、Materialize、Foundation 等。它被称为 widget-tweaks 文档:Widget Tweaks

  1. You can use it with Django's generic views
  2. Or with your own forms:
  1. 您可以将它与 Django 的通用视图一起使用
  2. 或者使用您自己的表格:

from django import forms

从 Django 导入表单

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

Instead of using default:

而不是使用默认值:

{{ form.as_p }} or {{ form.as_ul }}

You can edit it your own way using the render_field attribute that gives you a more html-like way of styling it like this example:

您可以使用 render_field 属性以您自己的方式对其进行编辑,该属性为您提供了一种更像 html 样式的方式,如下例所示:

template.html

模板.html

{% load widget_tweaks %}

<div class="container">
   <div class="col-md-4">
      {% render_field form.subject class+="form-control myCSSclass" placeholder="Enter your subject here" %}
   </div>
   <div class="col-md-4">
      {% render_field form.email type="email" class+="myCSSclassX myCSSclass2" %}
   </div>
   <div class="col-md-4">
      {% render_field form.message class+="myCSSclass" rows="4" cols="6" placeholder=form.message.label %}
   </div>
</div>

This library gives you the opportunity to have well separated yout front end from your backend

这个库让你有机会将前端与后端很好地分开

回答by Aula

Write your form like:

像这样写你的表格:

    class MyForm(forms.Form):
         name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name")
         message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message")

In your HTML field do something like:

在您的 HTML 字段中执行以下操作:

{% for field in form %}
      <div class="row">
        <label for="{{ field.name}}">{{ field.label}}</label>{{ field }}
     </div>
{% endfor %}

Then in your CSS write something like:

然后在你的 CSS 中写一些类似的东西:

.name{
      /* you already have this class so create it's style form here */
}
.message{
      /* you already have this class so create it's style form here */
}
label[for='message']{
      /* style for label */
}

Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.

希望这个答案值得一试!请注意,您必须编写视图来呈现包含表单的 HTML 文件。