How to add placeholder to forms of Django-Registration

旧巷老猫 提交于 2019-12-21 05:07:27

问题


I am using django-registration for my project. in my registration_form.html file:

{{form.username}}
{{form.email}}
//other fields

And I want to set placeholders for each field. But this is a kind of built-in app. so I need to find the way for editing these fields from my main app.

I don't want to change source of django-registration.


回答1:


If you can override the built-in form, you can define the placeholder as follows:

class RegistrationForm(forms.ModelForm):
    class Meta:
        model = YourModelName
        widgets = {
            'username' : forms.TextInput(attrs = {'placeholder': 'Username'}),
            'email'    : forms.TextInput(attrs = {'placeholder': 'E-Mail'}),
        }

Or else you can use jQuery to add placeholder to the fields by using the corresponding field's id as given below:

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

You can use firebug to find the id of the field.




回答2:


I would actually create a template tag filter that modifies the field.

@register.filter
def html_placeholder(field, args=None):
    if args == None:
        return field
    field.field.widget.attrs.update({ "placeholder": args })
    return field



回答3:


Another approach, which works for django.contrib.auth.AuthenticationForm (and I assume should work in your case as well) is to inject this information while rendering the view. That way you don't need to embed it in your form class and don't need to force jquery.

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


来源:https://stackoverflow.com/questions/13523286/how-to-add-placeholder-to-forms-of-django-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!