I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me
Method Not Allowed (POST)
I don know if i'm doing it rigth, or if i need to modify something for it to work.
My view.py is something like this
class Landing(View):
def get(self,request):
if request.method == 'POST':
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
return render(request,'landing.html',{'foo':'bar'})
And i send the reques from Javascript
$(document).ready(function() {
$('#productos').on('change', function(e) {
//Call the POST
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var value = $('#productos').val();
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken : csrftoken,
value : value
},
success : function(json) {
console.log(json);
drop(json);
},
error : function(xhr,errmsg,err){
console.log(xhr.status+": "+xhr.responseText)
}
});
});
});
I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views.
So, What does need my code to accept the POST method?
The dispatch method of a class based view determines which function is called, so far you've written a get function, but no post function so just move the logic into a post function.
class Landing(View):
def post(self,request):
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
def get(self, request):
return render(request,'landing.html',{'foo':'bar'})
Related
I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form.
At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax.
Views.py
def indexView (request):
form = FriendForm ()
friends = Friend.objects.all ()
return render (request, "index.html", {"form": form, "friends": friends})
def searchFriend(request):
if request.method =="POST":
form = FriendForm (request.POST)
if form.is_valid():
if request.is_ajax():
name = form.cleaned_data['name']
query = Friend.objects.filer(first_name__contains=name)
print(query)
return JsonResponse(list(query), safe=False)
else:
return JsonResponse(form.errors)
Main.js
$(document).ready(function() {
$("#form1").submit(function() { // catch the form's submit event
var search = $("#searchField").val();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
method: 'post',
dataType: 'json',
url: "search/ajax/friend/",
success: function(data) { // on success..
console.log(data)
}
});
return false;
});
});
Is your query getting printed in terminal ?
Friend.objects.filer use filter instead of filer
and use type: 'post' instead of method: 'post',
and add data: $(search).serialize(), instead of data: $(this).serialize(),
I have dictionary in javascript something like this:
var data = {"name":"nitin raturi"}
Now I want this data to be accessed in my django view something like this:
def my_view(request):
data = request.POST
How to send data to my url using jquery?
lets do this.
This is your dictionary in javascript:
var data = {"name":"nitin raturi"};
Now define a function that will make a post request using jquery.
function send_data(data, callback) {
// callback is a function that you should pass to handle your response
$.ajax({
type: "POST",
url: '/sample-url/', // change this to your url here
data: {"data": JSON.stringify(data)},
success: function (response) {
callback(response);
},
});
}
Now use the send_data function like this:
send_data(data,function(response){
//handle your response here
console.log(response);
})
Now you can access your data in your django view like this:
import json
#csrf_exempt
def my_view(request):
data = request.POST.get('data')
data = json.loads(data) # this will convert your json data to python dictionary
name = data.get("name")
// Handle your data and return anything you wish
return render(request,"index.html",{})
i have problem with ajax when i send a request from my form it doesn't get the value from the form
this is my view code
def create(request):
if request.method == 'POST':
msg_text = request.POST.get('the_massage')
data = {}
form = ChatApp(message=msg_text, user=request.user)
form.save()
data['message']=form.message
data['user']=form.user.username
return JsonResponse(data)
else:
return JsonResponse({'nothing coming thrue'})
it shod get the_massage variable but it give me null value
this is my ajax function :
$(function () {
$('#main-form').on("submit" ,function () {
console.log("create function is here");
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: {the_massage:$('#msgbox').val()},
dataType: 'json',
success: function(json) {
console.log(json);
console.log('success');
},
error: function(error){
console.log('we have error');
},
});
});
});
when i console log the value it just come through in the console
please help me
and show me this in the console :
Resource interpreted as Document but transferred with MIME type
application/json: "http://localhost:8000/create/".
Call the function in your event:
$('#main-form').on("submit" ,function (event) {
event.preventDefault();
console.log('submited');
console.log($('#msgbox').val())
created();
});
I see many possibles problems here.
1) just for dev propose, delete #login_required (if you have) from your view and add #csrf_exempt to avoid this problem on dev.
2) Please look inside request.body on your view.
3) if point 1 and 2 doesn't work, please put the server response of this call: POST localhost:8000/create 403 (Forbidden)
this is the write answer : i solve this and its on git hub now https://github.com/mhadiahmed/tinypice
I am currently working on a React-Rails app and am trying to figure out how to pass a deleted record to a parent component from the success function to update the parent component's view.
Here is the code in question:
handleDelete (e) {
var that = this;
var url = "/records/" + this.props.data.id;
e.preventDefault();
$.ajax({
method: 'DELETE',
url: url,
dataType: 'JSON',
success: (data) => {
console.log(data);
that.props.handleDeleteRecord(data);
}
});
}
The console.log(data) above returns undefined.
My problem is that Ajax doesn't seem to be passing anything to the success function. Is that true?
You need to edit the Rails RecordsController so that it renders some type of data after the request. I recommend JSON.
def destroy
record = Record.find(params[:id])
record.destroy
render json: record
end
With that you will have the JSON form of the record that you just delete passed back to the success function of the AJAX call.
I have a backbone model that I am calling fetch with. I have a flask server on which i need to access the id of the backbone model. I cannot seem to get my hands on the id of the model on the server. How can I access the entityId in my flask code
BB.Politician = Backbone.Model.extend({
defaults: {
type: "Politician"
},
url: "/my_url_here"
});
var currentUser = new BB.Politician({"entityId": "1625"});
currentUser.fetch({
//method: "POST",
success: function(user){
currentUserView.render();
}
});
#Flask server code
#app.route('/my_url_here', methods=['GET', 'POST'])
def return_poitician():
print request
print request.args
print request.values
#none of the above print statements are giving me the "entityId"
return data
I also tried adding in the id in the route but that just threw a 404 error when the fetch() executed:
#app.route('/my_url_here/<entityId>', methods=['GET', 'POST'])
def return_poitician(entityId):
print entityId
#app.route('/my_url_here/<entityId>', methods=['GET', 'POST'])
isn't picking up any id because you aren't sending any.
Backbone fetch uses the id field of the model to construct the fetch URL, in your case I would recommend turning the entityId into id:
BB.Politician = Backbone.Model.extend({
defaults: {
type: "Politician"
},
url: "/my_url_here"
});
var currentUser = new BB.Politician({"id": "1625"});
and let Backbone construct the GET, which would look like:
"/my_url_here/" + this.get('id'); // this refers to model
which turns into
"/my_url_here/1625"
Backbone.Model.url also accepts function as value so you can define your own logic for constructing URLs. For instance, if you must retain the entityId you can construct your url like:
url: function () {
return "/my_url_here" + this.get('entityId');
}