Access a json object form views django - javascript

i have tried a number of suggestions but need help.
in my views.py
def findnamesurname(request):
username = request.POST['username']
obj = Users.objects.all().values("first_name").filter(username=username)
return HttpResponse(obj)
in my js
$.ajax({
url: "/findnamesurname",
method: "POST",
data: {
'csrfmiddlewaretoken': '{{csrf_token}}',
"username": data,
},
success: function (data) {
alert(JSON.stringify(data))
}
})
}
I want to get first name please in a variable
How to access this object please.
Whet I alert I get:
{'first_name': 'hello', 'last_name': 'there'}

Not sure I got your question right. But if you want to retrieve the first and last name of a user by its username, you first need to filter/search that user in the database. Then you can send the response by using JsonResponse.
from django.http import JsonResponse
from django.http import Http404
def findnamesurname(request):
username = request.POST["username"]
try:
user = YourUserModel.objects.get(username=username).values(
"first_name", "last_name"
)
except YourUserModel.DoesNotExists:
raise Http404
return JsonResponse(user)

Related

Not able to retrieve data values from Ajax GET call into Django view

I am trying to query the employee list based on parameter I send
through ajax call inside data, but it giving me an error (i want it
through GET req only )
Js ajax func
$(document).ready(function () {
$(".call_ajax").click(function () {
$.ajax({
url: "/employee_list",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {
designation: "soft eng",
},
headers: {
"X-CSRFToken": csrftoken,
Authorization: my_token,
},
success: function (data) {
console.log(data);
},
error: function (xhr) {
//Do Something to handle error
console.log(xhr.error);
},
});
});
my view
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.data['designation']
print(data_)
employees = Employee.objects.all()
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
error i am getting in browser
GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)
error in Django log
File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
data_ = request.data['designation']
KeyError: 'designation'
request.data returns the parsed content of the request body.
This is similar to the standard request.POST and request.FILES
You can use request.GET.get('designation')
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.GET.get('designation') # Here I made changes
print(data_)
employees = Employee.objects.filter(designation=data_) # Map parsed data with database field
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
or
You can override get_queryset method. As for query string parameters request.data holds POST data, you can get query string params through request.query_params
def get_queryset(self):
data = self.request.query_params.get('designation')
queryset = Model.objects.filter() # use whatever you want filter
return queryset
To know more about request.data and request.query_params, here is the link
Request parsing link
It is most probably because you are using GET, but the data resides in body. Have a look at this. To try to fix this, change your request method to POST:
$.ajax({
url: "/employee_list",
type: "POST",
...

How to display search results with ajax in django project?

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(),

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)

Access ajax elements with django

i am using ajax to fetch django model and get results
views.py
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data':data,})
ajax request
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
if (data) {
console.log(data.title);
}
}
});
and i am getting this response from django
{"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"}
my question is how i can access the title.
You here double serialized the value for the "data" key: first by the serializers.serialize(..) that constructed a string, and the you again serialize it (constructing an string literal), making it harder to obtain the elements.
We can prevent this, for examply by turning the JSON blob back into a vanilla Python object first:
from json import loads as json_loads
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data': json_loads(data), })
Then the AJAX call will receive a JSON blob where "data" does not map to a string, but a list of subdictionaries, making it easier accessible.
Here there are two results for your query, you can print the first title with:
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
console.log(data.data[0].fields.title);
}
});

Not able to pass parameters through url in Ajax request using Rails

I'm trying to pass a parameter through a url in an Ajax request that's triggered by a confirmation dialogue. I'd like to fetch the value of that parameter in my Rails controller given a successful request but I haven't been able to do it.
I've tried so far the following code:
Here my Ajax request where I've been adding the param in the URL plus other params in data
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "POST",
url: "/leaderboards/1/?test=1",
data: { leader: { name: name, time: time } },
success: success
});
}
Here the dialogue-related JS
function nameAlert() {
return confirm("Name already exists. Would you like to continue?");
};
(function() {
if (nameAlert()) {
continueSave();
}
else {
//something else here
}
})();
Although the request successfully reaches the controller there's params[:test] is nil in the controller.
I've also tried to pass the test param in data, but it is not working either.
Would appreciate some help.
The relevant controller action (leaders_controller.rb)
def create
#leader = Leader.new(leader_params)
#leader.leaderboard_id = #leaderboard.id
#name_repeated = !#leaderboard.leaders.find_by(name: #leader.name).nil?
#check = params[:test]
if params[:test].nil? && #name_repeated == true
render :template => 'leaders/repeated_name.js.erb'
else
#leader.save
#rank = #leader.rank_in(#leaderboard)
respond_to do |format|
if #leader.save
format.html { redirect_to root_path }
format.js { }
else
end
end
end
end
Note:
1.- 'leaders/repeated_name.js.erb' contains the code for the Ajax request
2.- In routes Leader resource is nested within Leaderboard resource
Sorry guys I found the mistake. It was a dumb one.
I have shallow nested routes so that leaders is nested in leaderboards, therefore I was using the incorrect path for the request. It should be:
$.ajax({
type: "POST",
url: "/leaderboards/1/leaders?test=1",
data: { leader: { name: name, time: time } },
success: success
});
I should have caught that before sorry for wasting your time.
I'll post here - my comments are getting too long.
Try adding { type: 1} to your data and changing type to GET. Rails params contain both GET and POST data - you don't even have to change your controller.
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "GET",
url: "/leaderboards/1/",
data: { leader: { name: name, time: time }, test: 1 },
success: success
});
}

Categories

Resources