1
class customerDetailView(DetailView):
    queryset = Customer.objects.get(name=self.name) # This line give error NameError: name 'self' is not defined
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True

    def __init__(self, name=None, *args):
        self.name = name

gives an error NameError: name 'self' is not defined

chobo
  • 4,830
  • 5
  • 23
  • 36

2 Answers2

4

Since you're wanting to customize a DetailView's queryset, the correct way to do this is override the get_queryset() function. See the documentation for DetailView which shows the method resolution order. In particular, get_queryset() is called.

So your code would become this:

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True

    def __init__(self, name=None, *args):
        self.name = name

    def get_queryset(self):
        return Customer.objects.get(name=self.name)

You cannot use self in the manner you are because a self does not exist at class declaration, only when an instance of the class is created.

Austin Phillips
  • 15,228
  • 2
  • 51
  • 50
3

You should be putting your init code inside __init__, not the Class body:

class CustomerDetailView(DetailView):
    def __init__(self, name=None):
        self.name = name
        self.queryset = Customer.objects.get(name=self.name, None)
        self.context_object_name = 'customerDetail'
        self.template_name = "customer.html"
        self.allow_empty = True
    # stuff

Also, as an unrelated sidenote, your code uses a mix of three different styles. Try reading PEP8.

Amelia
  • 2,967
  • 2
  • 24
  • 39
  • 1
    That's not really correct, most of that code should stay outside of init. See the docs referenced in Austin's answer. – Aidan Ewen Feb 09 '13 at 11:03
  • @AidanEwen ahh, I see now. I'm not massively familiar with django; I answered from a python point of view. – Amelia Feb 09 '13 at 11:32
  • 1
    Love the PEP8 link - I've started using pydevd's PEP8 checker recently - it's an eye opener! – Aidan Ewen Feb 09 '13 at 12:02