I'm trying change Ajax json url to python variable with a json in Django. As you can see the url in both cases are the same so I can't understand what is going on.
Thanks in advance.
What I'm looking for and does not work
<script>
$(document).ready(function() {
var table = $('#users').DataTable({
"ajax": "{{ es_docs }}",
my view:
#login_required(login_url="/login/")
def index(request):
context = {}
context['segment'] = 'index'
html_template = loader.get_template( 'index.html' )
resp = requests.get("https://gyrocode.github.io/files/jquery-datatables/arrays_id.json").json()
context['es_docs'] = resp
return HttpResponse(html_template.render(context, request))
Template.html:
<script>
$(document).ready(function() {
var table = $('#users').DataTable({
"ajax": "https://gyrocode.github.io/files/jquery-datatables/arrays_id.json",
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
This:
resp = requests.get(...)
Returns a response object. To get the json data do this:
response = requests.get(...)
if response.status_code != 200:
# handle errors:
else:
json_data = response.json()
context['es_docs'] = json_data
Related
My html code:
<form method="post" action="" enctype="multipart/form-data">
<input id="file-upload" type="file" name="file-upload" style="display:none;" accept="image/png, image/jpeg, image/jpg">
<button class="avatar_button"
id="file-button"
name="coose_avatar"
onclick="document.getElementById('file-upload').click()"
style="cursor: pointer;"
>Choose file</button>
<script>
document.getElementById("file-upload").addEventListener("change", function() {
var file = this.files[0];
var formData = new FormData();
formData.append("file-upload", file);
fetch("/profile", {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(response => response.json())
.then(data => {
document.getElementById("avatar_input").value = data.link;
})
});
</script>
and my python code:
def upload_to_imgur(image_path):
client_id = ""
api_key = ""
url = "https://api.imgur.com/3/image"
headers = {
"Authorization": f"Client-ID {client_id}"
}
with open(image_path, "rb") as image:
data = {
"image": image.read(),
"type": "file"
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
response_json = response.json()
return response_json["data"]["link"]
else:
return None
#app.route("/profile", methods=["GET", "POST"])
def profile():
if request.method == "POST":
print(request.form)
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
if
alot of other things
elif request.form.get("file-uploader") == "file-uploader":
print("yes")
# sleep(5)
if 'file-upload' in request.files:
image = request.files["file-upload"]
name=session["username"]
imagename = name
image.save(imagename)
imgur_link = upload_to_imgur(imagename)
print(imgur_link)
it should make a imgur post and print the link but when i try to upload the file, the code already tried to run. how do i make it working and/or start the python code when the file is selected.
I; ve tried many things but it just wont work
can anyone help me?
I tried to get the data I send via Ajax with request.GET.get, but this does not work. Data is always None. I really appreciate any kind of help!
This is my jQuery/Ajax code:
$(document).ready(function(){
$(".jcf-select.jcf-unselectable").on('click', function(){
var sel = $('#sort').children("option:selected").val();
console.log(sel)
$.ajax({
url: '/filter-data',
data: sel,
dataType: 'json',
success:function(res){
console.log(res);
$("#filter_products").html(res.order);
}
});
});
});
This is my view:
def filter_data(request):
if request.is_ajax:
query = []
data = request.GET.get('data')
if data == "gpv":
query = data.order_by("price_with_shipping")[:150]
elif data == "gp":
query = data.order_by("lowest_price")[:150]
elif data == "lp":
query = data.order_by("liter_price")[:150]
elif data == "tz":
query = data.order_by("-lowest_price")[:150]
t = render_to_string('homepage/ajax-products.html', {'order': query})
return JsonResponse({'order': t})
data must be an object in ajax.
for example:
$.ajax({
url: '/filter-data',
data: {'key-data':sel},
dataType: 'json',
success:function(res){
console.log(res);
$("#filter_products").html(res.order);
}
and in your django veiw:
data = request.GET.get('key-data')
I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new r (https://js.stripe.com/v3/:1:6143)
at Js (https://js.stripe.com/v3/:1:165350)
at $s (https://js.stripe.com/v3/:1:165646)
at https://js.stripe.com/v3/:1:166758
at Qs (https://js.stripe.com/v3/:1:166769)
at nc (https://js.stripe.com/v3/:1:167275)
at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030)
at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39
Here's the Vue.js method responsible for this:
<script src="https://js.stripe.com/v3/"></script>
<script>
const PlansApp = {
data() {
return {
}
},
delimiters: ['[[', ']]'],
methods: {
subscribe(plan) {
console.log('Subscribe:', plan);
const stripe = Stripe('{{ stripe_pub_key }}');
fetch('/dashboard/myaccount/teams/api/create_checkout_session/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({
'plan': plan
})
})
.then(function(response) {
return response.json()
})
.then(function(session) {
console.log(session)
return stripe.redirectToCheckout({ sessionId: session.sessionId })
})
.then(function(result) {
if (result.error) {
console.log('Error:', result.error.message)
}
})
.catch(function(error) {
console.log('Error:', error);
});
}
}
}
Vue.createApp(PlansApp).mount('#plans-app')
</script>
And here's the Django code that creates the session on the backend:
#login_required
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
plan = data['plan']
if plan == 'basic':
price_id = settings.STRIPE_BASIC_PRICE_ID
else:
price_id = settings.STRIPE_PRO_PRICE_ID
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id = request.user.userprofile.active_team_id,
success_url = '%s%s?session_id={CHECKOUT_SESSION_ID}' % (settings.WEBSITE_URL, reverse('team:plans_thankyou')),
cancel_url = '%s%s' % (settings.WEBSITE_URL, reverse('team:plans')),
payment_method_types = ['card'],
mode = 'subscription',
line_items = [
{
'price': price_id,
'quantity': 1
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
I'm struggling to find out why I'm getting the error that I'm getting and would be grateful for any help!
I guest the problem come from the 'success_url' and the 'cancel_url'.
Try to add http:// or https:// in your url
Cordially
I'm trying to write a test for an Ajax get a request in Django.
Here's how I tried.
from django.test import TestCase
from django.urls import reverse
from .models import ResourcePost, User
from register.models import DonorProfile
from django.utils import timezone
class getResourcePostTests(TestCase):
def setUp(self):
ResourcePost.objects.create(
title="test1",
description="test",
quantity=10,
dropoff_time_1=timezone.now(),
dropoff_time_2=timezone.now(),
dropoff_time_3=timezone.now(),
date_created=timezone.now(),
donor=createdonor_1(),
resource_category="FOOD",
status="AVAILABLE",
)
...
def test_getResourcePost(self):
rescource_post_1 = ResourcePost.objects.get(title="test1")
rescource_post_2 = ResourcePost.objects.get(title="test2")
rescource_post_3 = ResourcePost.objects.get(title="test3")
response = self.client.get(reverse('donation:getResourcePosts'))
self.assertEqual(response.status_code, 200)
Here is my view for the ajax call:
#login_required
def getResourcePost(request):
user = request.user
curr_user_rc_1 = user.helpseekerprofile.rc_1
curr_user_rc_2 = user.helpseekerprofile.rc_2
curr_user_rc_3 = user.helpseekerprofile.rc_3
posts = ResourcePost.objects.all()
passingList = []
for post in posts:
if post.date_created >= user.helpseekerprofile.message_timer_before and (
post.resource_category == curr_user_rc_1
or post.resource_category == curr_user_rc_2
or post.resource_category == curr_user_rc_3
):
notiPost = {
"id": post.id,
"title": post.title,
"description": post.description,
}
passingList.append(notiPost)
context = {"resource_posts": passingList}
return JsonResponse(context)
This is my ajax code:
$(document).ready(function () {
setInterval(() => {
$.ajax({
type: 'GET',
url: "{% url 'donation:getResourcePosts' %}",
success: function (response) {
$("#display").html('<i class="fas fa-bell"></i>')
let postCounter = 0
for (i = 0; i < response.resource_posts.length; i++) {
postCounter += 1
}
if (postCounter > 0) {
$("#display").append('<span class="message-number">' + postCounter + '</span>')
}
},
error: function (response) {
console.log("No DATA FOUND")
}
})
}, 1000 * 2)
})
I keep getting fail because the reponse is 302.
Why am I not getting 200? How can I fix this to get 200?
The variables rescource_post_X come up as variables not used. How do I use them? Should I use them?
Thank you!
The #login_required decorator is redirecting your request to the login page
I'm trying to learn django/python and I'm trying to figure out how to read json data...
I have something like :
{
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
},...
}
I'm trying to read specific data in my html page. Right now this json data is being displayed in the html page.
The source of the this json comes from this:
return HttpResponse(json.dumps(response),mimetype="application/json")
I'm trying to figure out the django/python convention of getting specific data? Am I supposed to do a for each loop? I come from a self taught php background, and I'm trying to teach myself python/django.
Thank you
edit:
I also have this in my view.py before the return HttpResponse
try:
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError, error:
response = json.loads(error.read())
This is the easiest way to read json in html (Send by Django)
def sendJson(request):
if request.method == 'GET':
context = {"name":"Json Sample Data"}
return render_to_response('name.html',context)
Django Template Html Code
<div class="col-md-9 center">
<span class="top-text">{{name}}</span>
</div>
Now according to your:
def sendJson(request):
if request.method == 'GET':
jsonData = {
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
}
}
data = json.dumps(jsonData)
return HttpResponse(data, content_type="application/json")
you can read this data by using jquery also
another example to create json and read in html
url.py
url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),
view.py
def anotherexample(request):
if request.method == 'POST':
_date = strftime("%c")
response_data = {}
response_data['status'] = 'taken'
response_data['issueTakenTime'] = _date
return HttpResponse(json.dumps(response_data), content_type="application/json")
Html view and jquery
$.ajax({
url: "/anotherexample/",
// contentType: "application/json; charset=UTF-8",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
status : "taken"
},
type: "POST",
error: function(res) {
console.log("errr", res)
},
success: function(res) {
console.log("res", res)}
})
It's not clear what you want to loop over, where, or how, but basic loops work like this:
data = {"key1":[1,2], "key":[4,5]}
for key, values in data.iteritems():
print key, values
I was able to figure out the solution through this link: Decode json and Iterate through items in django template
It helped me and hopefully it'll help someone else who has the same problem as me.
Thanks