【问题标题】:How to add a placeholder attribute in Django Form如何在 Django 表单中添加占位符属性
【发布时间】:2016-10-04 05:06:55
【问题描述】:

我在表单中添加占位符属性时遇到问题。我想添加一个占位符,使我的 HTML 看起来像:

<input type="text" name="sample" placeholder="sample">

现在这是我的代码的样子。

这是我的模特:

from django.db import models

class Sample(models.Model):

    name = models.CharField("Name", max_length=120)

这是我的表格:

from django.forms import ModelForm, TextInput
from .models import Sample

class SampleForm(ModelForm):

    class Meta:
        INPUT_CLASS = 'form-control'

        model = Sample
        widgets = { 
            'name': TextInput(attrs={'class':INPUT_CLASS, 
                                     'placeholder':'Enter title here'}),
        }

观看次数

def update(request):

     sampleForm = SampleForm()

     return render(request, 'sample/profile.html', 'form':sampleForm)

在我的表单中,当我包含占位符属性时,它不起作用。让这项工作发挥作用的最佳方法应该是什么?

【问题讨论】:

  • 你是如何渲染表单的?请贴出相关模板代码。

标签: python django forms placeholder


【解决方案1】:

虽然有点晚了,但我还是会插手的。我一直在尝试做同样的事情,而不必重新定义表单中使用的小部件。发现以下工作:

class ExampleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)

        # sets the placeholder key/value in the attrs for a widget
        # when the form is instantiated (so the widget already exists)
        self.fields['name_of_field'].widget.attrs['placeholder'] = 'random placeholder'

编辑:虽然我意识到这并不能回答你的代码为什么不起作用的问题......

【讨论】:

    【解决方案2】:

    就形式本身而言,这对我总是有效的

    class SampleForm(ModelForm):
        class Meta:
            model = Sample
    
        name = forms.CharField(
            label='Name', 
            widget=forms.TextInput(
                attrs={'class': 'form-control', 'placeholder': 'Enter title here'}
            )
        )
    

    【讨论】:

    • @solarissmoke 我还不知道
    猜你喜欢
    • 2012-11-11
    • 2013-10-29
    • 2019-06-06
    • 2011-09-17
    • 2019-04-14
    • 2018-12-23
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多