Serialized Data Displaying Letter by Letter Django - python

I'm learning to work with JSON and so I'm running a simple example to create a list item in my template for each object in my django model. My output looks like this:
So I wanted each <li> to show just the actual value in Name. How can I amend my code to achieve that?
views.py
def Ajax(request):
if request.is_ajax():
exporter = serializers.serialize("json", Proforma.objects.all())
print(exporter)
data = json.dumps(exporter)
return HttpResponse(data, content_type='application/json')
$("#populate").click(function() {
$.ajax({
url: "/ajax/more",
success: function(data) {
for(i = 0; i < data.length; i++){
$('ul').append('<li>'+data[i]+'</li>');
}
}
});
});
EDIT:
Here is the output from the console:
(index):739 [{"model": "Poseidon.proforma", "pk": 24, "fields": {"Name": "greg", "Shipment": 4, "Exporter": "greg", "QuoteNo": "jiojo", "Date": "ijoi", "Consignee": 10, "MethodOfDispatch": "ujhiuh", "TypeOfShipment": "iuhiu", "PortOfLoading": "huyg", "PortOfDischarge": "uioj", "Terms": "iugh", "ProductCode": "utyg", "DescriptionOfGoods": "iuhi", "UnitQty": "ug", "UnitType": "t", "Price": "iuh", "Amount": "iy", "BankDetails": "guyt", "AdditionalInfo": "gy", "InvoiceTotal": "tf", "Place": "uyg", "SignatoryCompanyBuyer": "uyf", "SignatoryCompany": "utfy", "NameSignerBuyer": "guyg", "NameSigner": "uy", "SignatureBuyer": "fy", "Signature": "trf", "CreatedBy": "uyg"}}]

the problem is the ajax because you cant print a whole object in the li tag:
try this(would print "Poseidon.proforma" on the li tag):
$("#populate").click(function() {
$.ajax({
url: "/ajax/more",
success: function(data) {
var data = JSON.parse(data); // parse the string response to JSON
for(i = 0; i < data.length; i++){
$('ul').append('<li>'+data[i]["model"]+'</li>');
}
}
});
});
if you want a to understand the problem i think w3schools may help

Related

JSONDecodeError in Django after Paypal payment

I keep getting the below error when I complete payment via Paypal in development:
JSONDecodeError at /checkout/thankyou
Expecting value: line 1 column 1 (char 0)
I have looked around and I can see that there is some issue with the format of the JSON, and my view can't process it. I can't figure out what the issue with my data is exactly, however. I want to use my Json data to create an order on my Django model once it has pulled through, however I can't get to that stage yet.
checkout.html script:
let bagContents = '{{ bag_products|safe }}';
const csrftoken = getCookie('csrftoken');
const paymentAmount = '{{ total | safe }}';
// Parse bagContents, then for each create a variable for name, id and quantity
let bag = JSON.parse(bagContents);
for (let i = 0; i < bag.length; i++) {
let itemName = bag[i].name;
let itemId = bag[i].id;
let itemQuantity = bag[i].quantity;
console.log(itemName);
console.log(itemId);
console.log(itemQuantity);
}
function completeOrder(){
let url = '{{ success_url }}'
fetch(url, {
method: 'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken': csrftoken,
},
body:JSON.stringify({'bagContents': 'bagContents'})
})
}
paypal.Buttons({
// Sets up the transaction when a payment button is clicked
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [{
amount: {
value: paymentAmount
}
}]
});
},
// Finalize the transaction after payer approval
onApprove: (data, actions) => {
return actions.order.capture().then(function (orderData) {
// Successful capture! For dev/demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
const transaction = orderData.purchase_units[0].payments.captures[0];
completeOrder()
actions.redirect("{{ success_url }}");
// When ready to go live, remove the alert and show a success message within this page. For example:
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
{% endblock %}
Views.py:
def order_success(request):
"""
View that displays the successful order page after an order has been
processed.
"""
print(request.body)
body = json.loads(request.body)
print('BODY:', body)
return JsonResponse('Success!', safe=False)
Print Statements:
b'{"bagContents":"[{\\"name\\": \\"Teddy Bear\\", \\"id\\": 2, \\"quantity\\": 3}, {\\"name\\": \\"Bath Toys\\", \\"id\\": 1, \\"quantity\\": 1}, {\\"name\\": \\"Chew Toy\\", \\"id\\": 4, \\"quantity\\": 2}]"}'
b''
BODY: {'bagContents': '[{"name": "Teddy Bear", "id": 2, "quantity": 3}, {"name": "Bath Toys", "id": 1, "quantity": 1}, {"name": "Chew Toy", "id": 4, "quantity": 2}]'}
Any help would be greatly appreciated!

How to get th content of a string inside a request response?

I was coding a webapp based on GPT-2 but it was not good so I decided to switch to official OpenAI GPT-3.
So I make that request:
response = openai.Completion.create(
engine="davinci",
prompt="Hello",
temperature=0.7,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
And when I print the response I get this:
{
"choices": [
{
"finish_reason": "length",
"index": 0,
"logprobs": null,
"text": ", everyone, and welcome to the first installment of the new opening"
}
],
"created": 1624033807,
"id": "cmpl-3CBfb8yZAFEUIVXfZO90m77dgd9V4",
"model": "davinci:2020-05-03",
"object": "text_completion"
}
But I only want to print the text, so how can I do to print the "text" value in the response list.
Thank you in advance and have a good day.
Using the dict indexing by key, and the list indexing by index
x = {"choices": [{"finish_reason": "length",
"text": ", everyone, and welcome to the first installment of the new opening"}], }
text = x['choices'][0]['text']
print(text) # , everyone, and welcome to the first installment of the new opening
You can try print(response["choices"][0]["text"])
Hope this helps.
I think GPT-3 response structure has been changed, for reference, the response object looks this:
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Say this is a test",
temperature: 0,
max_tokens: 6,
});
// the response looks like the following
{
status: 200,
statusText: 'OK',
headers: {
},
config: {
},
request: <ref *1> ClientRequest {
},
data: {
id: 'cmpl-5zzyzqvh4Hmi5yyNL2LMI9ADkLBU0',
object: 'text_completion',
created: 1665457953,
model: 'text-davinci-002',
choices: [ [Object] ],
usage: { prompt_tokens: 5, completion_tokens: 6, total_tokens: 11 }
}
}
// choices can be accessed like this
var { choices } = { ...response.data }

DataTable (JQuery): how to switch language with browser language?

I use DataTable in my Django project and currently doing internationalisation of my apps
I would like DataTable change with browser language as for my templates.
I have found the way to change language with DataTable option
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
is their a simple way doing it?
or should I test for browser language and have a switch to initialize var table?
something like that (pseudocode):
if browser.lang == 'english'{
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
});
}
else {
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
}```
Try to make a comparision between:
var lang = navigator.languages && navigator.languages[0] ||
navigator.language || navigator.userLanguage;
Var language is different on current browsers
thanks to Synapsido that show me the way...
below the code I use
<script>
$(document).ready( function () {
if(window.navigator.language == 'fr-FR'){
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
} else {
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
});
}

react-table not rendering server-side data in table (with manual pagination, filtering & sorting)

I'm having trouble getting data from the backend (Python API) to show in react-table manually. I've read the documentation and I'm trying to use the example here: https://react-table.js.org/#/story/server-side-data
I'm only seeing data in one column and only for 6 records which is really weird. It's probably the way I'm mixing in async/await syntax with the example code which uses a promise. I was able to create a simple react-table fetching data with the same async/await syntax, but when I added the server-side data code from the example (the requestData function) it wouldn't work.
I've spent days on this and looking all over Stackoverflow and the internet. I'm a newbie so please go easy on me. Here's what I have:
import React from 'react'
import { render } from 'react-dom'
import ReactTable from 'react-table'
import api from 'src/api'
import { orderBy } from 'lodash'
// importing react-table css would not work so I added it using cdn link
const requestData = async (pageSize, page, sorted, filtered) => {
// api is a wrapper for axios.create()
const rawData = await api.admin.exercise.feed()
return new Promise((resolve, reject) => {
let filteredData = rawData;
if (filtered.length) {
filteredData = filtered.reduce((filteredSoFar, nextFilter) => {
return filteredSoFar.filter(row => {
return (row[nextFilter.id] + "").includes(nextFilter.value);
});
}, filteredData);
}
const sortedData = orderBy(
filteredData,
sorted.map(sort => {
return row => {
if (row[sort.id] === null || row[sort.id] === undefined) {
return -Infinity;
}
return typeof row[sort.id] === "string"
? row[sort.id].toLowerCase()
: row[sort.id];
};
}),
sorted.map(d => (d.desc ? "desc" : "asc"))
);
const res = {
rows: sortedData.slice(pageSize * page, pageSize * page + pageSize),
pages: Math.ceil(filteredData.length / pageSize)
};
resolve(res);
});
};
export class ExerciseList extends React.Component {
constructor() {
super();
this.state = {
data: [],
pages: null,
loading: true
};
this.fetchData = this.fetchData.bind(this);
}
setLoading(loading) {
this.setState({ loading })
}
fetchData(state, instance) {
this.setLoading(true);
requestData(
state.pageSize,
state.page,
state.sorted,
state.filtered
).then(res => {
this.setState({
data: res.rows,
pages: res.pages,
loading: false
});
});
}
render() {
const { data, pages, loading } = this.state;
return (
<div>
<ReactTable
columns={[
{
Header: "Name",
accessor: "name"
},
{
Header: "Movement",
accessor: "movement"
},
{
Header: "Equipment",
accessor: "equipments"
},
{
Header: "Channel",
accessor: "channel"
},
{
Header: "Level",
accessor: "skill_level"
},
{
Header: "Duration",
accessor: "duration",
filterable: false
},
{
Header: "Injuries",
accessor: "injuries"
},
{
Header: "Is Substitute",
accessor: "has_video",
Cell: ({ value }) => (value? 'Yes': 'No'),
filterable: false
}
]}
data={data}
pages={pages}
loading={loading}
onFetchData={this.fetchData}
manual
filterable
defaultPageSize={10}
className="-striped -highlight"
/>
</div>
);
}
}
render(<ExerciseList />, document.getElementById('datatable'));
Please refer the link for server-side sorting, pagination and manual filtering within the grid
// Component related to methods for sorting, pagination server side and filtering manual filtering with in the grid
import React from 'react'
import 'react-table/react-table.css'
import ReactTable from 'react-table'
import autoBind from 'react-autobind'
import {filterCaseInsensitive} from '../../helper/commonMethods'
class ServerSideAtomGrid extends React.Component {
super(props)
const userDetails = getUserDetails()
this.state = {
page: 0,
pageSizeOptions: [500, 1000, 2000, 4000],
pageSize: 500,
totalRecords: 0,
nextCursor: '*',
cursorList: [{
page: 0,
cursor: '*'
}],
sortFields: {
field: 'created_dtm',
sort: 'desc'
},
columnData,
}
autoBind(this)
}
handlePageChange (page) {
const pageNumber = (page)
const cursorList = this.state.cursorList
let cusrsorMark = ''
_.each(cursorList, (list) => {
if (list.page === pageNumber) {
cusrsorMark = list.cursor
}
})
this.setState({
nextCursor: cusrsorMark,
page: pageNumber
}, () => this.searchData(cusrsorMark, pageNumber))
}
handleSizePerPageChange (pageSize) {
this.resetData(pageSize)
this.searchData('*', 0)
}
handleSorting = (state, instance) => {
const sorted = state
let field = 'created_dtm'
let sort = 'desc'
sorted && sorted.length > 0 && sorted.map(fld => {
field = fld.id
sort = fld.desc ? 'desc' : 'asc'
})
this.setState({
sortFields: {
field,
sort
}
}, () => this.searchData('*', 0))
}
////
searchData('*', 0) {
//Axios call you cna have
}
filterCaseInsensitive (filter, row) {
const id = filter.pivotId || filter.id
return row[id] ? row[id].toString().toLowerCase().includes(filter.value.toLowerCase()) : true
}
render () {
const {
classes, gridData, gridColumns, defaultFilter, totalRecords,
gridPageSizeOptions, gridPage, gridPages, gridPageSize, gridLoading
} = this.props
return (
<div>
<ReactTable
columns={gridColumns}
data={gridData}
onSortedChange={(state, instance) => {
this.handleSorting(state, instance)
}}
filterable={defaultFilter}
defaultFilterMethod={filterCaseInsensitive}
noDataText="Ops No result found!"
defaultPageSize={this.state.pageSize}
className="-highlight"
style={{height: `${totalRecords < 25 ? '' : `800px`}`, width: '100%', textAlign: 'center'}}
pageText={`Total Count : ${totalRecords.toLocaleString()} Page: `}
loading={gridLoading}
page={this.state.page}
pages={this.state.pages}
showPaginationTop
pageSize={this.state.pageSize}
pageSizeOptions={gthis.state.pageSizeOptions}
minRows={25}
manual
onPageChange={page => {
this.setState({page})
this.handlePageChange(page)
}}
onPageSizeChange={(pageSize, page) => {
this.setState({
page,
pageSize
})
this.props.handleSizePerPageChange(pageSize)
}}
showPageJump={false}
/>
</div>
)
}
}
export default (ServerSideAtomGrid)
My Fiddle: https://jsfiddle.net/gowthamguruju/o9ybxqaj/8/

error 405 get method not allowed

Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);

Categories