0

I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it:

export function ProviderRegistration(){
    const[logoField, setLogoField] = useState()
    const token = useSelector((state) => state.user.token)
    const [cookie, setCookie] = useCookies(['auth'])

    const confirm = () => {
        axios.post(`/providers/?username=${cookie.auth.login}`, 
        {
            photo : logoField
        }, 
        { "headers" : { "Authorization" : "token " + token }})
        .then(res => console.log(res))
        .catch(err => console.log(err))
    }

    return(
        <div className="registration-provider-container">
            <div className="registration-title">Provider registration</div>
            <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/>
            <button className="registration-confirm" onClick={() => confirm()}>Confirm</button>
        </div>
)}

And the endpoint processing this request

class Providers(viewsets.ModelViewSet):
    filterset_class = ProvidersFilter
    queryset = Provider.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission]
    def get_serializer_class(self):
        if self.action == 'list':
            return GetProviderSerializer
        else:
            return PutProviderSerializer

    def create(self, request):
        username = request.GET.get('username', '')
        user = User.objects.get(username=username).pk
        request.data.update({'user' : user})
        print(request.data)
        return super().create(request)

When I try to upload an image, django returns the following error:

"The submitted data was not a file. Check the encoding type on the form."

And I haven't found a way to correctly upload an image to django using Ajax. I also output what my browser sends to the server:

{photo : 'C:\\fakepath\\magnit.jpg'}
3
  • Have you installed PIllow? are you able to upload the picture in the Admin? Commented Dec 20, 2022 at 17:31
  • Yes, I had installed pillow and I can add image from Admin panel Commented Dec 20, 2022 at 18:06
  • Can we see your forms and model? Commented Dec 20, 2022 at 21:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.