Thursday, December 19, 2019

Update value in database

Hi!

I have a real estate django app and i have a form to users insert a new property. I also have in the form several images fields that users can use to upload images to database whitout problem. 
The problem is if the user want to delete one of the images field.

I have an ajax request that sends the id of the property and the field name to update (delete) on database.

function delete_img(i){
              var prim_key = document.getElementById('list_id').value;
              var id_number = i.id;

               $.ajax({
                  type: 'GET',
                  url: '',
                  data: {'csrfmiddlewaretoken' : "{{  csrf_token  }}",'img_id':id_number , 'post_id':prim_key },
                  success: function(data){
                      if(data) {
                       console.log(id_number + " " + prim_key);
                       document.getElementById('img_' + id_number).src = "http://localhost:8000/media/upload_img_default.png";
                      }
           
     
                    }
                });

In views.py i have a function that receives the data from ajax and executes the task.

@csrf_exempt
def delete_img(request):
        if request.method=='GET' and request.is_ajax():
            img_id = request.GET['img_id']
            post_id = request.GET['post_id']
            try:
                obj = Listing.objects.get(id=post_id)
                obj1 = getattr(obj,img_id) 
                obj1.value = None
                obj.save()
                return True
            except Listing.DoesNotExist:
                return False
        else:
            return False


Can anyone help me with this situation?
Thanks for your help.

--
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/9cb23263-95e4-4060-b855-09a0e30cb89d%40googlegroups.com.

No comments:

Post a Comment