问题描述
我刚接触Django并读了一堆书,现在我正在构建我的第一个应用程序.当我使用...在模板中呈现表单时
I have just gotten into Django and read a bunch of books, now im building my first app. When I render my forms in my template im using...
{{ form.as_ul }}
现在我正在尝试将一些CSS应用于表单.事实证明很难使它看起来不错.我想知道是否有更好的方式来渲染和样式化表格?
And now I'm trying to apply some CSS to my form. It's proving difficult to get it look nice. I was wondering if there is a better way of rendering and styling forms?
推荐答案
好,您可以利用以下几个选项:
Well, there are a couple of options that you can take advantage of like:
-
form.as_p
-
form.as_ul
-
form.as_table
由您决定自己想要什么.至于使用CSS进行自定义,请在此处查看他们如何构造表单(摘自Django文档):
Its up to you to decide what you would like. As for customizing it with CSS, take a look at how they structured the form here (taken from django docs):
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
<div class="fieldWrapper">
{{ form.message.errors }}
<label for="id_message">Your message:</label>
{{ form.message }}
</div>
<div class="fieldWrapper">
{{ form.sender.errors }}
<label for="id_sender">Your email address:</label>
{{ form.sender }}
</div>
<div class="fieldWrapper">
{{ form.cc_myself.errors }}
<label for="id_cc_myself">CC yourself?</label>
{{ form.cc_myself }}
</div>
<p><input type="submit" value="Send message" /></p>
</form>
原始形式如下:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
因此,如您所见,您可以通过
So, as you can see, you can just access the form element, by
{{形式.< element_name>.< element_properties>}}
您可以将自己的CSS添加到 label
s或 div
s中.完全由您决定要做什么.附带说明一下,如果您希望使用Bootstrap 3格式化表格,那么我建议您使用 django-crispyforms
django的扩展名.
You can add your own CSS to the label
s or div
s. Its totally up to you to decide what you want to do. On a side note, if you want forms formatted with Bootstrap 3, then might I suggest that you use django-crispyforms
extension for django.
这篇关于Django格式化表格的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!