Update value in database

15 views
Skip to first unread message

Nuno Vieira

unread,
Dec 19, 2019, 11:50:10 AM12/19/19
to Django users
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.
Reply all
Reply to author
Forward
0 new messages