Checking the type of an argument in Django Python views

Viewed 28

I have more experience with C (intermediary expertise) and now working on something in Django Python.

I have a url function which directs a REST call to a views function. Now, I am trying to make a single url for passing an argument for both an ID (int) and an email (str/EmailField) to land on the same views function and I can then unpack the type of the arg sent and do something different.

I want the url to be argument type agnostic and then do the conditional check in the views function. But it looks like each time, the argument is sent as a str (even when the id is sent).

I believe there may be 2 things here I do not fully understand: perhaps the argument will always be sent to the view function as a str all the time? Or there may be an issue with my type checking (as you can see I am trying to cast the type of the arg and check if true. Seems more like a C method of doing stuff?

Thank you!

urls.py looks like

path('<arg>/', views.getUpdateDeleteAccount), ->> this is what I am trying to do
#path('<int:pk>/', views.getUpdateDeleteAccount), ->>> works in isolation
#path('<str:email>/', views.getUpdateDeleteAccount), -->>> works in isolation

view.py looks like

@api_view(['GET', 'PUT', 'DELETE'])
def getUpdateDeleteAccount(request, arg):
    if type(int(arg)) is int:
        print("account id search, arg type is ")
        print(type(arg))
        try:
            account = Account.objects.get(id=arg)
        except Account.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    elif type(EmailField(arg)) is EmailField:
        print("email add search, arg type is ")
        print(type(arg))
        try:
            account = Account.objects.get(emailAddress=arg)
        except Account.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
1 Answers

Seems to be working now.

But a few things I have since realised. EmailField is probably not even a valid Python type to begin with!

Secondly, I have corrected the type checking (which was probably wrong in the first place).

Lastly, modified the url.py to look like this now:

urls.py

path('<int:arg>/', views.getUpdateDeleteAccount),
path('<str:arg>/', views.getUpdateDeleteAccount),

views.py

def getUpdateDeleteAccount(request, arg):
    """To get, update and delete a single user account"""

    if type(arg) is int:
        try:
            account = Account.objects.get(id=arg)
        except Account.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    elif type(arg) is str:
        try:
            account = Account.objects.get(emailAddress=arg)
        except Account.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Related