Django:如何向表单上的输入字段添加任意 html 属性?

发布于 2024-09-03 00:12:13 字数 404 浏览 9 评论 0原文

我有一个使用如下模板呈现的输入字段:

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

叫思念不要吵 2024-09-10 00:12:14

最终形式外观和渲染我花了好几天的时间尝试创建可重用的表单模板来在 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')
  });

Final form look and renderingI 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.

#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 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

 <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 Code remember to load this in $(document).ready(function() { /* ... */}); 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')
  });
枉心 2024-09-10 00:12:14

例子:

class LoginForm(forms.ModelForm):
        username = forms.CharField(max_length=50, label='Username', widget=forms.TextInput(attrs={"class":"login-input", "autocomplete": "username"}))
        password = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={"class":"login-input", "autocomplete": "current-password"}))

Example:

class LoginForm(forms.ModelForm):
        username = forms.CharField(max_length=50, label='Username', widget=forms.TextInput(attrs={"class":"login-input", "autocomplete": "username"}))
        password = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={"class":"login-input", "autocomplete": "current-password"}))
锦上情书 2024-09-10 00:12:13

检查此页面

city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))

Check this page

city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))
暗恋未遂 2024-09-10 00:12:13

抱歉打广告,但我最近发布了一个应用程序(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>

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:

{% 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>
失退 2024-09-10 00:12:13

如果您使用“ModelForm”:

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['city'].widget.attrs.update({
            'autocomplete': 'off'
        })

If you are using "ModelForm":

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['city'].widget.attrs.update({
            'autocomplete': 'off'
        })
望她远 2024-09-10 00:12:13

如果您使用的是 ModelForm,除了可以使用 __init__ 作为他的答案中提供的 @Artificioo 之外,Meta 中还有一个 widgets 字典用于重要的是:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

相关文档

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:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

Relevant documentation

人│生佛魔见 2024-09-10 00:12:13

我不想使用整个应用程序来做这件事。
相反,我在这里找到了以下代码 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" }}

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/

# 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

{% load utils %}
{{ form.field_1|add_attr:"class:my_class1 my_class2" }}
{{ form.field_2|add_attr:"class:my_class1 my_class2,autocomplete:off" }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文