Saturday, March 27, 2021

hi mates trouble with ajax 500 error server

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

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9c63de9e-04b3-41a7-b878-3111e13c7c0dn%40googlegroups.com.

No comments:

Post a Comment