'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view in Django RestFramework
I'm trying to return a response after the execution of loop but I'm getting an error as
AssertionError at Data/CurrentRunningActivityForAudit/10
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response
`
views.py:
def CurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
result_set = cursor.fetchall()
IsActive = 'true'
for row in result_set:
data = []
data.append({
'TaskId':row[0],
'TaskName' : row[1],
'Source' : row[2],
'Requester' : row[3],
'type' : row[4],
'IsActive':IsActive,
})
return Response(data[0], status=status.HTTP_200_OK)
when I move the return response outside the loop it shows as local variable 'data' referenced before assignment
Solution 1:[1]
Try this:
def CurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
result_set = cursor.fetchall()
IsActive = 'true'
data = []
for row in result_set:
data.append({
'TaskId': row[0],
'TaskName' : row[1],
'Source' : row[2],
'Requester' : row[3],
'type' : row[4],
'IsActive': IsActive,
})
return Response(
data[0] if data else [],
status=status.HTTP_200_OK
)
Solution 2:[2]
You've to change your code like this
def CurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
result_set = cursor.fetchall()
IsActive = 'true'
data = [] # changed
for row in result_set:
data.append({
'TaskId':row[0],
'TaskName' : row[1],
'Source' : row[2],
'Requester' : row[3],
'type' : row[4],
'IsActive':IsActive,
})
return Response(data[0], status=status.HTTP_200_OK)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mahrus Khomaini |
Solution 2 |