Axios unable to get JSON from Django view - django

I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below.
axios.post("{% url 'main:getCommodityInfo'%}",
param,
{headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
.then(response=>{
console.log(response);
alert("response has been caught");
})
.catch(error=>{
console.log(error);
alert("connection has error")
})
But when I want to return json from view to axios:
def getCommodityInfo(request):
if request.method=="POST":
# get POST parameters
searchKey = request.POST.get('searchKey')
category = request.POST.get('category')
print("Enter the POST view! ", searchKey, category)
# unique ID for each record for DB
uniqueId = str(uuid4())
# spider setting
settings = {
'unique_id': uniqueId,
'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
# taskId to indentify each task
task = scrapyd.schedule('JDSpider', 'getCommodityInfo',
settings=settings, searchKey=searchKey, category=category)
print("It seems everything is running well? ")
return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False)
the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in urls.py.
urlpatterns = [
# eg:127.0.0.1:8000/main/
path('', views.index, name = 'index'),
path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'),
path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'),
# path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'),
]
Because I found that the initial url http://127.0.0.1:8000/main/ in my browser after clicking on the button to post data to getCommodityInfo view became http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics . This url seems not to match any url patterns in urls.py. So I tried to append an additional urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'). Unfortunately, it doesn't work.
After that, I am searching for a long time on net. But no use. Please tell me whether my idea to solve right. Or try to give some ideas how to achieve this.Thanks in advance.
Edit 1 My console logs were asked.
This is my console log after click the button to post data.
And when I click on the alert, the browser go to http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics and the chrome network loading shows like:
And there are no log output in console.
Edit 2 There are some doubts on whether axios send the request by POST or GET, and I try to indentify it in my django view
My python console output this, meaning getCommodityInfo did indentify the request as POST(You could review my code)
Edit 3 #dirkgroten pointed out likely I have sended both POST and GET. So I give the whole code related in my template
And here is my form. And whole js related.
<form action="" id="searchForm">
<label for="searchKey">KeyWords</label>
<input v-model="searchKey" palceholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">
<label for="category">Commodity Category</label>
<select v-model="selected" id="category" name="category">
<option v-for="option in options" v-bind:value="option.value">
${option.text}
</option>
</select>
<button v-on:click="startSpider" class="btn btn-default" >Submit</button>
<p>KeyWords : ${ searchKey }</p>
<p>Category : ${ selected }</p>
</form>
<script type="text/javascript">
var searchApp = new Vue({
delimiters:['${','}'],
el: "#searchForm",
data:{
searchKey:'',
selected:'',
options: [
{text: 'Baby', value:'Baby'},
{text: 'Book', value:'Book'},
{text: 'Electronics', value:'Electronics'},
{text: 'Fashion', value:'Fashion'},
{text: 'Food', value:'Food'},
{text: 'Health&Beauty', value:'Health&Beauty'},
{text: 'Home', value:'Home'},
{text: 'Industrial&Scientific', value:'Industrial&Scientific'},
{text: 'Motor', value:'Motor'},
{text: 'Pet', value:'Pet'},
{text: 'Sports', value:'Sports'},
{text: 'Other', value:'Other'},
]
},
created:function(){
this.selected = "";
},
methods:{
startSpider:function(event){
console.log(this.searchKey);
console.log(this.selected);
alert("spider is ready to run!");
var param = new URLSearchParams();
param.append('searchKey',this.searchKey);
param.append('category',this.selected);
axios.post("{% url 'main:getCommodityInfo'%}",
param,
{headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
.then(response=>{
this.searchKey = "!!!";
this.category = "Baby";
console.log(response.data)
alert("response has been caught");
console.log(response.data)
})
.catch(error=>{
console.log(error);
alert("connection has error")
})
},
getCookie:function(name) {
var value = '; ' + document.cookie
var parts = value.split('; ' + name + '=')
if (parts.length === 2) return parts.pop().split(';').shift()
},
}
});
</script>

Acutally, I have found the mistake. It's all about the <form>... The solution is here

Related

Failing to make a POST request from ReactJS to Django

Hello so I am working on a Django and React project I am fairly new to the domain I can't understand why this is not working, so I would love to make a POST request to my API and save the contents to the database and the after then the function that is currently working to retrieve contents in my DB will do its work to update the website.
So after I made the POST request this is the response I get when I console logged:
Response { type: "cors", url: "http://127.0.0.1:8000/api/upload-lecture/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
I personally thought after getting a status code of 200 everything is fine but when I go check the database the is nothing new that was added.
I even checked the with Django logs that were coming and this is what I got too:
"POST /api/upload-lecture/ HTTP/1.1" 200 108
So I do not understand why the contents are not in the database.
Code to my Api: Upload method:
#api_view(['POST'])
def videoUpload(request):
serializer = LectureVideosSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
Code to React:This is where I was trying to make the POST request
import React, { useState } from 'react';
const VideoUploadForm = () =>{
const [lecturer, setLecturer] = useState('');
const [module, setModule] = useState('');
const [video, setVideo] = useState();
const [date, setDate] = useState('');
const newVideo = () =>{
const uploadData = new FormData();
uploadData.append('lecturer', lecturer);
uploadData.append('module', module);
uploadData.append('video', video);
uploadData.append('date', date);
fetch('http://127.0.0.1:8000/api/upload-lecture/', {
method:'POST',
body:uploadData
}).then(response => console.log(response)).catch(error => console.log(error))
}
const handleLecturer = (e) =>{
setLecturer({
lecturer: e.target.value
})
}
const handleModule = (e) =>{
setModule({
module: e.target.value
})
}
const handleVideo = (e) =>{
setVideo({
video: e.target.files[0]
})
}
const handleDate = (e) =>{
setDate({
date: e.target.value
})
}
return(
<div className="form__container">
<label>
Lecturer:
<input type="text" onChange={handleLecturer} placeholder="Lecturer uploading"/>
</label>
<label>
Module:
<input type="text" onChange={handleModule} placeholder="Module of Video Uploaded"/>
</label>
<label>
Video:
<input type="file" onChange={handleVideo}/>
</label>
<label>
Date:
<input type="text" onChange={handleDate} placeholder="YY-mm-dd"/>
</label>
<button onClick={() => newVideo()}>Upload Video</button>
</div>
)
}
export default VideoUploadForm;
This is the error that I am getting when I print out the serializers errors
[*] Error:{'video': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')], 'date': [ErrorDetail(string='Date has wrong format. Use one of these formats instead: YYYY-MM-DD.', code='invalid')]}
How can I resolve this
For the date make sure you have the format mentioned in the error,for file upload,I usually use MultiPartParser,you can set that up using a parser_classes decorator.

AJax does not seem to work on the delete button

I am really new to ajax. I want to delete the entry from database on button click and I do not want the page to reload. but the ajax doesn't seem to work at all. What is wrong in my code? Please suggest the correct code. Thanks in advance.
<script>
$(document).on('click','#delete',function(){
var a ;
a=confirm("Do you really want to delete the user?");
if(a==true){
var newurl = "{% url 'NewApp:centredelete' pk=1%}"
var id = $(this).attr('name')
$.ajax(
{
type:"GET",
url: "newurl.replace('1',id);",
data:{
delete:True
},
success: function( data )
{
if(data.success == true){
$(id).remove();
}
else{
alert(data.error)
}
}
})}
});
</script>
views.py
def CentreDeleteView(request, pk):
centre = Centre.objects.get(pk=pk)
centre.delete()
return HttpResponseRedirect(reverse('NewApp:centrelist'))
edit:
urls.py
url(r'^centredelete/(?P<pk>\d+)/$',views.CentreDeleteView,name='centredelete'),
I am getting "Not Found: /NewApp/centrelist/url.replace('1',id);
" in the terminal. I don't know why it is taking the wrong url.
Kindly add your url file here and mention here the response on server terminal
replace "newurl.replace('1',id);" with newurl.replace('1',id) in your ajax.
You've used double quotes around newurl.replace('1',id) so the url will send as is instead of replacing '1' with the required id.

401 error while uploading file to Sharepoint 2013 using REST API

I have a simple html form where i have request is built to upload a file to Sharepoint Server 2013 using REST ( taken reference of the Code from the net ) .
Following is the code snippet
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
function AddAttachments()
{
var digest = "";
$.ajax(
{
url: "http://vmjnjlabeling01:22216/as/Shared Documents/_api/contextinfo",
method: "POST",
headers: {
"ACCEPT": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"Authorization" : "Basic c3AyMDEzOlNoYXJlcG9pbnRAMjAxMw=="
},
success: function (data) {
digest = data.d.GetContextWebInformation.FormDigestValue;
},
error: function (data) {
}
}).done(function() {
var fileInput = $('#uploadFile');
var fileName = fileInput[0].files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var fileData = e.target.result;
var res11 = $.ajax(
{
//url: "http://vmjnjlabeling01:22216/as/_api/web/lists/getbytitle('DocTest')/items(1)/AttachmentFiles/ add(FileName='" + fileName + "')",
url:"http://vmjnjlabeling01:22216/as/_api/web/getfolderbyserverrelativeurl('/as/Shared Documents')/Files/add(overwrite=true, url='" + fileName + "')",
method: "POST",
binaryStringRequestBody: true,
data: fileData,
processData: false,
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": digest,
// "content-length": fileData.byteLength
},
success: function (data) {
},
error: function (data) {
alert("Error occured." + data.responseText);
}
});
};
reader.readAsArrayBuffer(fileInput[0].files[0]);
});
}
</script>
</head>
<body>
<div>
<input id="uploadFile" type="file">
</div>
<div>
<input type="submit" onclick="AddAttachments()" value="Add Attachments"> </input>
</div>
</body>
</html>
But when i upload the document i am getting the 401 Error everytime despite all permissions have been given .
Please find the screenshot :
Any help on this topic to resolve this issue is most appreciated.
Regards,
N
You need to enable Basic Authentication credentials are sent in clear text in Authentication Providers.
Goto
Central Admin>> Security>>Security Authentication providers>>
In Right side dropdown select the Application and click on default
Tick Basic Authentication in Claims Authentication Types
Because your page isn't inside SharePoint (you're not getting any "SharePoint" in it), you'll need to authorize differently than if it were a SharePoint page. The easiest answer is probably to look at how the Add-in model works. On the other hand, since there's nothing going on in the page other than your attempt to upload an attachment, could the page be a SharePoint page?

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I have created an API in Django, and some plain files from the desktop for angular and html. I like to fill an angular app with the API output. The request reaches the webserver, but then i get an error.
I get the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
So i need to add "Access-Control-Allow-Origin" = True or something, but where and how? I have read many issues now, tried different things where and how to add, but i cannot figure it out. Can someone please help me with this? Thanx in advance.
views.py
def myjson(request):
data = Dish.objects.all()
#data = {'string':'test', 'twee':'pollo'}
#data = serializers.serialize('json', data)
data = json.dumps( [{'name': o.name, 'description': o.description, 'persons': o.persons} for o in data])
return HttpResponse(json.dumps(data),mimetype="application/json")
script.js
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.dish = {};
//$scope.dish = [{"persons": 4, "name": "Pasta Bolognese", "description": "Pasta met een saus op tomaten basis"}, {"persons": 2, "name": "Pasta Carbonara", "description": "gdsdgfgds"}, {"persons": 4, "name": "Pizzadeeg voor Big Green Egg", "description": "sdgfgfdgfd"}, {"persons": 2, "name": "Low and Slow Ribs", "description": "fdsfsdsfdfsddf"}];
//$scope.dish = '';
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/food/myjson/'
})
.success(function (data) {
// See here, we are now assigning this username
// to our existing model!
$scope.dish = data;
})
.error(function (data, status, headers, config) {
});
}]);
html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.js"></script>
<script src="script.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="UserCtrl">
{{ dish }}
</div>
</div>
</body>
</html>
This is a CORS (cross-origin resource sharing) issue. It happens when you try to hit an endpoint that is on a different domain. So that'd make sense if you have a REST API for your backend.
Your API needs to set headers to allow requests from various sources. We had to allow Access-Control-Allow-Origin to allow localhost for our dev environments. I found that in Angular, with each request, you need to send withCredentials: true as well.
$http({withCredentials: true, method: 'GET', url: http://127.0.0.1:8000/food/myjson/' })
.success(function (data) {
// See here, we are now assigning this username
// to our existing model!
$scope.dish = data;
})
.error(function (data, status, headers, config) {
});
});
Some sources say you also need to set the header on the client side as well for each request. I haven't had to do that though. But it may not hurt to include it:
headers: {'Content-Type': 'application/json; charset=utf-8'}

django-facebookconnect extended permissions

I am wanting to add some extended permissions to django-facebookconnect namely "email". After looking through the code I see that the actual connect is managed in javascript. So, I thought that something like this might work
{% load facebook_tags %}
<script type="text/javascript">
FB_RequireFeatures(["XFBML"], function() {
FB.Facebook.init("{{ facebook_api_key }}", "{% url facebook_xd_receiver %}"{%extended_permissions%});
});
function facebookConnect(loginForm) {
FB.Connect.requireSession();
FB.Facebook.get_sessionState().waitUntilReady(function(){loginForm.submit();});
}
function pushToFacebookFeed(data){
if(data['success']){
var template_data = data['template_data'];
var template_bundle_id = data['template_bundle_id'];
feedTheFacebook(template_data,template_bundle_id,function(){});
} else {
alert(data['errors']);
}
}
function pushToFacebookFeedAndRedirect(data){
if(data['success']){
var template_data = data['template_data'];
var template_bundle_id = data['template_bundle_id'];
feedTheFacebook(template_data,template_bundle_id,function(){window.location.href=template_data['url'];});
} else {
alert(data['errors']);
}
}
function pushToFacebookFeedAndReload(data){
if(data['success']){
var template_data = data['template_data'];
var template_bundle_id = data['template_bundle_id'];
feedTheFacebook(template_data,template_bundle_id,function(){window.location.reload();});
} else {
alert(data['errors']);
}
}
function feedTheFacebook(template_data,template_bundle_id,callback) {
FB.Connect.showFeedDialog(
template_bundle_id,
template_data,
null, null, null,
FB.RequireConnect.promptConnect,
callback
);
}
</script>
here is the extended_permissions tag
#register.simple_tag
def extended_permissions():
if hasattr(settings,'FACEBOOK_EXTENDED_PERMISSIONS'):
return """, {permsToRequestOnConnect: "%s"}""" % ','.join(settings.FACEBOOK_EXTENDED_PERMISSIONS)
return ''
In theory I think the above code should work. Actually it does work it just breaks the popup window functionality. When the user accepts the request from the app they are redirected(within the popup) to the home page. Before the edits the popup would close and the main browser window would be redirected to /facebook/setup.
Any suggestions would be greatly appreciated
I think the problem might be here:
FB.Facebook.init("{{ facebook_api_key }}", "{% url facebook_xd_receiver %}"{%extended_permissions%});
I bet it should be
FB.Facebook.init("{{ facebook_api_key }}", "{% url facebook_xd_receiver %}{%extended_permissions%}");
or possibly even
FB.Facebook.init("{{ facebook_api_key }}", "{% url facebook_xd_receiver %}?perms={%extended_permissions%}");
Not sure, but I never liked the js api anyways. If you're still running into problems, try my Django oauth implementation: https://github.com/dickeytk/django_facebook_oauth