Monday, March 29, 2021

Hello mates

Im catching a model in a select, using ajax to request, so Im receiving an error I can,t solve
Im get an empty dict, the error is :
error: "'str' object has no attribute 'toJSON'".
Its occurrs when  I try to print  the data in console
I created a function into the model to convert this in dict, late I define the view  and create the ajax function. You will see the code below:
Thanks in advance

MODEL
from django.forms import model_to_dict

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})


VIEW
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(item_name__icontains=request.POST['term'])
              
                for i in prods:
                    item = i.toJSON()
                    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')



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);
            console.log(data);
        }).fail(function (jqXHR,textStatus, errorTrown){
        alert(errorTrown);
        }).always(function(data){

        });

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

}
});

--
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/99d4f2af-9d65-41bc-9c32-054822115b80n%40googlegroups.com.

No comments:

Post a Comment