Question

urls.py

url(r'^customer/(?P<name>[^\s]+)/$', customerDetailView.as_view(), name="customerDetailView"), #pass 'name' variable

and

views.py

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

    def __init__(self, name=None, *args):
        self.name = name # name is 'None'... Why...?

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

I just request '192.168.1.5/customer/abc/', but 'name' is none...

How to receive 'name'? What should I do?

edit-----

views.py

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True
    """
    def __init__(self, **kwargs):
        import pdb;pdb.set_trace()
        self.name = kwargs['name']
    """
    def get_queryset(self):
        # import pdb;pdb.set_trace()
        self.name = self.kwargs['name'] # Thanks  Kay Zhu!!
        return Customer.objects.get(name=self.name)

I apply code you answered.

Then, I get a error

Generic detail view customerDetailView must be called with either an object pk or a slug.

So I need 'pk'...

What should I do?

Was it helpful?

Solution

You should be able to access the parameter with self.kwargs['name']. Further, get_queryset should return a queryset instead.

You also need to use pk instead of name in your URL if you want to use DetailView generic view. After that you only need to define model = Customer and slug_field = 'name' in your customerDetailView class and it should work. You do not need to access self.kwargs['name'] at all. [source]

If you really want to use <name> in your URL, you also need to change slug_url_kwarg to name (in addition to slug_field = 'name':

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True
    model = Customer
    slug_field = 'name'
    slug_url_kwarg = 'name'
    # no need to override any methods here

or override get_object by:

def get_object(self):
    return get_object_or_404(Customer, name=self.kwargs['name'])

without modifying slug_field and slug_url_kwarg in your class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top