我正在使用Django运行网站。这是views.py:
def signup(request):
registered=False
failed_ref=False
wrong_ref=False
if request.method=='POST':
if 'city' in request.POST:
user_form = UserForm(data=request.POST)
profile_form = ProfileForm(data=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)
else:
profile_form=ProfileForm()
return JsonResponse({'profile_form':profile_form,'registered':registered,
'failed_ref':failed_ref,'wrong_ref':wrong_ref},safe=False)
当我尝试获得Json Response时,我正在获得
ProfileForm类型的对象不是JSON可序列化的
我的ProfileForm()
:
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')
如何为此获取JSON响应?
答案 0 :(得分:1)
您需要序列化数据。
来自django.core导入序列化器
data = serializers.serialize('xml', Profile.objects.all(), fields=('first_name','last_name','mobile_no','email','address_line_1','address_line_2','postal_code','city','country','image','referral_contact','promo_coupon','ic'))
答案 1 :(得分:0)
Form类不是JSON可序列化的,您应该改用cleaned_data
def signup(request):
registered = False
failed_ref = False
wrong_ref = False
if request.method == 'POST':
if 'city' in request.POST:
user_form = UserForm(data=request.POST)
profile_form = ProfileForm(data=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
# use cleaned_data
profile_form.cleaned_data['user'] = user_form.cleaned_data
else:
print(user_form.errors, profile_form.errors)
else:
profile_form = ProfileForm()
return JsonResponse(
{
'profile_form': profile_form.cleaned_data,
'registered': registered,
'failed_ref': failed_ref,
'wrong_ref': wrong_ref
},
safe=False)