Issue
We used random.choice()
to show random placeholders in an entry form.
class EntryForm(forms.ModelForm):
class Meta:
my_placeholders = ['The fact that...',
'I am sure that...',
'It is awesome to...',
'I wish this was...',
'I always wanted to know how...',
'The reason I am writing this is...'
]
my_placeholders_random = random.choice(my_placeholders)
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80, 'placeholder': my_placeholders_random})}
This works, but only if the local server is stopped using CTRL-C
and restarted with python manage.py runserver
or when we make changes in the file and save it. In those cases another placeholder is displayed.
However, when the server is running, and we refresh the entry page a couple of times, the placeholder stays the same every time.
In what way can we make sure the placeholder will be changed after every refresh?
Solution
It will only run when you interpret the file for the first time. Then it will thus stick to the item it picked, as you found out.
But we can just move the logic to the constructor of the form, like:
my_placeholders = [
'The fact that...',
'I am sure that...',
'It is awesome to...',
'I wish this was...',
'I always wanted to know how...',
'The reason I am writing this is...',
]
class EntryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['text'].widget.attrs['placeholder'] = random.choice(
my_placeholders
)
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {
'text': forms.Textarea(attrs={'cols': 80, 'placeholder': None})
}
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.