我正在使用django-registration进行我的项目。在我的registration_form.html
文件中:
{{form.username}}
{{form.email}}
//other fields
我希望为每个字段设置占位符。但是这是一种内置应用程序,因此我需要找到一种从我的主要应用程序中编辑这些字段的方法。
我不想改变django-registration的源代码。
我正在使用django-registration进行我的项目。在我的registration_form.html
文件中:
{{form.username}}
{{form.email}}
//other fields
我希望为每个字段设置占位符。但是这是一种内置应用程序,因此我需要找到一种从我的主要应用程序中编辑这些字段的方法。
我不想改变django-registration的源代码。
如果您可以覆盖内置表单,您可以按如下方式定义占位符:
class RegistrationForm(forms.ModelForm):
class Meta:
model = YourModelName
widgets = {
'username' : forms.TextInput(attrs = {'placeholder': 'Username'}),
'email' : forms.TextInput(attrs = {'placeholder': 'E-Mail'}),
}
或者你可以使用jQuery将占位符添加到字段中,方法是使用相应字段的id
,如下所示:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#id_username").attr('placeholder', '{{form.username.label}}');
$("#id_email").attr('placeholder', '{{form.email.label}}');
});
</script>
你可以使用Firebug来查找该字段的id
。
class Meta(RegistrationForm.Meta):
更改为class Meta:
。为什么要这样定义Meta类? - arulmr我会创建一个模板标签过滤器来修改该字段。
@register.filter
def html_placeholder(field, args=None):
if args == None:
return field
field.field.widget.attrs.update({ "placeholder": args })
return field
def index(request):
form = AuthenticationForm(request)
form.fields['username'].widget.attrs.update({
'placeholder': 'Name'
})
form.fields['password'].widget.attrs.update({
'placeholder': 'Password'
})
context = RequestContext(request, {
'form' : form,
})
return HttpResponse(template.render(context))