0
votes

I'm following django-editorjs(django package) tutorial of https://medium.com/analytics-vidhya/integrating-editorjs-with-django-7a30127d0771. Whenever I try to upload image, I get this csrf error: Forbidden (CSRF token missing or incorrect.): /media/imageUpload/ I set up media root and url and I am able to view a sample image it from 'http://127.0.0.1:8000/media/imageUpload/example.jpg' and it seems it is working for media. However, this tutorial involves image upload with @exempt_csrf and @requires_csrf_token and it looks like it is causing csrf issue. I tried workarounds(ex: https://github.com/editor-js/image/issues/45), adding additionalRequestHeaders with csrf token but it keeps showing the same error.

Here is my code:

#urls.py(app)

from django.urls import path, include
from .views import upload_image_view
from django.views.decorators.csrf import csrf_exempt, csrf_protect

urlpatterns = [
    path('imageUpload/', csrf_exempt(upload_image_view)),
]

#urls.py (project)

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('post/', include('post.urls'), name='post'),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#views.py (functon part)

from django.shortcuts import render, get_object_or_404, reverse, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie, requires_csrf_token, csrf_exempt
from django.core.files.storage import FileSystemStorage

@requires_csrf_token
def upload_image_view(request):
    f=request.FILES['image']
    fs = FileSystemStorage()
    filename = str(f).split('.')[0]
    file = fs.save(filename, f)
    fileurl = fs.url(file)
    
    return JsonResponse({'success' :1, 'file': {'url': fileurl }})

#models.py

class Post(models.Model):
    title = models.CharField(max_length=200)
    desc = EditorJsField(
        editorjs_config={
            "tools": {
                "Table": {
                    "disabled": False,
                    "inlineToolbar": True,
                    "config": {"rows": 2, "cols": 3,},
                },
                "Image": {
                    "config" : {
                        "endpoints": {
                            "byFile" : 'http://127.0.0.1:8000/media/imageUpload/',
                            "byUrl": 'http://localhost:8000/media/imageUpload/',
                        },
                        "additionalRequestHeaders":[{"Content-Type":'multipart/form-data', "X-CSRF-TOKEN": "{{csrf_token}}" }] #setting it as token(like example from github) won't work because it shows error that it is not defined. I don't know how to call from models.py any idea?
                    }
                }
            }
        }
    )

I tried other variations on x-csrf-token like call token and use 'const csrftoken = getCookie('csrftoken');' in javascript and etc but I am keep trying to figure out.

Any ideas?

1

1 Answers

0
votes

So turns out revising endpoint solved the problem. Previously I used full url of media folder like 'http://127.0.0.1:8000/media/imageUpload/'. This gave me Forbidden csrf error. I've also tried using '/imageUpload/' but it gave me 'not found' error. Because there is a main project and post app is followed, i had to specify the route like this : '/post/imageUpload/'