基于Django类的视图中的URL参数和逻辑(TemplateView)

时间:2013-04-02 00:26:29

标签: python django django-class-based-views

我不清楚在Django 1.5中如何最好地访问基于类的视图中的URL参数。

请考虑以下事项:

查看:

from django.views.generic.base import TemplateView


class Yearly(TemplateView):
    template_name = "calendars/yearly.html"

    current_year = datetime.datetime.now().year
    current_month = datetime.datetime.now().month

    def get_context_data(self, **kwargs):
        context = super(Yearly, self).get_context_data(**kwargs)
        context['current_year'] = self.current_year
        context['current_month'] = self.current_month
        return context

URL配置:

from .views import Yearly


urlpatterns = patterns('',
    url(
        regex=r'^(?P<year>\d+)/$',
        view=Yearly.as_view(),
        name='yearly-view'
    ),
)

我想在我的视图中访问year参数,因此我可以执行以下逻辑:

month_names = [
    "January", "February", "March", "April", 
    "May", "June", "July", "August", 
    "September", "October", "November", "December"
]

for month, month_name in enumerate(month_names, start=1):
    is_current = False
    if year == current_year and month == current_month:
        is_current = True
        months.append({
            'month': month,
            'name': month_name,
            'is_current': is_current
        })

如何最好地访问CBV中的url参数,如上面TemplateView的子类,并且理想情况下应该在哪里放置逻辑,例如。在一个方法?

5 个答案:

答案 0 :(得分:95)

要访问基于类的视图中的网址参数,请使用self.argsself.kwargs,以便您通过self.kwargs['year']

访问它

答案 1 :(得分:47)

如果你传递这样的URL参数:

http://<my_url>/?order_by=created

您可以使用self.request.GET(在self.argsself.kwargs中未显示)在基于课程的视图中访问它:

class MyClassBasedView(ObjectList):
    ...
    def get_queryset(self):
        order_by = self.request.GET.get('order_by') or '-created'
        qs = super(MyClassBasedView, self).get_queryset()
        return qs.order_by(order_by)

答案 2 :(得分:20)

我找到了这个优雅的解决方案,对于django 1.5或更高版本,正如here指出的那样:

  

Django基于泛型类的视图现在自动包含一个视图   变量在上下文中。此变量指向您的视图对象。

在views.py中:

from django.views.generic.base import TemplateView    

class Yearly(TemplateView):
    template_name = "calendars/yearly.html"
    # No here 
    current_year = datetime.datetime.now().year
    current_month = datetime.datetime.now().month

    # dispatch is called when the class instance loads
    def dispatch(self, request, *args, **kwargs):
        self.year = kwargs.get('year', "any_default")

    # other code

    # needed to have an HttpResponse
    return super(Yearly, self).dispatch(request, *args, **kwargs)

question中找到的调度解决方案 由于view已在模板上下文中传递,因此您并不需要关心它。在您的模板文件annual.html中,可以通过以下方式访问这些视图属性:

{{ view.year }}
{{ view.current_year }}
{{ view.current_month }}

您可以保持您的urlconf

值得一提的是,将信息添加到模板的上下文中会覆盖get_context_data(),因此它会以某种方式破坏django的操作bean 流。

答案 3 :(得分:8)

到目前为止,我只能从get_queryset方法中访问这些url参数,尽管我只尝试使用ListView而不是TemplateView。我将使用url param在对象实例上创建一个属性,然后在get_context_data中使用该属性来填充上下文:

class Yearly(TemplateView):
    template_name = "calendars/yearly.html"

    current_year = datetime.datetime.now().year
    current_month = datetime.datetime.now().month

    def get_queryset(self):
        self.year = self.kwargs['year']
        queryset = super(Yearly, self).get_queryset()
        return queryset

    def get_context_data(self, **kwargs):
        context = super(Yearly, self).get_context_data(**kwargs)
        context['current_year'] = self.current_year
        context['current_month'] = self.current_month
        context['year'] = self.year
        return context

答案 4 :(得分:3)

如何使用Python装饰器使其易于理解:

class Yearly(TemplateView):

    @property
    def year(self):
       return self.kwargs['year']