【问题标题】:Get parameters slugs from the URL从 URL 获取参数 slugs
【发布时间】:2014-05-12 00:46:42
【问题描述】:

我正在尝试从 URL 中获取两个参数以添加到我的上下文中。

这是网址:

  url(r'^company/(?P<company>[\w\-\_]+)/?/(?P<program>[\w\-\_]+)/?$', RegistrationView.as_view(),
                       name='test'), 

观点:

class RegistrationView(RegistrationMixin, BaseCreateView):
    form_class = AppUserIntroducerCreateForm
    template_name = "registration/register_introducer.html"
    slug_field = 'company'



    def get_context_data(self, *args, **kwargs):
        context = super(RegistrationIntroducerView, self).get_context_data(**kwargs)
        print(self.get_slug_field())
        context['company'] = ??????
        context['program'] = ??????
        return context

我已经尝试了一切来获取值self.companykwargs['company'] 等,我在这里做错了什么?

【问题讨论】:

标签: python django


【解决方案1】:

基类 (View) 的 as_view 类方法是一个非常简单的 view 函数的闭包,它接受 urls.py 中定义的参数。然后它将它们作为字典分配给视图类的self.kwargs 属性。因此,为了访问这些数据,您需要做的是:

self.kwargs['company']

此外,如果您从 CreateView 继承 RegistrationView 而不是 BaseCreateView,您会得到 SingleObjectTemplateResponseMixin 与您的视图和 slug_field 混合在一起(以及 modelquerysetget_object 方法将使用它来获取所需的公司。此外,包含Company 实例的上下文变量company 已经为您设置好了,您不必自己设置。

【讨论】:

    【解决方案2】:

    试试这个

    self.kwargs['company']
    self.kwargs['program']
    

    【讨论】:

      【解决方案3】:

      Here 是您的参考。

      context = super(RegistrationView, self).get_context_data(**kwargs)
      print(self.get_slug_field())
      context['company'] = self.kwargs['company']
      context['program'] = self.kwargs['program']
      

      【讨论】:

      • 看在皮特的份上!我都试过了。成功了,谢谢。
      猜你喜欢
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2012-06-23
      相关资源
      最近更新 更多