Django - Calling one class method from another in Class Based View

Undefined Variable

I have a method inside a django class based view like called get_player_stats. From this method I want to call another method in the same class but I am unable to. Code is like below:

class ScoreView(TemplateView):

   def get_player_stats(request):
       player_id = request.GET.get(player_id, None)
       # compute  player stats

       #here I want to call like below:
       self.get_team_stats(player_id)

   def get_team_stats(self, player_id):
      #compute team stats

When I run this it says name 'self' is not defined

If I try def get_player_stats(self, request): it says missing 1 required positional argument: 'request'

If I try def get_player_stats(request, self): it says missing 1 required positional argument: 'self'

How can I call get_team_stats from get_player_stats?

This is very frustrating, any help is greatly appreciated

P.S: I call get_player_stats as an ajax call by defining a URL path as below:

url('score/get_player_stats', views.ScoreView.get_player_stats)

Then I call it using $.ajax with url: '/score/get_player_stats'

Alex Yu

I see here 2 problems:

  1. Misconceptions about class-based views in django
  2. Misconceptions about object- and class- methods in python

Let's look in more detail.

1. Django class-based views

It must be sound strange (especially for newcomers) but class-based view in django does not means that you bind methods of objects/classes to url-routes.

More so:

  • django.urls.path can use only functions of fn(request, *args, **kwargs)

  • Pythonic it's better explicite for self-param makes object-methods unusable for views (at least without "special magic").

So what the meaning of class-based views?

https://github.com/django/django/blob/2bc014750adb093131f77e4c20bc17ba64b75cac/django/views/generic/base.py#L48

In fact it's very simple:

  1. class-based view expose class method as_view
  2. as_view is a high-order function and not used directly in path/url calls.
  3. as_view constructs actual view function at runtime
  4. generated function is not very complicated too. Roughly speaking, it looks for existence of defined get/post/put/head-methods, calls them when they exists and raises exceptions when not exists.

So you can see that "one does not simply binds methods of class-view to url-routes in django".

It is a tool that can be hardly recommended for general cases, it works good in cases when this inflexibility is desirable.

2. object-,class-, static- methods

OK. Now the second problem.

Can we call from methods of class-based view other methods?

Yes we can but with some restrictions.

Let's look at one-file demo in django 2.0. (For 1.11 - %s/path/url/g)

from django.urls import path    
from django.http import HttpResponse
from django.utils.decorators import classonlymethod


# CASE 1: normal function - OK
def just_a_fun(request, **kwargs):
    context = kwargs if kwargs else {"method": "just a function"}
    return HttpResponse('method = %(method)s' % context)


class ViewClass(object):
    def get(self, request, **kwargs):
        return just_a_fun(request, **kwargs)

    # CASE 2: Object method - FAIL, not possible to use in `django.url.path`-calls
    def om_view(self, request):
        return self.get(request, **{"method": "object method"})

    # CASE 3: class method - OK
    @classmethod
    def cm_view(cls, request):
        return cls.get(cls, request, **{"method": "class method"})

    # CASE 4: static method - FAIL, not possible to call `cls.get` or `self.get`
    @staticmethod
    def sm_view(request):
        self = None  # This is a problem with static methods
        return self.get(self, request, **{"method": "static method"})

    # CASE 5: HOF-view, similar to django.views.generic.View.as_view - OK
    @classonlymethod
    def as_view(cls, **initkwargs):
        def view(request, **kwargs):
            self = cls(**initkwargs)  # Object construction
            self.request = request
            self.kwargs = kwargs
            return self.get(request, **{"method": "HOF as_view"})

        return view


urlpatterns = [
    path("just-a-fun", just_a_fun),  # OK
    path("object-method",
         ViewClass.om_view),  # Problem: redundant `self` for `path`
    path("class-method", ViewClass.cm_view),  # OK
    path('static-method',
         ViewClass.sm_view),  # Problem: not possible to call `get`
    path('hof-view', ViewClass.as_view()),  # OK. 
]

Summary:

  1. Plain functions are best in general
  2. Object methods are not usable (at least without some "special magic")
  3. Class methods: have no problems. But keep in mind that class methods can use only other class methods
  4. Static methods: OK for using in path/url calls but they can't use other methods of classes
  5. If you really really want to use OOP: you can do it in "django way" - create HOFs that will generate actual views functions at runtime. Look at django.views.generic source code for inspiration

...

I hope that must clear things up but questions, critique, corrections - you are welcome!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Javascript

Calling a method from another method in the same class

From Java

Calling one method from another within same class in Python

From Java

Calling method of Another class from run() method

From Java

java calling a method from another class

From Java

Calling service method from another service class

From Java

Using a method from one class into another class

From Java

NullPointerException when calling method from another class

From Dev

Python Inherit from one class but override method calling another class?

From Dev

Calling a special (non-HTTP) URL from the form_valid method of a Django class-based view

From Dev

Django Calling Class Based Mixin from Another Class Based Mixin

From Dev

calling render method from another class

From Dev

Reverse from POST method in django class based view (DetailView)

From Dev

Calling a class from another class with main method

From Dev

How do I return the result of a class-based view from another class-based view in Django?

From Dev

Undefined Method - Calling a class in one file from another

From Dev

Calling method from another class unsuccessful

From Dev

Calling a method from inside of another class

From Dev

Python: Calling a decorator method from another class

From Dev

Calling a method of the MainActivity from another class?

From Dev

coffeescript class - calling calling one class method from an other

From Dev

Calling function from one class in another class

From Dev

calling method in mainactivity from another class in android

From Dev

Calling a method from one class in another class

From Dev

JGroups RpcDispatcher calling method from another class

From Dev

Using a method from one class in another class

From Dev

Calling a list from one method to another in the same class in Python

From Dev

Kivy - Calling a pulsing method from one class to another

From Dev

Method returning from one class to another class

From Dev

Django: How to reference a context variable created in one class-based view from another class-based view

Related Related

  1. 1

    Calling a method from another method in the same class

  2. 2

    Calling one method from another within same class in Python

  3. 3

    Calling method of Another class from run() method

  4. 4

    java calling a method from another class

  5. 5

    Calling service method from another service class

  6. 6

    Using a method from one class into another class

  7. 7

    NullPointerException when calling method from another class

  8. 8

    Python Inherit from one class but override method calling another class?

  9. 9

    Calling a special (non-HTTP) URL from the form_valid method of a Django class-based view

  10. 10

    Django Calling Class Based Mixin from Another Class Based Mixin

  11. 11

    calling render method from another class

  12. 12

    Reverse from POST method in django class based view (DetailView)

  13. 13

    Calling a class from another class with main method

  14. 14

    How do I return the result of a class-based view from another class-based view in Django?

  15. 15

    Undefined Method - Calling a class in one file from another

  16. 16

    Calling method from another class unsuccessful

  17. 17

    Calling a method from inside of another class

  18. 18

    Python: Calling a decorator method from another class

  19. 19

    Calling a method of the MainActivity from another class?

  20. 20

    coffeescript class - calling calling one class method from an other

  21. 21

    Calling function from one class in another class

  22. 22

    calling method in mainactivity from another class in android

  23. 23

    Calling a method from one class in another class

  24. 24

    JGroups RpcDispatcher calling method from another class

  25. 25

    Using a method from one class in another class

  26. 26

    Calling a list from one method to another in the same class in Python

  27. 27

    Kivy - Calling a pulsing method from one class to another

  28. 28

    Method returning from one class to another class

  29. 29

    Django: How to reference a context variable created in one class-based view from another class-based view

HotTag

Archive