开发者

Is there a way to pass a variable to a generic view in Django?

I am using Django's generic views and trying to find a way to filter a list of articles using D.R.Y.

My current urls.py file (only relevant section):

all_articles = {
    'queryset'      :   Article.objects.all(),
    'template_name' :   'article/admin.html'
}

url(r'^admin/$', object_list, all_articles, 'admin_article_home'),

I want do to something like the following, but without all the seemingly redundant code:

filter_status_draft = {
'queryset'      :   Article.objects.filter(status = 'Draft'),
'template_name' :   'article/admin.html'
}

filter_status_scheduled = {
'queryset'      :   Article.objects.filter(status = 'Scheduled'),
'template_name' :   'article/admin.html'
}

url(r'^admin/filter/status/draft/$', object_list, filter_status_draft, 'admin_article_status_filter_draft'),
url(r'^admin/filter/status/schedul开发者_如何学Ced/$', object_list, filter_status_scheduled, 'admin_article_status_filter_scheduled'),

It seems there has to be a more efficient way to do this.

I have already viewed this answer, but it seems like creating a view defeats most of the purpose of a generic url.

Is there no way to do something as simple as this?


If you don't want to write your own views, another way you could do this is by writing custom model managers. So you'd write you urls.py like:

filter_status_draft = {
    'queryset'      :   Article.objects.drafted(),
    'template_name' :   'article/admin.html'
}

filter_status_scheduled = {
    'queryset'      :   Article.objects.scheduled(),
    'template_name' :   'article/admin.html'
}

Check documentation on writing custom model managers for more info.

However, writing views, especially now when views are class-based, is a much more flexible and DRY approach in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜