Django ModelForm with Select Widget - Use object.uid as default option value instead of object.id
django, django-forms, django-widget
Solution
You can do something like this:
class ChildModel(ModelForm):
secretdocs = forms.ChoiceField(choices=[(doc.uid, doc.name) for doc in Document.objects.all()])
class Meta:
model = Documents
fields = ('secretdocs', )
widgets = {
'secretdocs': Select(attrs={'class': 'select'}),
}
Problem
I have a form inheriting from ModelForm as such: ``` class ChildModel(ModelForm): class Meta: model = Documents fields = ('secretdocs') widgets = { 'secretdocs': Select(attrs={'class': 'select'}), } ``` The model "secretdocs" has a uid. But when it prints out the select and option, the option values appear as such: ``` <select class="select" id="id_secretdocs" name="secretdocs"> <option value="1">My Secret Doc</option> </select> ``` But I want it to instead have the uid of the option: ``` <select class="select" id="id_secretdocs" name="secretdocs"> <option value="cd2feb4a-58cc-49e7-b46e-e2702c8558fd">My Secret Doc</option> </select> ``` I've so far tried to use BaseForm's data object and overwriting Select's value_from_datadict method but I'm pretty sure that wasn't the right approach. Does anyone know how I can do this? Thanks in advance.