Django:如何将任意 html 属性添加到表单上的输入字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2902008/
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
Django: How do I add arbitrary html attributes to input fields on a form?
提问by User
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"
?
现在假设我想向autocomplete="off"
呈现的输入元素添加一个属性,我该怎么做?或onclick="xyz()"
或class="my-special-css-class"
?
回答by Galen
回答by Mikhail Korobov
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:
抱歉打广告,但我最近发布了一个应用程序(https://github.com/kmike/django-widget-tweaks),它使这些任务变得更不痛苦,所以设计师可以在不接触 python 代码的情况下做到这一点:
{% load widget_tweaks %}
...
<div class="field">
{{ form.city|attr:"autocomplete:off"|add_class:"my_css_class" }}
</div>
or, alternatively,
或者,或者,
{% load widget_tweaks %}
...
<div class="field">
{% render_field form.city autocomplete="off" class+="my_css_class" %}
</div>
回答by Artificioo
If you are using "ModelForm":
如果您使用“ModelForm”:
class YourModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['city'].widget.attrs.update({
'autocomplete': 'off'
})
回答by Wtower
If you are using ModelForm
, apart from the possibility of using __init__
as @Artificioo provided in his answer, there is a widgets
dictionary in Meta for that matter:
如果您正在使用ModelForm
,除了__init__
在他的回答中提供使用@Artificioo的可能性之外widgets
,Meta 中还有一本字典:
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}
回答by ohlr
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/
我不想为这件事使用整个应用程序。相反,我在这里找到了以下代码https://blog.joeymasip.com/how-to-add-attributes-to-form-widgets-in-django-templates/
# utils.py
from django.template import Library
register = Library()
@register.filter(name='add_attr')
def add_attr(field, css):
attrs = {}
definition = css.split(',')
for d in definition:
if ':' not in d:
attrs['class'] = d
else:
key, val = d.split(':')
attrs[key] = val
return field.as_widget(attrs=attrs)
use the tag in the html file
使用 html 文件中的标签
{% load utils %}
{{ form.field_1|add_attr:"class:my_class1 my_class2" }}
{{ form.field_2|add_attr:"class:my_class1 my_class2,autocomplete:off" }}
回答by Fahrer Feyton
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.
我花了好几天时间尝试创建可重用的表单模板,以在 Django 表单中创建和更新模型。请注意,我正在使用 ModelForm 来更改或创建对象。我也在使用引导程序来设计我的表单。过去我对某些表单使用了 django_form_tweaks,但我需要一些自定义而没有很多模板依赖。因为我的项目中已经有 jQuery,所以我决定利用它的属性来设计我的表单。这是代码,可以使用任何形式。
#forms.py
from django import forms
from user.models import User, UserProfile
from .models import Task, Transaction
class AddTransactionForm(forms.ModelForm):
class Meta:
model = Transaction
exclude = ['ref_number',]
required_css_class = 'required'
Views.py
视图.py
@method_decorator(login_required, name='dispatch')
class TransactionView(View):
def get(self, *args, **kwargs):
transactions = Transaction.objects.all()
form = AddTransactionForm
template = 'pages/transaction.html'
context = {
'active': 'transaction',
'transactions': transactions,
'form': form
}
return render(self.request, template, context)
def post(self, *args, **kwargs):
form = AddTransactionForm(self.request.POST or None)
if form.is_valid():
form.save()
messages.success(self.request, 'New Transaction recorded succesfully')
return redirect('dashboard:transaction')
messages.error(self.request, 'Fill the form')
return redirect('dashboard:transaction')
HTML CodeNote: 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
HTML 代码注意:我使用 bootstrap4 模态来消除创建许多视图的麻烦。也许最好使用通用的 CreateView 或 UpdateView。链接 Bootstrap 和 jqQery
<div class="modal-body">
<form method="post" class="md-form" action="." enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="row">
<div class="col-md-12">
<div class="form-group row">
<label for="" class="col-sm-4 col-form-label {% if field.field.required %}
required font-weight-bolder text-danger{%endif %}">{{field.label}}</label>
<div class="col-sm-8">
{{field}}
</div>
</div>
</div>
</div>
{% endfor %}
<input type="submit" value="Add Transaction" class="btn btn-primary">
</form>
</div>
Javascript Coderemember to load this in $(document).ready(function() { /* ... */});
function.
Javascript 代码记得在$(document).ready(function() { /* ... */});
函数中加载它。
var $list = $("#django_form :input[type='text']");
$list.each(function () {
$(this).addClass('form-control')
});
var $select = $("#django_form select");
$select.each(function () {
$(this).addClass('custom-select w-90')
});
var $list = $("#django_form :input[type='number']");
$list.each(function () {
$(this).addClass('form-control')
});
var $list = $("form :input[type='text']");
$list.each(function () {
$(this).addClass('form-control')
});
var $select = $("form select");
$select.each(function () {
$(this).addClass('custom-select w-90')
});
var $list = $("form :input[type='number']");
$list.each(function () {
$(this).addClass('form-control')
});