Updated Question:
Wrong redirection of URL in Django. I have this:
views.py.
def graph(request):
if request.method == 'POST' and 'text' in request.POST:
print("testing....")
print(request.POST.get('text'))
name = request.POST.get('text')
context = {
'name': name,
}
print(context)
return render(request, 'StockPrediction/chart.html', context)
else:
return render(request, 'StockPrediction/greet.html')
urls.py
urlpatterns = [
path("", views.greet, name='greet'),
path("index/", views.index, name='Stock Prediction'),
path("prediction/", views.prediction, name='Prediction'),
path("view/", views.graph, name='Graph'),
]
for testing purposes, I m using a print statement. So there is no problem until printing print(context) but the problem is it goes to 'StockPrediction/greet.html' not 'StockPrediction/chart.html'. which I need.
You should use ajax request:
$.ajax({
type: 'POST',
url: 'YOUR VIEW URL',
data: {'row': row, 'text': text},
success: function (data){
DO SOMETHING HERE if VIEW has no errors
})
in your view:
row = request.POST.get('row')
text = request.POST.get('text')
also you should care about crsf-token. Documentation
your can POST it GET it or put it as a variable in your url. here is a post approach:
using jquery :
$.ajax({
url : "/URL/to/view",
type : "POST", // or GET depends on you
data : { text: $text },
async: false,
// handle a successful response
success : function(json) {
// some code to do with response
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
In your view you can get the data as json and return josn as response
import json
def my_view(request):
if request.method == 'POST':
response_data = {} // to return something as json response
text = request.POST['text']
...
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
Related
Hello I am getting the mentioned error above in my python flask website
here is the code for adding expenses in my auth.py file
#auth.route('/add_expenses', methods=['GET', 'POST'] )
def adding_new_expenses():
name_user = request.args.get("user")
user = None
if name_user is None:
return redirect (url_for("auth.home"))
else:
form = AddExpense(request.form)
if request.method == 'GET':
return render_template("add_expenses.html", form=form)
else:
user = User.query.filter_by(id=name_user).first()
if user is not None:
if form.validate_on_submit():
new_expense = Expenses(expense_category_name=form.expense_category_name.data,
description_expense=form.description_expense.data,
date_purchase=form.date_purchase.data,
amount=form.amount.data,
user_id=user.id)
db.session.add(new_expense)
db.session.commit()
flash("Expense added successfully.")
return redirect(url_for("auth.home", user = name_user))
and my views.py:
#views.route('/add_expenses', methods=['POST'])
def adding_new_expenses():
data = request.json
name_user = data.get("user")
expense_category_name = data.get('expense_category_name')
description = data.get('description_expense')
date = data.get('date_purchase')
amount = data.get('amount')
if name_user is None or expense_category_name is None or description is None or date is None or amount is None:
return jsonify({"error": "Missing required fields"}), 400
user = session.query(User).filter_by(id=name_user).first()
if user is None:
return jsonify({"error": "User not found"}), 400
new_expense = Expenses(expense_category_name=expense_category_name, description_expense=description,
date_purchase=date,
amount=amount, user_id=user.id)
db.session.add(new_expense)
db.session.commit()
return jsonify({"message": "Expense added successfully."}), 200
and my javascript code:
function adding_new_expenses(name_user, type, description, date, amount) {
fetch("/add_expenses", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name_user: name_user,
expense_category_name: type,
description_expense: description,
date_purchase: date,
amount: amount
})
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("An error occurred while adding the expense.");
}
})
.then(data => {
if (data.message === "Expense added successfully.") {
console.log("Expense added successfully.");
window.location.href = '/home?user=' + name_user;
} else {
console.log(data.error)
}
})
.catch(error => {
console.error(error);
})
}
i can't seem to figure out this error, maybe someone can help me out here.
i am using python flask as my framework, slqalchemy as my database, jinja2 template, bootstrap, and a javascript code
I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing.
display.html
var SelectedID = [];
function getvalues() {
$(':checkbox:checked').each(function (i) {
SelectedID[i] = $(this).val();
console.log("Selected Data", SelectedID[i])
$.ajax({
url: "{% url 'addtoexisting' bid=adduser.id %}",
type: "POST",
dataType: "json",
data:{
SelectedID : SelectedID[i],
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
console.log("Selected Data AJAX", SelectedID)
alert("Successfully sent the Data to Django");
},
error: function (xhr, errmsg, err) {
// alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
}
views.py
def display(request):
is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
SelectedID = request.POST.get('SelectedID')
print(SelectedID)
return render(request, 'display.html',{})
SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing.
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 have two different AJAX requests that I want to combine.
The first one gets some html:
def ajax_get_html(request):
if request.is_ajax() and request.method == "POST":
context = {
...
}
return render(request,"my_app/my_template.html", context)
else:
raise Http404
And is used like this:
$.ajax({
type: "POST",
url: ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$(my_div).html(data);
}
});
My second one gets some data:
def ajax_get_data(request):
if request.is_ajax() and request.method == "POST":
data = {
"answer": 42,
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
else:
raise Http404
and is used like this:
$.ajax({
type: "POST",
url: another_ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
var answer = data.answer;
$("#notification_badge").html(answer);
}
});
How can I combine these to into the same request? I tried adding the result of render to the data in the second view, but json.dumps says it's non serializable.
You can't serialize the output of Django's render because it returns an HttpResponse object, not a string (which is what you want to be able to serialize it).
A good solution is to return your html to the frontend using render_to_string:
...
data = {
"answer": 42,
"html": render_to_string("my_app/my_template.html", context)
}
...
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