How to retrieve post data from view of django app - javascript

All I am new to jquery and Django.
I used the following code to post when the button with id 'submit_data' is clicked. Is it possible to retrieve the dictionary { data_key: 'myString'} from the views.py of the Django app?
If yes how?
$(function() {
$('#submit_data').on('click',function() {
$.post('/url/', { data_key: 'myString'}, function(result) {
alert('successfully posted');
});
});
});

For a POST request with form data, you can use request.POST:
def my_view(request):
print(request.POST)
# ...
For a POST request with JSON data, you need to decode request.body:
import json
def my_view(request):
# TODO: missing a suitable `content-type` header check
data = json.loads(request.body.decode())
print(data)
# ...

request.data is used to fetch data from your frontend
it is a dictionary-like object that lets you access submitted data by key name.
Try this:
request.data.get('data_key',None).
To avoid KeyError, you can use .get() which provides value if key found else None is returned.

In template script
$(function() {
$('#submit_data').on('click',function() {
$.post('/url/', { 'data_key': 'myString'}, function(result) {
alert('successfully posted');
});
});
});
in views.py
if request.method == 'POST':
data = request.POST.get('data_key', None)

Related

POST object via Form-Data ( in Django)

Trying to post the data via multipart (form data) in django backend from react js.
let form_data = new FormData();
let doc = [{ "form" : 1, "city": "Bangalore"}, { "form" : 2, "city": "Delhi"}]
form_data.append("CRegNo", "Nectar00001");
form_data.append("CName", "Nectar");
form_data.append("cityName", doc);
form_data.append("userID", 1);
axios.post("http://127.0.0.1:8000/api/table/", form_data, head)
but in Django it interprets the cityName like this ['[object Object]']
Am I doing something wrong ?
You probably should use JSON.stringify on doc as follows
form_data.append("cityName", JSON.stringify(doc));
Afterwards in your django view you need to parse the data
import json
...
city_name = json.loads(request.POST.get('cityName'))
example using class based views
import json
from django.views import View
class MyView(View):
def post(self, request):
city_name = json.loads(request.POST.get('cityName'))
....

In Django, how to render both JSON data with api and info from context dictionary

In Django, I want to render a page that includes a Chart js chart that relies on data from my database. I believe I need to implement an API for this. The same page with the chart will contain other info from the database that I think is rendered with a context dictionary and {{ variable }}. I know how to do one or the the other, but not both on the same page. Here is what I have so far. In views.py:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import generic
from django.views.generic import View
from .models import Article
from rest_framework.views import APIView
from rest_framework.response import Response
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
articles = Article.objects.all()
correlationlist = []
nocorrelationlist = []
for corr in articles:
if corr.correlation_type == "Correlation":
correlationlist.append(1)
nocorrelationlist.append(0)
elif corr.correlation_type == "No Correlation":
correlationlist.append(0)
nocorrelationlist.append(1)
else:
pass
correlation_items = correlationlist
nocorrelation_items = nocorrelationlist
data = {
"correlation_items": correlation_items,
"nocorrelation_items": nocorrelation_items,
}
return Response(data)
The Javascript I have on the page where the chart appears is:
$(document).ready(function(){
var endpoint = 'api/chart/data/'
var defaultData1 = []
var defaultData2 = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
defaultData1 = data.correlation_items
defaultData2 = data.nocorrelation_items
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
CHART js code goes here
}
})
But on the page where the chart appears, I also want to include other information from the data base, such as:
The title of the article is: {{ title }}
To do this and to render the page, I think I need to create a function in views as follows:
def results(request):
myresults = Article.objects.all()
context = {'myresults': myresults}
return render(request, 'my_page_with_results_and_chart.html', context)
In short, how do you render a page that pulls data from an API for a chart, but also gets database information from the render(request, 'page.html', context) method? This is driving me crazy.
not really sure what you're asking, seems very ambiguous. From a glance it looks like, myresults = Article.objects.all() and articles = Article.objects.all() are the same and you just want to get the title from the article?
Just add articles into your data dictionary
data = {
"myresults": articles,
"correlation_items": correlation_items,
"nocorrelation_items": nocorrelation_items,
}
then just reference it in your html. You cant just do {{ title }} though like your example as 'title' is not a key to your dictionary. if 'articles' is a dictionary with title as a key, you'll need to do {{ myresults.title }} in the html. I hope i answered your question :/
I'm not sure if this is what you're asking as it seems too basic but just from your examples it looks like you are..? Anyway if you do need to make an api the Django RESTful library is really good and great documentation http://www.django-rest-framework.org/

Using Fetch API with Rails application?

I am trying to use the Fetch API with my Rails application. I can pass parameters to the controller as part of a query string, but still can't figure out how to pass JSON data or where to find it in the controller. A sample call looks like the below. Where can I access my test data on in the controller? Happy Sunday :)
export const fetchControllerData = () => {
return fetch('api/users',), {
body: { "test": "test" }
})
.then(res => res.json());
};
I'm in the process of working out my own issues with fetch and Rails. But I'll take a stab at this.
I expect that fetch is using GET as the default method - which won't use the body at all. You will likely need to set the method to be POST to get the body through. Further to that you might need to set the Content-Type header (to application/json) in order to send the data through as JSON.
May be u need to send params in this way for get request and use this link for https://github.com/axios/axios
export const fetchControllerData = () => {
params = { body: { "test": "test" } }
return HTTP.get('api/users', params)
.then((response) => {
if (response.success) {
// do something here
} else {
// handle error condtion here
}
});
}

Error when doing ajax with grails and javascript

I have this jquery function on the client side...
$('#add-car').on('click', function() {
$.ajax({
type: 'POST',
url: 'cars/',
data: {brand: 'brand', model: 'model', price: 100,
registryYear:1999},
success: function(data) { console.log(data)},
dataType: 'json'
});
});
And this Grails code in the server side
class UrlMappings {
static mappings = {
"/cars/$id?"(controller: "cars") {
action = [GET:"list", POST:"save", DELETE:"delete", PUT:"edit"]
}
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
import grails.converters.JSON
class CarsController {
def index() {
render ( Car.findAll() as JSON )
}
def save() {
def json = request.JSON
def car = new Car(json)
car.save()
render (json)
}
def delete() {
def car = Car.findById(params.id)
car?.delete()
render (car as JSON)
}
def edit() {
def car = Car.findById(params.id)
bindData(car, request.JSON)
render (car.save() as JSON)
}
}
But when the button #add-car is pressed it returns nothing... What Am I doing wrong?
This is about debugging method.
Please check if the request comes to your server or not. You can do that by adding some logs "Running here" into your requested action at the controller.
If the "Running here" get printed, the request was sent and you must find out how the server doesn't return the expected result.
If the log doesn't get printed, it means you must re-check your javascript. Using Firebug may help in uncovering some tricky javascript bugs.
By the way, I think you should use "jQuery" instead of "$" sign in your javascript. That is for avoiding conflicts with other libraries, such as:
jQuery('#add-car').click(function() {
....
});
well i dont code in grails
but your closest url mapping appears to be this "/cars/$id?"
which im assuming requires an ID
but from your javascript code you are not sending back any variable named Id

How to send data to controller by using YAHOO connect and json

I can not send data to MVC controller using YAHOO connect library.
Parameters query and filter are NULL. Where is the problem?
// --- JavaScript --- //
var callbacks = {
// Successful XHR response handler
success: function (o) {
var messages = [];
// Use the JSON Utility to parse the data returned from the server
try {
messages = YAHOO.lang.JSON.parse(o.responseText);
}
catch (x) {
alert("JSON Parse failed!");
return;
}
handleSearchResult(messages, query, filter);
},
argument: { query: "flowers", filter: "home" }
};
// Make the call to the server for JSON data
YAHOO.util.Connect.asyncRequest("GET", "Search/GetTopics", callbacks);
// --- C# --- //
//Controller
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTopics(string query, string filter)
{
// query and filter are NULL <- problem here //
// ...do my stuff... //
return Json(Search(query, filter), JsonRequestBehavior.AllowGet);
}
Thank you! :)
You have to possibilities to send parameters:
Use GET verb: In this case you need to pass the parameters in the querystring:
YAHOO.util.Connect.asyncRequest('GET',
'Search/GetTopics?query=foo&filter=bar', callbacks);
Use POST verb: In this case you could use the postData parameter
YAHOO.util.Connect.asyncRequest('POST', 'Search/GetTopics',
callbacks, 'query=foo&filter=bar');
In the first case it is actually recommended to use Url helpers to generate the address to make sure values are properly url encoded:
var url = '<%= Url.Action("GetTopics", "Search", new { query = "foo", filter = "bar" }) %>';
YAHOO.util.Connect.asyncRequest('GET', url, callbacks);
The same is true for the second case. Make sure to properly encode values.

Categories