user1427661
user1427661

Reputation: 11774

Dynamically add a placeholder to a form field

I have a Django form with a few typical fields:

first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
phone = USPhoneNumberField(label=_("Phone Number"))
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
    widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
    widget=forms.PasswordInput,
    help_text=_("Enter the same password as above, for verification."))

When rendering the form on a site, I create the fields using the following code:

    <label for="id_first_name">First Name: </label>{{ form.first_name }}
    <label for="id_last_name">Last Name: </label>{{ form.last_name }}
    <p><label for="id_email">Email: </label>{{ form.email }}
    <p><label for="id_phone">Phone: </label>{{ form.phone }}
    <p><label for="id_password1">Password: </label>{{ form.password1 }}
    <p><label for="id_password2">Password Confirmation: </label>{{ form.password2 }}
    <p><input type="submit" value="Sign up" /></p>

The problem is that I want placeholders for certain fields (Email, first name, last name), but I don't want them to be generic placeholders like "Email address", "First name", etc. Based on the app's business logic, I want them to be actual names and email addresses that come from the context of the view but that the user still has the power to change before making them final.

I want to leverage the convenience of forms, but it doesn't seem like there's an easy way to dynamically generate the placeholder attribute without totally foregoing Django forms and just using regular HTML tags. Any thoughts?

Upvotes: 3

Views: 2493

Answers (2)

schacki
schacki

Reputation: 9533

You can add any form field attributes dynamically during form initialization like this:

class MyForm(forms.Form):
    field = forms.TextField()
    def __init__(self, *args, **kwargs):
        form = super(MyForm, self).__init__(*args, **kwargs)
        form.fields['field'].widget.attrs['placeholder']='custom_placeholder'

However, based on your description, are you sure you need placeholders or do you want the form field to be prepopulated with a certain value that will be submitted to the server unless the user changes it.

Upvotes: 1

ndpu
ndpu

Reputation: 22561

You can set placeholder to form field dynamically:

def someview(request):
    form = SomeForm(..)

    if some_condition:
        form.fields['email'].widget.attrs['placeholder'] = instance.email

Upvotes: 8

Related Questions