I am trying to send post data from react to django, however, the data is not attached to the post object. My react code looks something like this:
class Homepage extends React.Component {
createProject() {
axios({
method: "post",
url: "localhost:8000/createProject/,
headers: { "Content-Type": "application/json" },
data: { name: "projectname" },
})
}
render() {
return <div onClick={this.createProject}></div>
}
urls.py
urlpatterns = [
path( "createProject/", views.createProject ),
]
views.py
def createProject( requests ):
print( requests.POST )
return JsonResponse({"this returns": "just fine"})
output from print( requests.POST ) in views.py:
<QueryDict: {}>
If it matters, I'm using csrf_exempt on my django functions as there are no plans of deploying.
Thanks!
Try to print in the view
print(request.get.POST('data'))
Related
I want to post a HTTP request like this:
http://localhost/context/{{name}}/{{age}}
And I want to bind these path variables to request body, if my request body is :
{
"name": "Frank",
"age": 18
}
the final request I want to send is:
http://localhost/context/Frank/18
so how to achieve this function in POSTMAN?
postman request
Provisioning your request in Postman (non-parametric url):
Parametric url
I don't think you need to pass variables in your route, since you're already passing them in the request-body. However, here's a brief.
If you're working with NodeJS (using Express) and any JS library, you can send the request as thus, (using axios):
const body = {
"name": "Frank",
"age": 18
}
const requestHandler = async() => {
const serverResponse = await axios.post(`http://localhost/context/${body.name}/${body.age}`, {data: body}, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${backend-token}`
}
};
Then, on your server-side, with a proper definition for your routes (for parametric and non-paramatric choice of url), you'd create a route to handle the request as:
Using Express
import {Router} from "express";
const yourServerRouter = Router();
yourServerRouter.post(`yourPrimaryDomain/:name/:age`, function-to-handle-request)
If you're working with a python framework (Flask or Django), you can do thus:
Flask (using flask_restful):
urls = [f"your_base_url/name/age"]
from flask_restful import Resource, request
import json
class BioData(Resource):
def post(self):
url = request.url
if "context" in url:
request_body = json.loads(request.data)
response = self.context_handler(request_data)
def context_handler(self, request_data):
name, age = request_data
....
....
flask_app = Flask(__name__)
flask_app.add_resource(BioData, *urls)
Django (Using DRF - viewsets)
from rest_framework import viewsets, routers
class BioDataViewsets(viewsets.ModelViewSets):
#action(methods=["POST"], detail=False, url_name="context", url_path="context")
def context(self, *args, **kwargs):
clients_request = json.loads(self.request.body)
**define your path as above (for flask)**
context_router = routers.DefaultRouter()
context_router.register("name/age/", company_viewsets.CompanyViewSets)
url_patterns = [path(f"your_base_url/context", include(context_router.urls())]
Eventually I got some clues from this page. The request body can be parsed through Pre-request-Script, and the attributes of interest can be set as variables and referenced in URL.
var r = JSON.parse(request.data);
pm.variables.set("name", r.name);
pm.variables.set("age", r.age);
And use below form to apply variables set in the Pre-request-Script:
http://localhost/context/{{name}}/{{age}}
the request body is :
{
"name": "Frank",
"age": 18
}
postman request
Trying to get my model data from django views.py in home.html javascript variable using AJAX.
So far I'm at :
Views.py:
class HomePageView(ListView):
model = Flights
template_name = 'home.html'
def flights_list(request):
flights = serializers.serialize("json", Flights.objects.all())
return JsonResponse({"flights": flights})
Ajax:
function get_data() {
$.ajax({
url: '', //Not sure what to put here.
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
locations = {{ flights }};
}
});
};
$(document).ready(function(){
setInterval(get_data,5000);
});
Every 5 seconds i'm getting alert "Got data!"
But when I'm trying to pass variable location = {{ flights }};
Then locations is empty.
in ajax url:'' i suppose to have my views.py location? as when trying to alert("Got data!" + data) then my whole html is in that data variable..
Am i doing something wrong here?
UPDATE:
My flights urls:
from django.urls import path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'flights', views.FlightViewSet)
urlpatterns = [
path('',views.HomePageView.as_view(),name='home'),
]
Update 2:
Ok so I've found out what's wrong,
Changed urls.py:
urlpatterns = [
path('',views.HomePageView.as_view(),name='home'),
path('flights/', views.flightslist, name='flights')
]
Views.py:
def flightslist(request):
flights = serializers.serialize("json", Flights.objects.all())
return JsonResponse(flights, safe=False)
Had to add safe=False as no other way worked..
Update:
I've managed to sort it out by code:
function get_data() {
$.ajax({
url: 'flights/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
var locations = data;
}
});
};
$(document).ready(function(){
setInterval(get_data,5000);
});
How to convert var locations = data to dictionaries? As now it shows up as :
[{"model": "flightapp.flights", "pk": 390, "fields": and only then dictionary that i need.
I uploaded a program on which a django application is used for file uploading and used the chunk file uploads for it (with the blueimp fileupload on JS side).
When I tested my application locally, it works. When I do it on the IIS production, I always get this error:
POST http://URL/api/chunked_upload/ 500 (Internal Server Error)
The logs in the IIS were not helpful either.
JS Code:
$('#fileUpload').fileupload({
url: window.location.href + 'api/chunked_upload/',
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
type: 'POST',
add: function (e, data) {
form_data.splice(1);
calculate_md5(data.files[0], 100000);
$("#submitButton").off('click').on("click", function () {
showLoading()
data.submit();
});
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
},
done: function (e, data) { // Called when the file has completely uploaded
let formInput;
$.ajax({
type: "POST",
url: window.location.href + 'api/chunked_upload_complete/',
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
inputForm = document.getElementById('ddGraderForm')
document.getElementById('id_formFile').value = data['file']
inputForm.submit()
}
});
},
});
Django urls
urlpatterns = [
path('', views.webinterfaceViews, name='main'),
path('api/chunked_upload_complete/', FastaFileUploadCompleteView.as_view(), name='api_chunked_upload_complete'),
path('api/chunked_upload/', FastaFileUploadView.as_view(), name='api_chunked_upload'),
]
Django view
class FastaFileUploadView(ChunkedUploadView):
model = fileUpload
def check_permissions(self, request):
# Allow non authenticated users to make uploads
pass
class FastaFileUploadCompleteView(ChunkedUploadCompleteView):
model = fileUpload
def check_permissions(self, request):
# Allow non authenticated users to make uploads
pass
def on_completion(self, uploaded_file, request):
# Do something with the uploaded file. E.g.:
# * Store the uploaded file on another model:
# SomeModel.objects.create(user=request.user, file=uploaded_file)
# * Pass it as an argument to a function:
# function_that_process_file(uploaded_file)
pass
def get_response_data(self, chunked_upload, request):
return {'file': chunked_upload.file.name, 'filename': chunked_upload.filename}
The error code I receive is
BytesReceived="0", ErrorCode="Reached the end of the file.
(0x80070026)"
Headers="Content-Type: text/html
Vary: Cookie
Server: Microsoft-IIS/10.0
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
X-Powered-By: ASP.NET
"
I am using Python 3.7.4 with Django 3.0.3 and I have a script Ajax in javascript run in the front end app. When the user click in link, a variable must to be sending to back end python. See the exemple
Javascript
$('.likebutton').click(function() {
var catid;
catid = $(this).attr("data-catid");
$.ajax({
type: "GET",
// url: "/likePost",
url: "/likePost/" + catid,
/* data: {
post_id: catid
},
*/
success: function(data) {
$('#like' + catid).remove();
$('#message').text(data);
}
})
});
urls.py
In the urlpattner of app I have
urlpatterns = [
path('', views.index, name='index'), # index view at /
path('likePost/', views.likePost, name='likepost'), # likepost view at /likepost
]
views.py
def likePost(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.obejcts.get(pk=post_id) #getting the liked posts
m = Like(post=likedpost) # Creating Like Object
m.save() # saving it to store in database
return HttpResponse("Success!") # Sending an success response
else:
return HttpResponse("Request method is not a GET")
In Debug I received the follow message error
Not Found: /likePost
[25/Feb/2020 16:12:17] "GET /likePost?post_id=1 HTTP/1.1" 404 2335
What I am doing wrong?
In your ajax script, you are passing a querystring parameter called post_id (eg. likePost/?post_id=1), but in your urlpatterns, you specify post_id as a path parameter (eg. likePost/1/).
You have 2 options:
post_id as a path parameter
Add the post_id to the url instead of sending it as data:
$('.likebutton').click(function() {
var catid;
catid = $(this).attr("data-catid");
$.ajax({
type: "GET",
// standard syntax
url: "/likePost/" + catid,
// template string syntax
// url: `/likePost/${catid}`,
success: function(data) {
$('#like' + catid).remove();
$('#message').text(data);
}
})
});
Then add post_id to your view:
def likePost(request, post_id):
...
post_id as a querystring
change your path to the following:
path('likePost/', views.likePost, name='likepost')
You can then access post_id via request.GET in your view:
def likePost(request):
post_id = request.GET['post_id']
...
Furthermore, I'd recommend reading When do I use path parameters vs. query params in a RESTful API? if you aren't sure of which option to use.
I am trying to send a form through ajax call to django view as follows:
$.ajax({
type: 'POST',
url: "{% url 'edit_experience' %}",
data: {
item_id : itemId,
form: $("#sample-form").serialize()
},
beforeSend : function() {
},
success: function (data) {
},
error: function(data) {
},
complete : function() {
}
});
I am able to see the data being posted to the http server:
form role=Fresher&organization=TestOrganization&description=Hard+work+pays
item_id 3
My problem is in the server side where I am trying to fetch the data. I am able to access the item_id but I am having a problem accessing the form elements:
In Django View:
def edit_experience(request):
request.POST['form']['role']
return ....
This does not fetch the role. What is the correct way to fetch all the form attributes??
Kindly help. Thanks in advance.
To fetch attributes from the querystring you can use QueryDict:
from django.http import QueryDict
d = QueryDict(request.POST['form'])
role = d['role']