【问题标题】:How can we use html <input type= ""> for Django model form?我们如何将 html <input type=""> 用于 Django 模型表单?
【发布时间】:2018-05-27 06:05:55
【问题描述】:
将这个用于 django 模型形式,我们无法创建漂亮的前端。
<form method="POST" action="">
{% csrf_token %}
<div class="esor">
Name: {{form.Name}}<br>
Class: {{form.Class}}<br>
Publisher: {{form.Publisher}}<br>
</div>
<input type="submit" value="submit">
</form>
有没有什么办法可以使用html代码,比如:
<form method="GET" action="#">
<input type="text" name="name" placeholder="Name of book">
</form>
而不是 {{form.Name}} 或 {{form.as_p}}
【问题讨论】:
标签:
html
django
forms
django-models
django-forms
【解决方案1】:
是的,你可以通过这种方式获得一个漂亮的界面,只需在 form.py 中传递你使用的名称
示例:
forms.py
class NameForm(forms.ModelForm):
class Meta:
model = MyModel
fields = [
"whatever"
]
HTML 模板
<form method="POST">{% csrf_token %}
<input type="text" name="whatever" placeholder="Write whatever">
</form>
【解决方案2】:
我通常使用两种方法:
安装widget tweaks,这样您就可以轻松自定义输入:
{% load widget_tweaks %}
{{ form.Name|add_class:"css_class"|attr:"placeholder:Name of book" }}
或者 2,在您的 forms.py 中,为该字段设置您想要的所有属性:
Name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name of book'}))
【解决方案3】:
您可以通过将输入元素的名称与表单字段的名称相同来做到这一点。您可以通过在 html 中显示 {{ form }} 然后在浏览器中检查表单字段来获取表单字段的名称,然后该字段的名称属性将是表单字段的名称。