从URL获取参数slug

1 投票
3 回答
1770 浏览
提问于 2025-04-18 00:48

我想从网址中提取两个参数,以便添加到我的上下文中。

这是网址:

  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'] 等等,我到底哪里做错了呢?

3 个回答

1

基本类(View)的 as_view 类方法其实是一个简单的闭包,它围绕着一个叫 view 的函数,这个函数会接受在 urls.py 文件中定义的参数。然后,它会把这些参数作为一个字典赋值给视图类的 self.kwargs 属性。所以,如果你想访问这些数据,你只需要这样做:

self.kwargs['company']

另外,如果你的 RegistrationView 是从 CreateView 继承的,而不是从 BaseCreateView 继承的,那么你的视图中会混合进 SingleObjectTemplateResponseMixin。这样的话,slug_field(还有 modelqueryset)就会被 get_object 方法用来获取你想要的公司。而且,包含 Company 实例的上下文变量 company 会自动为你设置好,你就不需要自己去设置了。

2

试试这个

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

这里有一个链接,里面有关于Django类视图的参考资料,帮助你理解如何将额外的参数传递给as_view()方法。

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

撰写回答