简体   繁体   English

Django URL变量未通过

[英]Django url variable not passing

I'm trying to get a variable from url and display it in template using django. 我正在尝试从url获取一个变量,并使用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: 我的urls.py看起来像这样:

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

Now, here's views.py 现在,这里是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. 所以我在这里传递bucketName变量,但是当页面打开时,我得到“ None”而不是变量名。 Here's the bucket.html: 这是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. 谢谢。

self.request.GET holds variables from the querystring, eg if you did /bienbox/bucket/?bucket=mybucket . self.request.GET保存查询字符串中的变量,例如,如果您执行过/bienbox/bucket/?bucket=mybucket

In your case, you can get the bucket name from self.kwargs . 就您而言,您可以从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. 使用基于类的视图时,请尽量避免覆盖getpost 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM