Django:如何向表单上的输入字段添加任意 html 属性?
我有一个使用如下模板呈现的输入字段:
<div class="field">
{{ form.city }}
</div>
呈现为:
<div class="field">
<input id="id_city" type="text" name="city" maxlength="100" />
</div>
现在假设我想向呈现的输入元素添加 autocomplete="off"
属性,我该如何做这样做吗?或者onclick="xyz()"
或class="my-special-css-class"
?
I have an input field that is rendered with a template like so:
<div class="field">
{{ form.city }}
</div>
Which is rendered as:
<div class="field">
<input id="id_city" type="text" name="city" maxlength="100" />
</div>
Now suppose I want to add an autocomplete="off"
attribute to the input element that is rendered, how would I do that? Or onclick="xyz()"
or class="my-special-css-class"
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我花了好几天的时间尝试创建可重用的表单模板来在 Django 表单中创建和更新模型。请注意,我使用 ModelForm 来更改或创建对象。我还使用引导程序来设计我的表单。
我过去使用 django_form_tweaks 来处理某些表单,但我需要一些自定义,而无需太多模板依赖。由于我的项目中已经有 jQuery,我决定利用它的属性来设计我的表单。
这是代码,可以使用任何形式。
Views.py
HTML 代码
注意:我使用 bootstrap4 模式来消除创建许多视图的麻烦。也许使用通用的 CreateView 或 UpdateView 更好。
链接 Bootstrap 和 jqQery
Javascript 代码 请记住将其加载到
$(document).ready(function() { /* ... */});
函数中。I have spent quite a few days trying to create re-usable form templates to create and update models in Django forms. Note that am using ModelForm to change or create object. Am using also bootstrap to style my forms.
I used django_form_tweaks for some forms in past, but I needed some customization without a lot of template dependency. Since I already have jQuery in my Project I decided to leverage its properties to style my forms.
Here is the code, and can work with any form.
Views.py
HTML Code
Note: Am using bootstrap4 modal to remove the hassle of creating many views. Maybe it is better to use generic CreateView or UpdateView.
Link Bootstrap and jqQery
Javascript Code remember to load this in
$(document).ready(function() { /* ... */});
function.例子:
Example:
检查此页面
Check this page
抱歉打广告,但我最近发布了一个应用程序(https://github.com/kmike/django-widget-tweaks ),这使得此类任务变得更加轻松,因此设计人员可以在不接触 Python 代码的情况下完成此任务:
或者,
Sorry for advertisment, but I've recently released an app (https://github.com/kmike/django-widget-tweaks) that makes such tasks even less painful so designers can do that without touching python code:
or, alternatively,
如果您使用“ModelForm”:
If you are using "ModelForm":
如果您使用的是
ModelForm
,除了可以使用__init__
作为他的答案中提供的 @Artificioo 之外,Meta 中还有一个widgets
字典用于重要的是:相关文档
If you are using
ModelForm
, apart from the possibility of using__init__
as @Artificioo provided in his answer, there is awidgets
dictionary in Meta for that matter:Relevant documentation
我不想使用整个应用程序来做这件事。
相反,我在这里找到了以下代码 https://blog.joeymasip.com/how-to-add-attributes-to-form-widgets-in-django-templates/
使用html文件中的标签
I did't want to use an entire app for this thing.
Instead I found the following code here https://blog.joeymasip.com/how-to-add-attributes-to-form-widgets-in-django-templates/
use the tag in the html file