1

I have a view :

def add_view(request):
    if request.method == "POST":

        files = request.FILES.getlist("file")
        response_data = {}

        for file in files:
            my_model = MyModel()
            my_model.my_file = file
            my_model.save()
            id_info = my_model.id
            response_data.append(id_info)

    return HttpResponse(json.dumps(response_data), content_type="application/json")

Here lets say if there are 5 files then I want to send the id of 5 file in response through json. Here its saying local variable response_data referenced before assignment.

I want to send the id of all 5 files. How to do this ?

gamer
  • 5,673
  • 13
  • 58
  • 91

1 Answers1

3

First you are defining response_data = {} inside the if and your return response is outside, because that you are getting response_data referenced before assignment error.

Second, a dict has not append() method. You should declare your responde_data as a list

def add_view(request):
    response_data = []
    if request.method == "POST":

        files = request.FILES.getlist("file")


        for file in files:
            my_model = MyModel()
            my_model.my_file = file
            my_model.save()
            id_info = my_model.id
            response_data.append(id_info)

    return HttpResponse(json.dumps(response_data), content_type="application/json")
levi
  • 22,001
  • 7
  • 73
  • 74
  • what if I use dict. Using list will give me data in correct json format ? – gamer Mar 25 '15 at 20:14
  • @gamer python list are json serializable, but is you want a dict, just wrapp it using {} `json.dumps({'response_data':response_data})` – levi Mar 25 '15 at 20:32