1

I wrote a test file to check if the URL works or not and it keeps printing Forbidden (CSRF cookie not set.) could please check what's the problem

#post handler
@csrf_exempt
    def post(self, request, *args, **kwargs):
        valid_json = is_json(request.body)
        if not valid_json:
            error_data = json.dumps({'message': 'Invalid data sent, please send using JSON format'})
            return self.render_to_response(error_data, status=400)
        data = json.loads(request.body)
        form = SupervisorForm(data)
        if form.is_valid():
            obj = form.save(commit=True)
            obj_data = obj.serialize()
            return self.render_to_response(obj_data, status=201)
        if form.errors:
            data_error = json.dumps(form.errors)
            return self.render_to_response(data_error, status=400)
        json_data = json.dumps({'message': 'Not Allowed'})
        status_code = HTTP_400_BAD_REQUEST
        return self.render_to_response(json_data, status_code)


def post():
    data = {
        'supervisor_name':'name',
        'supervisor_phone': '76786875',
        'supervisor_email': 'sdsds@sdsd.com',
        'supervisor_image': 'path to local image',
    }
    json_data = json.dumps(data)
    json_loads = json.loads(json_data)
    print(type(json_data))
    print(type(json_loads))
    print(help(requests.put))
    r = requests.put('http://127.0.0.1:8000/api', json = json.dumps(data))

    return r.json()
Ayman Subbagh
  • 46
  • 1
  • 6

1 Answers1

1

You have probably configured your Django to use a CSRF token but have not set it up for your API. Are you able to disable CSRF in your configuration? Otherwise, you'd have to set it up in accordance with the documentation

CSRF is important for websites that are at a high risk of getting hacked through scripts/iframes. CSRF is what prevents your bank account from sending money to a hacker via email/popup scripts. Unless you're building a website that has confidential data scoped to the user (e.g. Facebook, Venmo, PayPal) CSRF is not necessary.

Moshe
  • 2,583
  • 4
  • 27
  • 70