Validating django rest api get request using traditional forms class

Viewed 124

I am trying to validate a DRF get request using django form as follows,

The view of django rest api

@csrf_exempt
@api_view(['GET', 'POST'])
def pkg_list(request):
    if request.method == 'GET':        
        frm=ThisForm(request.GET) 
        if frm.is_valid:
            print("form ok")
            print(frm.cleaned_data)            
        else:
            print("invalid")
        mydata=[{"email": request.GET['reseller']}]     
        results=ResellerListPackages(mydata,many=True).data   
        return Response(results)

The view class is form is as follows,

class ThisForm(forms.Form):
    reseller=forms.EmailField(max_length=255)
    def clean(self):
        self.cleaned_data = super().clean()
        print(self.cleaned_data)            
        return self.cleaned_data

The form validation seems working fine , but the frm.cleaned_data is not found with the following error,

    print(frm.cleaned_data)
AttributeError: 'ThisForm' object has no attribute 'cleaned_data'

Can some one point to me the correct direction. It is the first time using the DRF

1 Answers

Change

frm.is_valid

to

frm.is_valid() 

Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

but in your case, you are not calling the is_valid() method.

Related