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
Related
Im try send data from client to server and i get errorm, i use django, python & react.
name: 'AxiosError'
code: "ERR_BAD_REQUEST"
message: "Unsupported protocol localhost:"
the error i have
enter image description here
the data i want to send
enter image description here
api
enter image description here
views
enter image description here
url
enter image description here
models
enter image description here
data i want to send
const onPay = () => {
service.PurchaseDetailsService.setPurchaseDetails(
100,
"test",
"test1",
3,
4,
52
);
};
api
import Axios from "axios";
const $axios = Axios.create({
baseURL: "localhost:8000/api/",
headers: {
"Content-Type": "application/json",
},
});
$axios.interceptors.response.use(
(response) => response,
(error) => {
console.error("got error");
console.error(error);
throw error;
}
);
class PurchaseDetailsService {
static setPurchaseDetails(id, items, name, price,
cardNumber,
idOfPerson) {
const bodyFormData = new FormData();
bodyFormData.append("id", id);
bodyFormData.append("items", items);
bodyFormData.append("name", name);
bodyFormData.append("price", price);
bodyFormData.append("cardNumber", cardNumber);
bodyFormData.append("idOfPerson", idOfPerson);
return $axios({
method: "post",
url: `PurchaseDetails/get_mock_PurchaseDetails/${id}`,
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
}
const service = {
PurchaseDetailsService,
};
export default service;
views
from rest_framework import status
from rest_framework.decorators import api_view,
renderer_classes
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from myStore.serializers import PurchaseDetailsSerializer
from myStore.models import PurchaseDetails
from myStore.serializers import PurchaseDetails
#api_view(['GET'])
#renderer_classes([JSONRenderer])
def get_PurchaseDetails(_, PurchaseDetails):
PurchaseDetails = get_mock_PurchaseDetails()
serializer = PurchaseDetailsSerializer(PurchaseDetails)
return Response(serializer.data,
status=status.HTTP_200_OK)
def get_mock_PurchaseDetails(id, items,
name, price, cardNumber,
idOfPerson):
newData = PurchaseDetails(id,items, name,
price, cardNumber, idOfPerson)
newData.save()
url
urlpatterns = [
path('admin/', admin.site.urls),
path('api/PurchaseDetails/get_mock_PurchaseDetails/<int:id>',
views.get_mock_PurchaseDetails),
]
models
from django.db import models
class PurchaseDetails(models.Model):
id = models.AutoField(primary_key=True)
items = models.CharField(max_length=30)
name = models.CharField(max_length=30)
price = models.IntegerField()
cardNumber = models.IntegerField()
idOfPerson = models.IntegerField()
Try to change the url to const baseURL='http://localhost:8000/api/'
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
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
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"
)
how I can modify my code that be check login&password without refreshing? Ajax call function in django to check login and password then send .json with result. Next one I want display error in js if result is failed or play animation if it's true.
js code:
function CheckBeforeSend()
{
var LoginInput = document.getElementById('flogin');
if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null)
{
if(document.getElementById('Windows').childElementCount > 2)
{
document.getElementById('Windows').children[0].remove();
}
AddPicture("paperJsConn");
}
else
{
document.getElementById("button").type = "submit";
$.ajax({
url: 'http://127.0.0.1:8000/',
data: $('#login_form').serialize(),
type: "POST",
async:false,
success: function(response) {
var CheckingCorrect = response['result'];
//if checkingcorrect play func animation.
},
error: function(error){
alert('No Connection!');
}
});
}
}
$('#login_form').submit(function(e){
e.preventDefault();
$.post('view-url', $(this).serialize());
}); // this event dont work.
views.py:
def Logget(request):
if request.method == 'POST':
login = request.POST.get('flogin')
response_data = {}
response_data['result'] = 'Failed'
lengthBase = UsersLog.objects.count()
for i in range(lengthBase):
if login == str(UsersLog.objects.get(id=i+1)):
password = request.POST.get('lpass', False)
if str(password) == str(UsersLog.objects.get(id=i+1).password):
response_data['result'] = 'Succes'
break
return JsonResponse(response_data)
return render(request, 'index.html')