Problem with AJAX calls in Django app while developing google chrome extension - python

When I am trying to send data to my localhost using the ajax call in popup.js, I am getting an error :
Not Found: /sentiment/
"GET /sentiment/?number=219 HTTP/1.1" 404 1714
Even though I checked the url and it is correct and exists.
This is the snippet of my ajax call:
$.ajax({
url:"http://127.0.0.1:8000/sentiment/",
dataType:"json",
data:{
number:newTotal
},
crossDomain:true,
success:function(json)
{
$('#total').text(json.number)
}
})
and this is my urls.py file in django app :
from django.contrib import admin
from django.urls import path,include
from DetectHate import views
from django.urls import path,re_path
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^sentiment/$', views.sentiment,name="sentiment"),
]
and this is my views.py file -
import json
from django.http import Http404,HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def sentiment(request):
if request.is_ajax():
var=request.POST.get('number')+5
data={}
data['number']=var+5
return HttpResponse(json.dumps(data),content_type='application/json')
else:
raise Http404

Related

How to add React JS's Link paths to DJango URLs backend

I have a project that has React as it's frontend & Django as it's backend. after i integrated React with django it works perfectly but the paths i created in React with react-router-dom doesn't load when i search the page on my browser. meaning, i can load http://127.0.0.1:8000 comfortably but if i try to search http://127.0.0.1:8000/rooms/1/UCL a path that i created with React-router-dom using it's Link, it throws an error calling Page not found
how can i fix this ?
#my URL.py
from re import template
from xml.etree.ElementInclude import include
from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include('api.urls')),
path('',TemplateView.as_view(template_name='index.html')),
]
my views.py
import profile
from rest_framework.response import Response
from django.http import HttpResponse
from rest_framework.decorators import api_view
from app.models import *
from .serializers import *
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
#api_view(['GET','PUT'])
def updateRoomData(request,pk):
try:
message = Message.objects.get(id=pk)
except message.DoesNotExist:
return HttpResponse(status=404)
if request.method=='GET':
serializer = messageSerializer(message)
if request.method == 'PUT':
serializer = messageSerializer(message, data=request.data)
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status=400)
return Response(serializer.data)

django returning or posting wrong template html?

I developed a django project named "dms" and an app which name is "add_excel" last month. The app receieves excel files from web page and store the data into mysql database. Today I added another two apps, "add_struc" and "homepage", which should be another function app and the homepage app. But something odd shows up. After I clicked the "upload" button in "add_excel" app, instead of it's original functions, it redirects to "homepage" without doing anything to the database.
The VS Code shows:
[18/Apr/2019 11:08:00] "GET / HTTP/1.1" 200 317 # I opened the
homepage
[18/Apr/2019 11:08:02] "GET /addexcel/index/ HTTP/1.1" 200 1341 # I clicked to the "add_excel" app hyperlink
[18/Apr/2019 11:08:20] "POST /homepage/index/ HTTP/1.1" 200 317 #
I clicked "upload" but it redirected me to homepage again.
If I delete the homepage url in the urls.py for the whole project, and click the upload button again, it says:
Page not found (404) Request Method: POST Request
URL: http://127.0.0.1:8000/homepage/index/ Using the URLconf defined
in dms.urls, Django tried these URL patterns, in this order:
^admin/ ^$ [name='index'] ^addexcel/ ^addstruc/ The current path,
homepage/index/, didn't match any of these.
The urls.py in dms project:
from django.contrib import admin
from django.conf.urls import url, include
from homepage.views import index # default homepage
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index, name='index'), # homepage
url(r'^addexcel/', include('add_excel.urls')),
url(r'^addstruc/', include('add_struc.urls')),
]
urls.py in add_excel app:
from django.conf.urls import url
from django.urls import path
from django.contrib import admin
from add_excel.views import IndexView
urlpatterns = [
url(r'index/', IndexView.as_view(), name ='index'),
]
urls.py in add_struc app:
from django.conf.urls import url
from django.urls import path
from django.contrib import admin
from add_struc.views import IndexView
urlpatterns = [
url(r'index/', IndexView.as_view(), name ='index'),
]
urls.py in homepage app:
from django.conf.urls import url
from django.urls import path
from django.contrib import admin
from homepage.views import index
urlpatterns = [
url(r'index/', index, name='index'),
]
views.py in add_excel app:
# -*- coding:utf-8 -*-
import os
import os.path
import sys
import datetime
from builtins import int
from django.db import models
from django.shortcuts import render
from django.views import View
import pymysql
import xlrd
from xlrd import xldate_as_tuple
# Create your views here.
class IndexView(View):
template_name = 'add_excel/index.html'
context={}
def get(self, request):
return render(request, 'add_excel/index.html', {})
def post(self, request):
# if request.method == 'POST' and 'excel_file' in request.POST:
if request.method == 'POST' and request.FILES["excel_file"]:
# do something
return render(request, 'add_excel/index.html', {"excel_data":excel_data})
You are using the name index in all of your url patterns which is causing a conflict. These should be properly namespaced (homepage-index, excel-index etc.) so when you refer to them throughout your application it is obvious to both developers and the program which URL should be chosen.
My theory is that there is some URL generation in your HTML Form that uses the name index and your Django site chooses the homepage for the URL so your IndexView is not run.

The custom page 404 is not showing but the page 500 is showing

When I load an inexistent url the page 404 does not show instead the page 500 is shown. Below my setups. Could you please guide me to turn Django on to show 404 page? Thanks
Ubuntu Server 16.04 ; Python 3.5.2 ; Django 2.0
cat contatoproj/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.conf.urls import include
from django.conf.urls import handler404, handler500
from contatoapp import views
from contatoapp import views as myapp_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^contato', views.contato, name='contato'),
]
handler404 = myapp_views.error_404
handler500 = myapp_views.error_500
cat contatoapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib import messages
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from contatoapp.forms import ContatoForm
def error_404(request):
data = {}
return render(request, 'ops404.html', data)
def error_500(request):
data = {}
return render(request, 'ops500.html', data)
$ ls -la templates/ops*
-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:31 templates/ops404.html
-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:29 templates/ops500.html
cat contatoproj/settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
If you're getting a 500 error for missing pages then it's because there is an error happening when Django tries to handle that response.
From looking at your code, this is probably because your 404 error handler is wrongly defined - it needs to accept a second exception argument which is missing. Change it to:
def error_404(request, exception):
data = {}
return render(request, 'ops404.html', data)
Also note that you should be returning a HttpResponseNotFound, otherwise the client will not receive a HTTP 404 response.
You're getting an error in the process of handling the 404. This means you're getting a 500 instead.
As you're not doing anything special in your 500 or 404 views, you don't need to explicitly define the handler views for them using handler404/500.
Instead, you should define 404.html and 500.html in your templates directory. Django will use these instead of the default templates, and you don't need to re-implement the 404 and 500 views correctly.

Django View Error - NoReverseMatch

I am new to django and I am trying to solve a NoReverseMatch issue. I think it has something to do with the views but i'm new to this.
The code is from a popular boiler plate repo from a few years ago. PLEASE NOTE: I tried reading like every answer on stack overflow already and have been stuck for hours.
Any help would be greatly appreciated
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^login/', include('shopify_app.urls')),
url(r'^', include('home.urls'), name='root_path'),
url(r'^admin/', admin.site.urls),
]
urls.py inside of app
from django.conf.urls import url
from shopify_app import views
urlpatterns = [
url(r'^$', views.login, name='shopify_app_login'),
url(r'^authenticate/$', views.authenticate, name='shopify_app_authenticate'),
url(r'^finalize/$', views.finalize, name='shopify_app_finalize'),
url(r'^logout/$', views.logout, name='shopify_app_logout'),
]
views.py inside of app
from django.shortcuts import redirect, render
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.conf import settings
import shopify
def authenticate(request):
shop = request.GET.get('shop')
print('shop:', shop)
if shop:
scope = settings.SHOPIFY_API_SCOPE
redirect_uri = request.build_absolute_uri(reverse('shopify_app.views.finalize'))
permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri)
return redirect(permission_url)
return redirect(_return_address(request))
def finalize(request):
shop_url = request.GET['shop']
try:
shopify_session = shopify.Session(shop_url)
request.session['shopify'] = {
"shop_url": shop_url,
"access_token": shopify_session.request_token(request.REQUEST)
}
except Exception:
messages.error(request, "Could not log in to Shopify store.")
return redirect(reverse('shopify_app.views.login'))
messages.info(request, "Logged in to shopify store.")
response = redirect(_return_address(request))
request.session.pop('return_to', None)
return response
Error
NoReverseMatch at /login/authenticate/
Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://localhost:8000/login/authenticate/?csrfmiddlewaretoken=zEwwHeTfxK7apbAp3dSxsehsafxqjSgEM4t&shop=piepiedev.myshopify.com&commit=Install
Django Version: 1.11.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.
Source code / file structure-
https://github.com/Shopify/shopify_django_app
Similar issue but not working solution-
https://github.com/Shopify/shopify_django_app/issues/13
Change inside authenticate(request):
redirect_uri = request.build_absolute_uri(reverse('shopify_app:shopify_app_finalize'))

Is a position of adding #csrf_exempt wrong?

I wanna connect my Swift app & Python Django Server in sending Image(I wanna send images from Swift app to Server) When I tried to do it,I got an error in Xcode
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre>
CSRF cookie not set.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href="https://docs.djangoproject.com/en/1.10/ref/csrf/">Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function passes a <code>request</code> to the template's <code>render</code>
method.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
<li>The form has a valid CSRF token. After logging in in another browser
tab or hitting the back button after a login, you may need to reload the
page with the form, because the token is rotated after a login.</li>
</ul>
<p>You're seeing the help section of this page because you have <code>DEBUG =
True</code> in your Django settings file. Change that to <code>False</code>,
and only the initial error message will be displayed. </p>
<p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>
</body>
</html>
So,I think adding csrf decorators to Django Server is needed. I added it to my codes like
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST
from .forms import RegisterForm
from django.contrib.auth import authenticate, login
from .models import Post
from .forms import UserImageForm
from .models import ImageAndUser
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def upload_save(request):
photo_id = request.POST.get("p_id", "")
if (photo_id):
photo_obj = Post.objects.get(id=photo_id)
else:
photo_obj = Post()
files = request.FILES.getlist("files[]")
photo_obj.image = files[0]
# photo_obj.image2 = files[1]
# photo_obj.image3 = files[2]
photo_obj.save()
# return render(request, "registration/accounts/photo.html")
photos = Post.objects.all()
context = {
'photos': photos,
}
return render(request, 'registration/accounts/photo.html', context)
But when I did same thing in Swift app,totally same error happened.
I think the position of adding #csrf_exempt is wrong,but I do not know how to fix this.And maybe the position of #csrf_exempt is ok,another point is wrong,I do not know.
My sending url is written in Swift is http://localhost:8000/admin/accounts/post/42/change/ .
In Django side,MyAPP's urls.py is
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^api/', include('UserToken.urls')),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^ResultJSON/', include('ResultJSON.urls')),
url(r'^api/1.0/', include('accounts.api_urls', namespace='api')),
url(r'^api/1.0/login/', include('accounts.apitoken_urls', namespace='apilogin')),
] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
accounts's urls.py is
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
from django.views.generic import TemplateView
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
url(r'^kenshinresults$', TemplateView.as_view(template_name='registration/accounts/kenshin_result.html'),
name='kenshinresults'),
url(r'^tcresults$', views.tc,name='tcresults'),
]
Please tell me what is wrong.
/admin/accounts/post/42/change/ is a URL in the Django admin. Your upload_save view which uses the csrf_exempt decorator is hooked up to /accounts/upload_save/ in your URL config.

Categories