Answer the question
In order to leave comments, you need to log in
How to change the value of a field in a form?
Hello!
I use JSONField , it stores data as a list ["123", "345", "test"], field oem_list .
When editing in the field, the data is in json ["123", "345", "test"], but you need it to be just comma-separated 123, 345, test!
How to change the data in the format I need, I try self.fields['oem_list'].initial, doesn't work?!
class QueryForm(forms.ModelForm):
oem_list = forms.CharField(label=u'OEM номера', required=False)
def __init__(self, user, *args, **kwargs):
super(QueryForm, self).__init__(*args, **kwargs)
self.fields['oem_list'].initial = u"Значение поля заменено" # не работает
class Meta:
model = Query
def clean_oem_list(self):
data = self.cleaned_data['oem_list'].upper()
if data and ',' in data:
data = list(set(x for x in data.split(',') if x))
elif data:
data = [data]
return data
Answer the question
In order to leave comments, you need to log in
Somehow strange you load json. First, try to do it right:
import json
.....
self.fields['oem_list'].initial = json.dumps(ваше поле с json).replace('"','')[1:-1]
.....
data = json.loads(self.cleaned_data['oem_list'])
You can write your own widget, override the render and value_from_datadict methods in it, and explicitly set oem_list for the field.
Why use a JSON field to store a list? Get ArrayField from djorm_pgarray if you have PostgreSQL.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question