Answers:
city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))
抱歉广告,但我最近发布了一个应用程序(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>
或者,
{% load widget_tweaks %}
...
<div class="field">
{% render_field form.city autocomplete="off" class+="my_css_class" %}
</div>
如果使用“ ModelForm”:
class YourModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['city'].widget.attrs.update({
'autocomplete': 'off'
})
如果您正在使用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}),
}
我不想为此使用整个应用程序。相反,我在这里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)
使用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" }}
我花了很多天的时间来尝试创建可重用的表单模板,以在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
@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代码 注意:我正在使用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代码请记住将其加载到$(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')
});