Home > Enterprise >  django the request argument must be an instance of django.http.HttpRequest
django the request argument must be an instance of django.http.HttpRequest

Time:07-15

I'm importing a service function from django views function and getting this error

'The `request` argument must be an instance of `django.http.HttpRequest`, not `collections.OrderedDict`.'

I have used the same implementation in other modules too and those are working fine.

from custom_label.services.custom_label_svc import update_label

@api_view(["POST"])
@authorize
def update_label(request) -> JsonResponse:
    try:
        payload = ValidateUpdateLabel(data=request.data)
        if payload.is_valid():
            # call service methods
            data = update_label(payload.validated_data) << here

            ...

In custom_label > services > custom_label_svc.py file:

from basic_files.database_connections import connect_to_postges

cursor = connect_to_postges()


def update_label(params: dict) -> dict:
    app_id = params.get('appid')
    label_name = params.get('label_name')
    updated_label_icon = params.get('updated_label_icon')

    sql = "UPDATE label SET icon = %s  WHERE appId = %s AND name = %s" % (updated_label_icon, app_id, label_name)
    cursor.execute(sql)

    return cursor.rowcount

What am I missing here?

CodePudding user response:

The reason this fails is because you have two functions that have the same name, so it will call the update_label that you defined in the name.

You can fix this by importing the function with a different name, so:

from custom_label.services.custom_label_svc import update_label as update_label_logic

@api_view(['POST'])
@authorize
def update_label(request) -> JsonResponse:
    try:
        payload = ValidateUpdateLabel(data=request.data)
        if payload.is_valid():
            # call service methods
            data = update_label_logic(payload.validated_data)
    # …

But wrapping the entire logic in a try-except is usually not a good idea. Furhtermore your function is vulnerable to SQL injection.

  • Related