Last active
June 28, 2024 12:32
-
-
Save conor10/8085ac62fd81ad3002e582d1be65c398 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ListTextWidget(forms.TextInput): | |
| def __init__(self, data_list, name, *args, **kwargs): | |
| super(ListTextWidget, self).__init__(*args, **kwargs) | |
| self._name = name | |
| self._list = data_list | |
| self.attrs.update({'list': 'list__{}'.format(self._name)}) | |
| def render(self, name, value, attrs=None): | |
| text_html = super(ListTextWidget, self).render(name, value, attrs=attrs) | |
| data_list = '<datalist id="list__{}">'.format(self._name) | |
| for item in self._list: | |
| data_list += '<option value="{}">{}</option>'.format(item[0], item[1]) | |
| data_list += '</datalist>' | |
| return text_html + data_list | |
| # Usage | |
| from django import models | |
| class Address(models.Model): | |
| NSW = 'NSW | |
| VIC = 'VIC' | |
| QLD = 'QLD' | |
| SA = 'SA' | |
| WA = 'WA' | |
| TAS = 'TAS' | |
| NT = 'NT' | |
| STATES = ( | |
| (NSW, 'New South Wales'), | |
| (VIC, 'Victoria'), | |
| (QLD, 'Queensland'), | |
| (SA, 'South Australia'), | |
| (WA, 'Western Australia'), | |
| (TAS, 'Tasmania'), | |
| (NT, 'Northern Territory') | |
| ) | |
| from django import forms | |
| class ExampleForm(forms.ModelForm): | |
| class Meta: | |
| model = Address | |
| exclude = [''] | |
| widgets = { | |
| 'state': ListTextWidget(data_list=STATES, name='state_list') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
update your code
def render(self, name, value, attrs=None):todef render(self, name, value, attrs=None, renderer=None):