1
votes
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

2
Where do you think it should get self from? - Ignacio Vazquez-Abrams
you are using self before __init__ is called. - Amelia

2 Answers

3
votes

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.

3
votes

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.