Karthik J
Karthik J

Reputation: 109

How to make Django Forms JSON serializable

I am running a website using Django framework. Below is the code.

Forms.py :

class ProfileForm(forms.ModelForm):

class Meta:
    model=Profile
    widgets = {
        'address_line_1': forms.TextInput(attrs={'placeholder': 'Door No,Building'}),
        'address_line_2': forms.TextInput(attrs={'placeholder': 'Area,Locality'}),
    }
    fields=('first_name','last_name','mobile_no','email','address_line_1','address_line_2','postal_code','city','country','image','referral_contact','promo_coupon','ic')

views.py :

def signup(request):
    registered=False
    failed_ref=False
    wrong_ref=False
    if request.method=='POST':
       user_form = UserForm(data=request.POST)
       profile_form = ProfileForm(request.POST)
       if 'city' in request.POST:
           if user_form.is_valid() and profile_form.is_valid():
               user = user_form.save()
               user.set_password(user.password)
               user.save()
               profile = profile_form.save(commit=False)
               profile.user = user
            else:
                print(user_form.errors,profile_form.errors)
                user_err=''
                mobile_err=''
                if user_form.errors:
                   user_err="A profile with this username already exists!"
                if profile_form.errors:
                    mobile_err="A profile with this mobile number already exists!"
                data={'registered':registered,'failed_ref':failed_ref,'wrong_ref':wrong_ref,'user_error':user_err,
                  'profile_error':mobile_err}
                return JsonResponse(data)
    else:
        user_form=UserForm()
        profile_form=ProfileForm()
    return JsonResponse({'profile_form':profile_form,'registered':registered,
                                                    'failed_ref':failed_ref,'wrong_ref':wrong_ref})

I want to get response in JSON . The error i am getting is "TypeError: Object of type ProfileForm is not JSON serializable". Can anyone help to figure out why this is happening?

Upvotes: 0

Views: 1208

Answers (2)

Sazzy
Sazzy

Reputation: 1994

Try replacing this:

return JsonResponse({'profile_form':profile_form,

with this:

return JsonResponse({'profile_form':profile_form.__dict__,

This will get you going with what you have right now. However, I do not advise you run this code in production.

You should take a look at serializing your response objects. See https://www.django-rest-framework.org/ for more details.

Upvotes: 2

José Eras
José Eras

Reputation: 90

Use the json python library:

import json

#your code

profile_form=ProfileForm()
datos_response = {'profile_form': profile_form }
return HttpResponse(json.dumps(datos_response), content_type="application/json")

Upvotes: 0

Related Questions