Django get_total_topup() missing 1 required positional argument: 'request' - django

class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup()
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})
somebody can help me ? I want to get data via ajax, but the response is 500 with message get_total_topup() missing 1 required positional argument: 'request'

Your call in return self.get_total_topup() has no arguments but your definition def get_total_topup(self, request) requires one. Try return self.get_total_topup(request).
class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup(request) # <--- just change this
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})

You are missing one positional argument in the method call.
return self.get_total_topup()
Fix it to
return self.get_total_topup(request)

Related

Strange TyperError put() missing 1 required positional argument: 'path'

I've been trying to test my PUT method in the following APITestcase:
def test_story_delete(self):
c = APIRequestFactory
user = User.objects.get(username='test1')
payload = {'storyName': 'changetest'}
request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json')
force_authenticate(request,user=user)
My URL:
path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'),
And I'm keep receiving this error:
TypeError: put() missing 1 required positional argument: 'path'
I don't understand what is going on because i declared the path inside request. Can someone help me?
Edit: sharing the view that I'm testing
class APIstory(APIView):
permission_classes = [IsAuthenticated]
def put(self,request, pk, idStory):
data = self.request.data
pk = self.kwargs['pk']
id = self.kwargs['idStory']
name = data['storyName'].strip()
if name == "" or str.isspace(name) or len(name) < 4:
return Response({"error": "minimum of 4 words"}, status=400)
if PokerRoom.objects.filter(id=pk).exists():
session = PokerRoom.objects.filter(id=pk)
if session[0].status == 'Finished':
return Response({'error': 'Session already ended'}, status=400)
else:
session = PokerRoom(id=pk)
if Story.objects.filter(id=id, idRoom=session).exists():
if not Story.objects.filter(idRoom=session, storyName=name).exists():
for hist in Story.objects.filter(id=id, idRoom=session):
if hist.status == 'Pending':
if hist.storyName == name:
return Response({'error':'story with the same name'}, status=400)
hist.storyName = name
hist.save()
status = hist.status
body = {"id":id,"storyName":name,"status":status}
message_socket("STORY_UPDATE", pk, body)
return Response({'success': 'story {} edited, status is {}.'.format(hist.id,hist.status)})
else:
return Response({'error': 'story already ended'}, status= 400)
else:
return Response({'error': 'story with the same name'}, status= 400)
return Response({'error': 'session doesnt exists.'}, status=400)
else:
return Response({'error': 'session doesnt exists.'}, status=400)
Edit2: I was forgetting to put the body in my request, but now I'm getting the following error: TypeError: super(type, obj): obj must be an instance or subtype of type
Shouldn't you add the request body also in a put request?
Something like this?
request = c.put(reverse('storyFunctions', kwargs={'pk': self.room.pk, 'idStory': self.story.pk}), payload, format='json')
As per the docs

call the function response in another function in Django RestFramework

I tried calling the another function inside the function which will return the response.I have tried this approach but couldn't able to achieve it.
I'm just getting error as
AssertionError at /api/Data/CurrentRunningActivity2/54
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
views.py:
#api_view(['GET'])
def CurrentRunningActivityView2(request, UserID):
if request.method == 'GET':
CurrentRunningActivity(UserID)
def CurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] #UserId=%s',(UserID,))
result_set = cursor.fetchall()
for row in result_set:
TaskId=row[0]
Number=row[1]
Opened=row[2]
Contacttype=row[3]
Category1=row[4]
State=row[5]
Assignmentgroup=row[6]
CountryLocation=row[7]
Openedfor=row[8]
Employeenumber=row[9]
Shortdescription=row[10]
Internaldescription=row[11]
Additionalcomments=row[12]
TaskName = row[1]
print("Number", Number)
return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype,
"Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation,
"Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription,
"Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK)
Put return statement in the CurrentRunningActivityView2 to return the Response from CurrentRunningActivity. Otherwise it won't return the Response from the second function.
#api_view(['GET'])
def CurrentRunningActivityView2(request, UserID):
if request.method == 'GET':
return CurrentRunningActivity(UserID)

Local variable 'cid' referenced before assignment

Im trying to add a payment method.
I also add Getway and Get Success Message.
Now I want to show success message with cid and name in my template page.
When I want to get context data, I got This Error.
** Local variable 'cid' referenced before assignment. **
My code:
class CheckoutSuccessView(View):
model = Transaction
template_name = 'success.html'
def get(self, request, *args, **kwargs):
# return render(request, self.template_name,{'transaction':transaction})
return HttpResponse('nothing to see')
def post(self, request, *args, **kwargs):
data = self.request.POST
try:
Transaction.objects.create(
name = data['value_a'],
cid = data['value_b'],
tran_id=data['tran_id'],
val_id=data['val_id'],
amount=data['amount'],
card_type=data['card_type'],
card_no=data['card_no'],
...
...
)
messages.success(request,'Payment Successfull')
name = data['value_a'],
cid = data['value_b'],
except:
messages.success(request,'Something Went Wrong')
context = {
'cid': cid,
'name' : name
}
return render(request, 'success.html', context)
You may miss block or put extra indentation.
Define it before try block.
You may try this:
class CheckoutSuccessView(View):
model = Transaction
template_name = 'success.html'
def get(self, request, *args, **kwargs):
# return render(request, self.template_name,{'transaction':transaction})
return HttpResponse('nothing to see')
def post(self, request, *args, **kwargs):
data = self.request.POST
name = data['value_a'],
cid = data['value_b'],
try:
Transaction.objects.create(
name = data['value_a'],
cid = data['value_b'],
tran_id=data['tran_id'],
val_id=data['val_id'],
amount=data['amount'],
card_type=data['card_type'],
card_no=data['card_no'],
...
...
)
messages.success(request,'Payment Successfull')
except:
messages.success(request,'Something Went Wrong')
context = {
'cid': cid,
'name' : name
}
return render(request, 'success.html', context)
I think you are using sslcommerz-lib for SSLCOMMERZ PAYMENT GATEWAY.

Pass a custom param in URL with a ModelViewSet

What's the best way of passing a param using a ModelViewSet? Forexample achieving something like this :
http://127.0.0.1:8000/api/v1/financing-settings/template/?param=block
Below is the approach I was using but found out I have set the param in the body section, but it's not what I want :
class TemplateView(ModelViewSet):
"""ViewSet for Saving Block/ Step template."""
def list(self, request, *args, **kwargs):
"""Get list of Block/Steps with is_process_template is equal to True."""
param = request.data['param']
if param == "block":
_block = Block.objects.filter(is_process_template=True).values()
return JsonResponse({"data": list(_block)}, safe=False, status=200)
elif param == "step":
_step = Step.objects.filter(is_process_template=True).values()
return JsonResponse({"data": list(_step)}, safe=False, status=200)
return Response(status=status.HTTP_204_NO_CONTENT)
param = request.GET.get('param')
or for a post request
param = request.POST.get('param')
param = request.query_params.get('param')

method() takes 1 positional argument but 2 were given in pagination decorator action

I have a problem doing a paginator about an action decorator in django rest framework and I can't find the solution, the question is that it gives me the following error:
get_response_data () takes 1 positional argument but 2 were given
class InterfacesViewSet(viewsets.ModelViewSet):
queryset = Interfaces.objects.all()
serializer_class = InterfaceSerializer
pagination_class = PostPageNumberPagination
def get_response_data(paginated_queryset):
data =[ {
'id_interface': interface.id_interface,
'id_EquipoOrigen': interface.id_EquipoOrigen_id,
'EquipoOrigen': interface.id_EquipoOrigen.nombre,
'LocalidadOrigen': interface.id_EquipoOrigen.localidad,
'CategoriaOrigen': interface.id_EquipoOrigen.categoria,
'id_PuertoOrigen': interface.id_PuertoOrigen_id,
'PuertoOrigen': interface.id_PuertoOrigen.nombre,
'estatus': interface.estatus,
'etiqueta_prtg': interface.etiqueta_prtg,
'grupo': interface.grupo,
'if_index': interface.if_index,
'bw': interface.bw,
'bw_al': interface.bw_al,
'id_prtg': interface.id_prtg,
'ospf': interface.ospf,
'description': interface.description,
'id_EquipoDestino': interface.id_EquipoDestino_id,
'EquipoDestino': interface.id_EquipoDestino.nombre,
'LocalidadDestino': interface.id_EquipoDestino.localidad,
'CategoriaDestino': interface.id_EquipoDestino.categoria,
'id_PuertoDestino': interface.id_PuertoDestino_id,
'PuertoDestino': interface.id_PuertoDestino.nombre,
'ultima_actualizacion': interface.ultima_actualizacion,
} for interface in queryset]
return data
#action(methods=['get'], detail=False, url_path='registros-data-table',
url_name='registros_data_table')
def registros_data_table(self, request):
queryset = Interfaces.objects.all()
page = self.paginate_queryset(queryset)
if page is not None:
data = self.get_response_data(page)
return self.get_paginated_response(data)
data = self.get_response_data(queryset)
return Response(data)
Function get_response_data expects 1 positional argument, but you are calling it with two - the object self and list page.
data = self.get_response_data(page)
Here is a shorter example code showing this issue:
class Example:
def test(*args):
print(args)
def run(self):
self.test("my string")
Example().run()
# (<__main__.Example object at 0x10320b160>, 'my string')
To fix this issue, you can change the function signature to include self positional argument:
def get_response_data(self, paginated_queryset):