【问题标题】:How to make Django Forms JSON serializable如何使 Django Forms JSON 可序列化
【发布时间】:2020-04-22 14:20:58
【问题描述】:

我正在使用 Django 框架运行一个网站。下面是代码。

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})

我想得到 JSON 格式的响应。我得到的错误是"TypeError: Object of type ProfileForm is not JSON serializable". 谁能帮忙弄清楚为什么会这样?

【问题讨论】:

标签: python json django


【解决方案1】:

尝试替换这个:

return JsonResponse({'profile_form':profile_form,

用这个:

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

这会让你继续使用你现在拥有的东西。 但是,我建议您在生产环境中运行此代码。

你应该看看序列化你的响应对象。详情请见https://www.django-rest-framework.org/

【讨论】:

  • 嘿,把它修好了。但现在我收到错误消息“mappingproxy 类型的对象不是 JSON 可序列化的”。
【解决方案2】:

使用json python库:

import json

#your code

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2011-04-15
    • 2020-07-18
    • 2019-06-06
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多