Hi, I would like to create and save an object in the database which has arguments args
and kwargs
. the arguments args
and kwargs
must obey the format JSON
, I have the following:
class ProgramarActividadForm(forms.ModelForm):
class Meta:
model = Mymodel
fields = '__all__'
widgets = {
'nombre': forms.TextInput(attrs={
'type' : 'text',
'placeholder' : 'Nombre de la Tare ',
'class': 'form-control'}),
'tarea':forms.Select(attrs = {
'class' : 'form-control',
}),
'usuarios_envio':forms.Select(attrs = {
'class' : 'form-control',
}),
'grupo_envio':forms.Select(attrs = {
'class' : 'form-control',
}),
}
The fields usuarios_envio
and grupo_envio
are as follows in the models:
usuarios_envio = models.ForeignKey('Usuarios.User')
grupo_envio = models.ForeignKey('auth.group')
In my view.py
I have something like this:
def form_valid(self, form):
task = ObjectTask(
name= form.cleaned_data['nombre'],
task=form.cleaned_data['tarea'],
args=json.dumps(form.cleaned_data['usuarios_envio']),
kwargs=json.dumps({form.cleaned_data['grupo_envio']})
)
task.save()
return super(ProgramarActividadView,self).form_valid(form)
Saving normal variables does not cause problems but when the argument is an object, in this case for args
and kwargs
tells me that it can not be serialized.
Error:
<User: Administrator> is not JSON serializable
Update:
The first solution they propose is tested
kwargs=json.dumps({'msjtxt': form.cleaned_data['usuarios_envio'].__dict__,})
But now you get an error:
PhoneNumber is not serializable JSON
because as seen:
usuarios_envio = models.ForeignKey('Usuarios.User')
refers to a model User
and that model has an attribute:
celular_gsm = PhoneNumberField(blank=True, help_text=help_text_number)
I already tried the following solution:
kwargs=json.dumps({'msjtxt': form.cleaned_data['usuarios_envio'].values(),})
But I get an error because User
does not have the attribute Values
Then I tried the following:
kwargs=json.dumps({'msjtxt': form.cleaned_data['usuarios_envio'].__dict__.values(),})
And he sent me the following error:
dict_values ([PhoneNumber (country_code = 52, national_number = 1234567890, extension = None, italian_leading_zero = None, number_of_leading_zeros = None, country_code_source = 1, preferred_domestic_carrier_code = ''), PhoneNumber (country_code = 52, national_number = 1234567890, extension = None, italian_leading_zero = None, number_of_leading_zeros = None, country_code_source = 1, preferred_domestic_carrier_code = ''), 'Centrales', '123213', '', False, 2, 'IngOM', 'maternal', 'Paterno', True, None , '[email protected]', PhoneNumber (country_code = 52, national_number = 123456789, extension = None, italian_leading_zero = None, number_of_leading_zeros = None, country_code_source = 1, preferred_domestic_carrier_code = ''), datetime.datetime (2016, 1, 7, 18, 6, 43, tzinfo =), 'Raul', '12312313', False]) is not serializable JSON