Why do I get a HTTP 200 followed immediately by a HTTP 500? I have the impression the Ajax function is called twice in a row. The objects that I expect to be created are actually created though...
my ajax function is called on a form submit:
$(document).on('submit','#like_form_reading_list{{ article.pk }}', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "userprofile:like" %}',
data: {
journal: '{{ journal.pk }}',
section: '{{ section.pk }}',
article: '{{ article.pk }}',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function showAlertLike() {
$("#success_like").show().delay(2000).fadeOut();
},
error: function showAlertPin() {
$("#error_like").show().delay(2000).fadeOut();
}
});
});
In my view:
class LikeView(generic.FormView):
"""
A view that creates a LikedArticles object when a user clicks on the like badge under each article displayed.
"""
def post(self, request):
if request.method == 'POST':
user = request.user
journal_pk = request.POST.get('journal')
section_pk = request.POST.get('section')
article_pk = request.POST.get('article')
journal = Journal.objects.get(pk=journal_pk)
section = Section.objects.get(pk=section_pk)
article = Article.objects.get(pk=article_pk)
print('IN LIKE VIEW ', user, journal_pk, section_pk, article_pk)
LikedArticles.objects.create(
user=user,
journal=journal,
section=section,
article=article
)
return HttpResponse('')
In my terminal:
Internal Server Error: /like/
Traceback (most recent call last):
[SOME ERROR MESSAGE]
"/Users/benoitkoenig/Desktop/projet_web/harrispierce_django/hpdjango/lib/python2.7/site-packages/django/db/models/fields/init.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
('IN LIKE VIEW ', at 0x107eb5c80>>, u'1', u'2', u'2390')
[31/Oct/2017 18:59:58] "POST /like/ HTTP/1.1" 200 0
[31/Oct/2017 18:59:59] "POST /like/ HTTP/1.1" 500 18107
Related
I have the following ajax request:
$(document).ready(function () {
$.ajax({
url: '{{ admin.generateUrl('url') }}',
method: 'GET',
data: {
'id': {{ object.id }}
},
success: function (html) {
//
},
});
Data being optional as this request will be called in two different pages, create and /{id}/edit. How do I pass this to my data as the id of the object will not be always present?
I have 2 serializers:
class DetalleSerializer(serializers.ModelSerializer):
producto = serializers.CharField(source='producto.nombre')
class Meta:
model = DetalleVenta
fields = ('cantidad','producto')
class PedidoSerializer(serializers.ModelSerializer):
detalleventa = DetalleSerializer(many=True, read_only=True)
class Meta:
model = Venta
fields = ('id','cliente','descripcion','detalleventa','atendido')
and my viewset:
class PedidoViewSet(viewsets.ModelViewSet):
queryset = Venta.objects.exclude(atendido=True)
serializer_class = PedidoSerializer
def destroy(self, request, pk=None):
try:
queryset = Venta.objects.exclude(atendito=True)
object = get_object_or_404(queryset, pk=pk)
object.atendido = True
object.save(update_fields=['atendido'])
return Response({"status": True, "results": "Pedido atendido correctamente"})
except NotFound as err:
return Response({"status": False, "error_description": err.detail})
To remove simply change the state of my attended field, which is a Boolean (true / false) logical deletion.
y estas mis 2 urls:
url(r'^pedido/$',PedidoViewSet.as_view({'get': 'list', 'post': 'create'}),name='api-pedido',),
url(r'^pedido/(?P<pk>\d+)/$',PedidoViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}),
name='api-atendido',),
The recovery of all data is not a problem, it brings me everything I need.
via the url: url: "{% url 'api-pedido'%}", GET
But when I want to do the logical deletion of a button **(DELETE):
$('.btn').click(function(){
$.ajax({
url: "{% url 'api-atendido' %}",
data: {pk:91},
type: 'DELETE',
contentType: 'application/json',
success: function(result) {
console.log('atendido correctamente');
},
});
});
It shows me the following error: Reverse for 'api-atendido' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pedido/(?P<pk>\\d+)/$']
error captures:
Something missing? or something am I doing wrong?
Issue is due to your url name. Your ajax url is {% url 'api-atendido' %}. That url name required a valid pk rather than sending pk as data. ajax url should be {% url 'api-atendido' 'pk' %}, where pk is the primary key of the model Venta.
$('.btn').click(function(){
$.ajax({
url: "{% url 'api-atendido' 91 %}",
data: {},
type: 'DELETE',
contentType: 'application/json',
success: function(result) {
console.log('atendido correctamente');
},
});
});
If you are calling the ajax call dynamically, then give the exact url instead of its name. Because template rendering is done by server. So all the template tags are converted during the page rendering. To do it dynamically consider the following code.
$('.btn').click(function(){
var pk = 91; //replace this with the actual id
$.ajax({
url: "pedido/"+pk+"/",
data: {},
type: 'DELETE',
contentType: 'application/json',
success: function(result) {
console.log('atendido correctamente');
},
});
});
all! Can u please help me? I have a small problem. When i click button, When I click on a button, a new object should be created without reloading the page. Only one parameter is required to create an object.
The problem is that when you click the object is created (the new object is displayed in the admin panel), but in the console js there is an error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
JS:
function initBuyButton(){
$('.button-buy').click(function(e){
e.preventDefault();
var test = $(this);
var smartphone_id = test.data("smartphone_id");
var url = test.attr("action");
basketUpdating(smartphone_id, url);
});
}
function basketUpdating(smartphone_id, url){
var data = {};
var csrf_token = $('#form_buying_product [name="csrfmiddlewaretoken"]').val();
data["csrfmiddlewaretoken"] = csrf_token;
data.smartphone_id = smartphone_id;
$.ajax({
url: url,
type: 'POST',
data: data,
cache: true,
});
}
$(document).ready(function(){
initBuyButton();
});
View:
def basket_adding(request):
"""Add new smartphone to basket."""
data = request.POST
smartphone_id = data.get('smartphone_id')
SmartphoneInBasket.objects.create(smartphone_id=smartphone_id)
return True
HTML:
<form id="form_buying_product" > {% csrf_token %}
{% for sm in smartphones %}
...
<input type="submit" action="{% url 'basket_adding' %}" class="button-
buy" data-smartphone_id = "{{ sm.id }}" value="Buy">
{% endfor %}
</form>
As mentioned in the comments, a view needs to return an HttpResponse. If you want, it can be n empty:
return HttpResponse()
You need to include the csrf token as a header.
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
url: url,
type: 'POST',
headers:{
"X-CSRFToken": csrftoken
},
data: data,
cache: true,
});
Because an error 500 is that your permission gets denied to send the data.
I have the following helper functions defined:
import json
def json_response(request, val, **kw):
"""Return a json or jsonp response.
"""
if request.GET.get('callback'):
return jsonp(request.GET['callback'], val, **kw)
else:
return jsonval(val, **kw)
def jsonval(val, **kw):
"""Serialize val to a json HTTP response.
"""
data = dumps(val, **kw)
resp = http.HttpResponse(data, content_type='application/json')
resp['Content-Type'] = 'application/json; charset=UTF-8'
return resp
def jsonp(callback, val, **kw):
"""Serialization with json callback.
"""
data = callback + '(%s)' % json.dumps(val, **kw)
return http.HttpResponse(
data,
content_type='application/javascript; charset=utf-8'
)
with those defined your view can return a json object (to your ajax call):
def basket_adding(request):
"""Add new smartphone to basket."""
...
return json_response(request, True)
it's common practice to return an object though, so perhaps:
return json_response(request, {"status": True})
I am trying to make a simple ajax request to a view but keep having a not Found error for the given url:
Not Found: /myapp/start_session/1/scan_ports/
"POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711
js
$(document).ready(function() {
$.ajax({
method: 'POST',
url: 'scan_ports/',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function (data) {
alert("OK!");
},
error: function (data) {
alert("NOT OK!");
}
});
});
url
url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'),
view
#login_required
def ScanPorts(request):
user = request.user
if request.method == 'POST':
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
return HttpResponse('')
Is the ajax request not set properly?
Assuming you are in the "myapp" app, replace:
method: 'POST',
url: 'scan_ports/',
for this:
method: 'POST',
url: '/myapp/scan_ports/',
First check your urls, the url on which you posted is incorrect hence 404 not found error.
Try to define your url in your JS as: {% url 'scan_ports' %} which will search your urls with the name your provided in urls.py
In addition, this may not be a good approach to submit a form via ajax.
Your JS should be something like this:
$('.form-class-name').on('submit', function (e) {
e.preventDefault();
console.log("ajax is called");
$.ajax({
type: $(this).attr('method'),
url: "/url-name/",
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(data) {
alert("Failure");
}
})
}
e.preventDefault() prevents the natural/default action, and prevents from submitting the form twice.
.serialize(), serializes the form data in a json format.
append a "/" before and after your action url.
Your view must return a dictionary as ajax deals with JSON format.
Edit your view like this:
if request.method == "POST":
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
a = {'data':'success'}
return HttpResponse(json.dumps(a))
This will return a dictionary required by the ajax.
Here is my code ,I got response is 200 OK but ajax came to error part
I can't figure it out
My html:
$(".statics").click(function(){
var name = $(this).attr("data-name");
$.ajax({
url: 'statics/',
data: {
'name':name
},
type: 'POST',
async: false,
dataType: 'json',
success: function(dataArr){
console.log("ssss:",dataArr)
if(dataArr == "IS_PASS"){
alert('PASS!');
}else if(dataArr == "NOT_PASS"){
alert('NOT_PASS');
}
},
error: function(ts){
console.log("eeee:",ts)
alert('fail');
},
});
});
My views.py
def statics_r(request):
if request.is_ajax():
name = request.POST['name']
...
if is_pass:
return HttpResponse("IS_PASS")
else:
return HttpResponse("NOT_PASS")
And the console is : eeee: Object {readyState: 4, responseText: "NOT_PASS", status: 200, statusText: "OK"}
Why it is not success???
For an ajax response, you should be returning json, the easiest way is to use the JsonResponse class instead of HttpResponse, or set the content_type
HttpResponse("{'result': 'IS_PASS'}", content_type="application/json")
You would need to adjust your success function to access the results, i.e dataArr.result