django csrf issue with uploading image through Editor.js - django

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?

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/'

Related

Django DRF APITestCase post url results in 404 error

I'm learning DRF test cases, and in my test.py file, my URL in the client post-call is coming back in a 400 status error:
Here's my urls.py:
from django.contrib import admin
from django.urls import path, include
#from rest_auth.views import LoginView, LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path("api/", include("profiles.api.urls")),
path("api-auth/", include("rest_framework.urls")),
path("api/rest-auth/", include("rest_auth.urls")),
path("api/rest-auth/registration/", include("rest_auth.registration.urls"))
]
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here's my test.py file
import json
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from rest_framework import status
from profiles.models import Profile
from profiles.api.serializers import ProfileSerializer
class RegistrationTestCase(APITestCase):
def test_registration(self):
data = {"username": "testuser1", "email": "test#localhost.app", "password1": "A41&14all", "password2": "A41#14all"}
response = self.client.post("/api/rest-auth/registration/", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
It appears that the line self.client.post.... fails to find the endpoint.
What am I missing?
thanks!

Page Not Found 404 Django & Python

I am having the following error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in Decoder.urls, Django tried these URL patterns, in this order:
form.html [name='form1']
hl7 [name='hl7']
The empty path didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Its my first time writing code using Django
`from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('hl7rest.urls')),
]`
and this other file
from . import views
from django.urls import path
urlpatterns = [
path('form.html', views.render_form_View, name='form1'),
path('hl7', views.hl7_web_view ,name='hl7'),
]
Your paths don' t match the request.
You can create a TemplateView subclass for render your template:
Views
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = "display_form.html"
Url patterns
urlpatterns = [
path('', HomePageView.as_view(), name='home')
]

Django -Page not found (404) Request Method: GET Method

I am very new to Django ,I am trying to run a URL ,however I get this error of page not found.I went through almost 90% of the posts here but nothing worked for me.
Here are three .py files
views.py.....
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello world....')
**products\urls.py****
from django.urls import path
from . import views #.means current folder ,we are importing a module
urlpatterns=[
path(' ', views.index),
]
pyshop\urls.py.......
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('products/',include('products.urls'))
]
Error I get.....
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products/
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:
admin/
products/
The current path, products/, didn't match any of these.
I think you have to delete the space on the path :
urlpatterns=[
path(' ', views.index),
]
Like :
urlpatterns=[
path('', views.index),
]

How to resolve an error 404 for django-social?

I want to be able to login through social media. Followed all the steps (registered app), the login works just fine but does not go through because django does not recognize my url.
This is my call to the api endpoint
facebookLogin(token: string):any{
return this.http.post(environment.api + 'fblogin/', {token:this.token}).subscribe(
(onSucess:any) => {
localStorage.setItem(this._tokenKey, onSucess.token)
}, onFail => {
console.log(onFail)
}
);
}
But I get the following error : POST http://127.0.0.1:8000/api/fblogin/ 404 (Not Found). From this I know there to be something wrong with my django urls. And indeed going to http://127.0.0.1:8000/api/fblogin/ gave me a page not found error and that it tried to match several other urls.
However I can't see what is wrong with my urls
URLS in my app
from django.conf.urls import url, include
from rest_framework import routers
from . import views
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from social_django import urls
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'fblogin/', include(urls)),
url(r'auth/', obtain_jwt_token),
url(r'refresh/', refresh_jwt_token)
]
URLS in my project
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('Backend.api.urls'))
]
Other URLS like http://127.0.0.1:8000/api/users/ do work. I also am under the impression that all of my settings are in order.
I suggest that I might be because of the order and way in which you have defined URLs.py try the below format
from django.conf.urls import url, include
from rest_framework import routers
from . import views
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from social_django import urls
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^fblogin/', include(urls)),
url(r'^auth/', obtain_jwt_token),
url(r'^refresh/', refresh_jwt_token)
] + router.urls

Django Name Error

I have the following code in my urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
url(r'^testModule/',include(testModule.urls)),
url(r'^admin/', admin.site.urls),
]
and testModule is my app name which includes :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name='index'),
]
And my views.py is
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
# Create your views here.
However, i get the following error while running the server:
line 20: url(r'^testModule/',include(testModule.urls)),
NameError: name 'testModule' is not defined
You haven't imported testModule in your main urls.
Had the same problem but solved it like this:
add "import testModule" to your urls.py
add "from django.conf.urls import url" to your urls.py in the app directory, in this case testModule
Once done you will get a "Page not found at/" error when you reload 127.0.0.1:8000. This is bacause the url to your app is actually at 127.0.0.1:8000/testModule