hi mates trouble with ajax 500 error server

17 views
Skip to first unread message

frank galan

unread,
Mar 27, 2021, 12:38:15 PM3/27/21
to Django users
Im receiving a 500 server error,  when I trying  to obtain data wiith ajax from my model. 
 My details are as follows:
Model:
class Item(models.Model):
    """Items Product model"""
    operation = models.ForeignKey(Operation, on_delete=models.CASCADE)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(SubcategoryItem, on_delete=models.CASCADE)
    categ = models.ForeignKey(CategItem, on_delete=models.CASCADE)
    section = models.ForeignKey(Section, on_delete=models.CASCADE)
    currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
    item_name = models.CharField(max_length=255, verbose_name='item')
    item_description = models.TextField(null=True)
    item_SKU = models.CharField(max_length=100, null=False, blank=True)
    ean = models.CharField(max_length=100, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=100, null=True)
    is_active = models.BooleanField()
    price = models.PositiveIntegerField(null=True)
    purchase_price = models.PositiveIntegerField(null=True, blank=True)
    tax = models.PositiveIntegerField(null=True)
    color = models.CharField(max_length=30, null=True)
    size = models.CharField(max_length=3, null=True, blank=True)
    weight = models.CharField(max_length=5, null=True, blank=True)
    height = models.CharField(max_length=5, null=True, blank=True)

    image = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )
    image_1 = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )
    image_2 = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )
    image_3 = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )
    image_4 = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )
    image_5 = models.ImageField(
        upload_to='backoffice/static/images',
        blank=True,
        null=True
    )

    class Meta:
        ordering = ('item_name',)

    def __str__(self):
        return self.item_name

    def toJson(self):
        item = model_to_dict(self)
        item['item_name'] = self.item_name.toJson()
        item['item_description'] = self.item_description.toJson()
        item['item_SKU'] = self.item_SKU.toJson()
        item['operation'] = self.operation.toJson()
        item['brand'] = self.brand.toJson()
        item['subcategory'] = self.subcategory.toJson()
        item['categ'] = self.categ.toJson()
        item['section'] = self.section.toJson()
        item['price'] = format(self.price, '.2f')
        item['purchase_price'] = format(self.purchase_price, '.2f')
        item['tax'] = format(self.tax, '.2f')
        item['weight'] = format(self.weight, '.2f')
        item['height'] = format(self.height, '.2f')
        return item
   
    def get_absolute_url(self):
        return reverse('all_items.html', kwargs={'pk':self.id})


HTML :
<div class="input-group mb-3 col-md-8">
                    <span class="input-group-append">
                      <button  type="button" class="btn btn-danger"><i class="fa fa-search" style="color:#fff" ></i>
                      </button>
                    </span>
                      <input type="text"  id="search_box" name="search_box" class="form-control" value="" placeholder="Find the items you need add to invoice">
                  </div>

Ajax
$('#search_box').autocomplete({
source:function(request, response){
alert(request.term);

$.ajax({
url:window.location.pathname,
type: 'POST',
data: {
'action':'search_item',
'term': request.term
},
dataType:'json',
        }).done(function(data){
        response(data);
            alert('hola');
        }).fail(function (jqXHR,textStatus, errorTrown){
        alert( errorTrown);
        }).always(function(data){

        });

},
delay: 500,
minLength: 1,
select: function(event, ui){
console.log(ui.item);

}
});

Sold.py View

#Creating an invoice instance
class SoldCreate(LoginRequiredMixin, CreateView):
    model = Sold
    form_class = SoldForm
    template_name = 'solds/add_invoice.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tittle'] = 'Sold Forms'
        context['table_tittle'] = 'New sold'
        context['table_subtittle'] = 'Add here your new solds'
        return context
    
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
    
    @method_decorator(csrf_exempt)
    def post(self, request, *args,**kwargs):
        data={}
        try:
            action == request.POST['action']
            if action == 'search_item':
                data = []
            
                prods = Item.objects.filter(name__icontains=request.POST['term'])
              

                for i in prods:
                    item = i.item_description
                    item['value'] = i.item_name
                    data.append(item)

            else:
                data['error']='no ha ingresado una opcion'
        except Exception as e:
            data['error'] = str(e)
    
        return JsonResponse(data, safe=False)
        
    def get_success_url(self):
        return reverse('all_sold')

Thanks a lot in advance

Kasper Laudrup

unread,
Mar 27, 2021, 1:49:51 PM3/27/21
to django...@googlegroups.com
On 27/03/2021 15.13, frank galan wrote:
> Im receiving a 500 server error,  when I trying  to obtain data wiith
> ajax from my model. 

You should look at the server logs or the output from the console. That
should hopefully provide some details on the reason behind the "Internal
Server Error".

Kind regards,

Kasper Laudrup

OpenPGP_signature

frank galan

unread,
Mar 27, 2021, 4:42:49 PM3/27/21
to django...@googlegroups.com
thanks, here is the server error response

Traceback (most recent call last):

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner

    response = get_response(request)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response

    response = wrapped_callback(request, *callback_args, **callback_kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view

    return self.dispatch(request, *args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper

    return bound_method(*args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view

    return view_func(*args, **kwargs)

  File "/Users/blackmaster/Documents/programacion/proyectos_django/localsys/backoffice/views/sold.py", line 49, in dispatch

    return super().dispatch(*args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch

    return super().dispatch(request, *args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch

    return handler(request, *args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper

    return bound_method(*args, **kwargs)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view

    return view_func(*args, **kwargs)

  File "/Users/blackmaster/Documents/programacion/proyectos_django/localsys/backoffice/views/sold.py", line 72, in post

    return JsonResponse(data, safe=False)

NameError: name 'JsonResponse' is not defined

[27/Mar/2021 20:39:37] "POST /dashboard/backoffice/new_sold HTTP/1.1" 500 96481


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b3540a30-7ece-f675-c3eb-710e74065686%40stacktrace.dk.

Kasper Laudrup

unread,
Mar 27, 2021, 7:58:32 PM3/27/21
to django...@googlegroups.com
On 27/03/2021 21.41, frank galan wrote:
> thanks, here is the server error response
>
> NameError: name 'JsonResponse' is not defined
>

That error message should be fairly obvious. You haven't defined
anything called JsonResponse.

You most likely just need to import the correct module. I don't know
what that would be, but it would probably be from the library you use to
generate JSON responses whatever that might be.

Kind regards,

Kasper Laudrup

OpenPGP_signature

frank galan

unread,
Mar 28, 2021, 9:35:23 AM3/28/21
to django...@googlegroups.com
Thanks a lot, you're right. I solved it. Thanks


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages