Ajax with primary key in url of Django cannot work - django

all, i am using Django to do a social website and now i am trying to do friend network.
The problem i encountered now is when i am using ajax to pass user id in url and it throw url cannot be found error, maybe see code the will be much clearer.
the code is as following
i tried to take awayid, that is , take away all id in ajax, url, and method, then it can work. but if i add id parameter in, then it cannot work
html template
<button class="add-friend-btn" id="add-friend"> Add friend
<script src="{% static 'account/js/friends.js'%}" type="text/javascript" ></script>
<script type="text/javascript">
var userprofilePk = "{{userprofile.pk}}"; // other user's id(primary key)
</script>
{% endif %}
javascript friend.js
$(document).ready(function() {
var addFriend = document.getElementById('add-friend');
addFriend.addEventListener("click", function (event) {
$.ajax({
type: 'POST',
headers: { "X-CSRFToken": csrftoken },
url: "ajax/friend-request/send/"+userprofilePk+"/",
data: {
"test": "test",
},
dataType: 'json',
success: function (data) {
},
error: function (error) {
},
});
});
});
Django url
urlpatterns = [
re_path("ajax/friend-request/send/<pk>/", views.send_friend_request, name="user_send_request"),
]
views.py
def send_friend_request(request, id):
print("send_friend_request")
payload = {"test": "test"}
return HttpResponse(json.dumps(payload), content_type='application/json')
the error message is:
Not Found: /account/profile/sm10547/ajax/friend-request/send/2/
app_1 | HTTP POST /account/profile/sm10547/ajax/friend-request/send/2/ 404 [0.01, 172.18.0.1:38852]

If you are using normal URL dispatcher like path use path
converters to capture URL parameters like <int:pk> for example:
path("ajax/friend-request/send/<int:pk>/",
views.send_friend_request, name="user_send_request"). docs for path()
If you're using regex URL dispatcher like re_path use regular
expression to catch URL parameters like (?P<pk>[0-9]) for example: use re_path(r"ajax/friend-request/send/(?P<pk>[0-9])/$", views.send_friend_request, name="user_send_request"). docs for re_path()
In your case use re_path(r"ajax/friend-request/send/(?P<pk>[0-9])/$", views.send_friend_request, name="user_send_request") it should work fine.

Related

Django Ajax Dropdown Select2 not return data

There is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection.
I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this.
<script>
$('.select').select2({
allowClear: true
});
</script>
Here is my ajax code :
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_worksite_id").change(function () {
const url = $("#subunitForm").attr("data-subunit-url");
const worksiteId = $(this).val();
$.ajax({
url: url,
data: {
'worksite_id': worksiteId
},
success: function (data) {
$("#id_upper_subunit_id").html(data);
}
});
});
Thank you for your help, best regards

Django: how to get a javascript value from template to view?

I am currently using Django framework.
I would like to get the value of a javascript value wrote in an html file.
I would like to be able to display it in my view file
Here is my html file from the folder templates:
<script>
var toto = "javascript";
document.write(toto)
</script>
This is my view file:
def javascript(request):
# print the javascript value here
return render(request, "rh/javascript.html")
Thank you for your help !
You have to consider that your script runs on the client-site whereas the view function runs on the server-side. This is one main challenge when it comes to shifting variables from one end to the other.
To make a long story short:
You will have to make a http request from the client-site (for example using jQuery AJAX) to call the view. Then you can pass the variable via AJAX to the view function and use it for further logic.
Example:
your.html
<script type="text/javascript">
// A CSRF token is required when making post requests in Django
// To be used for making AJAX requests in script.js
window.CSRF_TOKEN = "{{ csrf_token }}";
</script>
<div id="variable">Variable</div>
javascript
(function($) {
// trigger the logic on click of the container
$('#variable').on('click', function() {
// assign variable
var variable_for_view = $(this).html();
// make http request using AJAX
$.ajax({
type: 'post',
url: '/your_url/', // this is the mapping between the url and view
data: {
'variable': variable, // ! here is the magic, your variable gets transmitted to the server
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
success: function(data) {
print(sliced_variable)
},
});
});
}(jQuery));
views.py
def your_view(request):
# Assign variable from AJAX request
variable = request.POST.get('variable')
print(variable)
variable.slice(3)
context = {
'sliced_variable': variable
}
return render(request, 'your.html', context)

500 (Internal Server Error) when fetching from Django Rest API default router (to create object)

I am trying to make Django and React to work together, and although I have a basic knowledge of Django (I can develop a site), I am just starting to learn React.
My project structure is based on this video which is loosely based on this blog in turn.
My API works perfectly fine, I can create, retrieve, update, and delete objects without problems.
Also, on my frontend, I have managed to correctly display a list of the items from my database, by fetching the related API Url.
Just to make it clear, here is the main 'backend' urls.py:
from rest_framework import routers
from .views import AssessmentViewSet
router = routers.DefaultRouter()
router.register('api/assessments', AssessmentViewSet, 'assessments')
urlpatterns = router.urls
Now, from what I see on my API webpage, objects are created and retrieved on the same Url, and namely http://127.0.0.1:8000/api/assessments/, as you can see from this screenshot.
The only difference, I guess, is that when I want to create an object, all I have to do ist to specify inside the fetch function, that I am making a POST request. This is done in my CreateAssessmentForm.jsx file:
import React, { Component } from "react";
class CreateAssessmentForm extends Component {
state = {
loading: false,
title: "",
is_finished: false,
created_at: "",
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
let value = event.target.value;
console.log("Value: ", value);
this.setState({
title: value,
});
}
handleSubmit(event) {
event.preventDefault(console.log("Item:", this.state));
fetch("http://127.0.0.1:8000/api/assessments", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(this.state.title),
}).then(response => {
this.setState({
loading: false,
title: "",
is_finished: false,
created_at: "",
}).catch(function (error) {
console.log("ERROR:", error);
});
});
}
render() {
return (
<div>
{this.state.loading ? (
<div className="text-center">Loading...</div>
) : (
<form onSubmit={this.handleSubmit} method="POST">
<h2 className="text-center">Assessment Title</h2>
<div className="form-group">
<label htmlFor="Title">Title</label>
<input
onChange={this.handleChange}
type="text"
className="form-control"
id="TitleInput"
value={this.state.title}
placeholder="E.g. History Quiz"
/>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
)}
</div>
);
}
}
export default CreateAssessmentForm;
When I type something inside the title input, the console logs properly every entry, and when I press the submit button it also logs an object (which as you can see from the code above is my actual state - {this.state}).
The problem is that when submitting, I get a 500 (Internal Server Error) and the object is not saved on the backend database.
Does anyone know what I am doing wrong?
Best shot would be to check what are the django logs as you get Internal Server Error. It should be clear enough of what you are doing wrong, if not, please post the error log.

Paypal call back give me 403 error: csrf token missing or incorrect on django app

I am implementing paypal to a django project. receiving a message to my notify_url works fine. but: when paypal tries to get back to my return_url I provided, django always says csrf-error and the page can not be displayed:
403 error: csrf token missing or incorrect
The return_url is directed to my start page. Any ideas whats wrong with it and why it throws this error?
I appreciate your help very much!
HA
EDIT
views.py
#csrf_exempt
def view_back(request):
return render_to_response("csrf.html",
{"csrftest":"here I am!" },
context_instance=RequestContext(request))
urls.py
url(r'csrf$', 'view_back', name='view_back')
csrf.html
<{% extends 'base.html' %}
<!DOCTYPE html>
{% block content %}
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<body><h1>My Test</h1>
<!-- writes out the form tag automatically -->
{{ csrftest }}
</body>
</html>
{% endblock %}
EDIT2
urlpatterns = patterns('my_project.views',
url(r'^$', 'calculation', name='calculation'),
url(r'money$', 'view_that_asks_for_money', name='view_that_asks_for_money'),
url(r'csrf$', 'view_back', name='view_back'),
)
I have a slightly different answer for this question, as I was trying to figure out how to do this with Express Checkout/Server Integration, and the answer is as follows:
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'sandbox-client-id',
production: 'live-client-id'
},
payment: function(data, actions) {
return actions.request({
method: "post",
url: '/your/django/payment/route/',
headers: {
'X-CSRFToken': "{{ csrf_token }}"
},
json: {
key: value,
}
})
.then(function(response) {
return response.id;
});
},
onAuthorize: function(data, actions) {
return actions.request({
method: "post",
url: '/your/django/execution/route/',
headers: {
'X-CSRFToken': "{{ csrf_token }}"
},
json: {
payment_id: data.paymentID,
payer_id: data.payerID,
key: value,
}
})
.then(function(response) {
// Show the buyer a confirmation message.
return console.log(response);
});
}
}, element_selector);
I suppose you are using the django-paypal library but even if you are not this note from the documentation of the library explains everything:
Note that return_url view needs #csrf_exempt applied to it, because
PayPal will POST to it, so it should be custom a view that doesn’t
need to handle POSTs otherwise.
So please careful when adding #csrf_exempt[see the docs] to the view, make sure this page is used only for this purpose and not for other POSTs for obvious security reasons.
Here's an example of how to pass CSRF with paypal, to a django backend.
payment: function () {
return new paypal.Promise(function (resolve, reject) {
$.ajax({
method: 'post',
url: '{% url 'payment_comms' %}',
data: {
what: 'create_payment',
amount: $("#amount").val(),
},
headers: {
'X-CSRFToken': '{{ csrf_token }}',
},
success: function (data) {
resolve(data.paymentID);
},
error: function (data) {
reject(data)
}
})
})
},

Django Ajax calls to load a file not working

I'm going through Jquery AJAX tutorial in w3schools and trying to simulate a similar call in my Django project.
I want to load a file from the server using Ajax request, I was able to successfully load through load() function by calling a view which is mapped to /ajaxload/ in my urls.py file.
$("button").click(function(){
alert('hi');
$("p").load("/ajaxload/");
return false;
})
Can I load the same file by calling .ajax call by passing the url directly?
I apologize if its a very basic question but my new to web development.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"demo_ajax_load.txt",async:false,success:function(result){
$("div").html(result);
}});
});
});
</script>
</head>
<body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>
Update:
I read some docs and trying to call view as below but I dont any response
$(document).ready(function(){
/* This call is working
$("button").click(function(){
alert('hi');
$("p").load("/ajaxload/");
return false;
})
*/
//The below call is not working
$("button").click(function(){
alert('hi');
$.ajax({
url: "/ajaxload/",
type: "get",
data: serializeData,
success: function(response) {
alert(response)
}
})
event.preventDefault();
})
});
views.py
def ajax_load(request):
return render(request,'demo_test.txt')
urls.py
(r'^ajaxload/$',ajax_load),
Update:- It started working once the data:serializedata was removed..
serializeData is not defined in your js script, so it raises an exception that breaks the run.
Open your browser console, you will see the error.