Random word on form

I am trying to place a random word on a form field’s placeholder, so that it is semi-dynamic. However, I am failing so far, because the random element seems to get locked in at server initialisation, rather than producing a random word each time.

The random word generator:

def random_search_prompt():
	thelist = [
				'take away',
				'off licence',
	return random.choice(thelist)

The form:

class DirectorySearchForm(forms.Form):
    q = forms.CharField(required=False, label=_('Search'), 
            attrs={'placeholder': ('Search for ' + random_search_prompt())}

So, every time I get “barber”, until I restart Apache, and then I get another word (perhaps), until I restart again…

How to get a randomised placeholder on each load of the page?


1 Like

When does random_search_prompt() get called?

I can tell you: It gets called during “import-time”, not at “request-time”.

You can set attrs during the constructor (__init__()) of your Form, then it will be called for every request.

Thanks, looking at the __init()__ almost got me to the answer, but once I had figured out how to update the attrs I started getting errors in the browser that the form had no attribute get, or render_to_response… which all started to seem very peculiar…

Then I remembered that this wasn’t a standard form view, and thus came to a solution like:

class DirectorySearchView(ListView):
	def get_context_data(self, **kwargs):
		context = super(DirectorySearchView, self).get_context_data(**kwargs)
		context['form'] = DirectorySearchForm(self.request.GET or None)
		context['form'].fields['q'].widget.attrs.update({'placeholder': ("Search for… " + utilskit.random_search_prompt())})
		return context

The unfortunate part about this is that for each view on which this form resides (there are three) I have to effectively repeat this setup of the context. But I’ll figure that bit out later.