davidb
davidb

Reputation: 1603

Django url variable not passing

I'm trying to get a variable from url and display it in template using django. Here's the page with the link to the bucket's page:

<div id="left">
   <a href="{% url 'project:bucket' bucket=bucket.bucketName %}"><h4 id='s3ItemName'>{{ bucket.bucketName }}</h4></a>
</div>

This displays the bucket name properly and contains a link to abucket detail page. My urls.py look like this:

url(r'bienbox/bucket/(?P<bucket>\w+)$',views.bucketPage.as_view(),name='bucket')

Now, here's views.py

class bucketPage(TemplateView):
template_name = "project/bucket.html"

def get(self, request, bucket):
    bucketName = request.GET.get('bucket')
    return render(request,self.template_name,{'bucketName': bucketName})

So I'm passing the bucketName variable here, however when the page opens I get "None" instead of the variable name. Here's the bucket.html:

<div class="mainPage">
   <div class="s3Wrapper">
      <h2>{{ bucketName }}</h2>
   </div>
</div>

What am I doing wrong? Why is the variable not passed? Thanks.

Upvotes: 0

Views: 50

Answers (1)

Alasdair
Alasdair

Reputation: 308839

self.request.GET holds variables from the querystring, e.g. if you did /bienbox/bucket/?bucket=mybucket.

In your case, you can get the bucket name from self.kwargs.

def get(self, request, *args, **kwargs):
    bucketName = self.kwargs['bucket']
    return render(request,self.template_name,{'bucketName': bucketName})

Try to avoid overriding get or post when you use class based views. In this case you could do:

class bucketPage(TemplateView):
    template_name = "project/bucket.html"

    def get_context_data(self, *args, **kwargs):
        context = super(bucketPage, self).get_context_data(**kwargs)
        context['bucketName'] = self.kwargs['bucket']
        return context

Upvotes: 3

Related Questions