我正在尝试使用django做一些简单易行的事情:
对项目列表进行分页。
所以,我有一个文章页面,我想每页最多显示10篇文章,下一页= 10篇下一篇文章等。
您可以按某些类别作为来源或日期订购。
所以,当我到达我的mydomaine.com/articles/时,我会显示所有元素。
如果我按来源排序,就像这个views.py显示:
class SourceEntriesView(ContextSourcesMixin, BaseArticleView, BaseArticleListView):
model = Article
context_object_name = 'article_list'
template_name = 'base_templates/template_press.html'
_source = None
paginate_by = get_setting('PAGINATION')
view_url_name = 'djangocms_press:articles-source'
@property
def source(self):
if not self._source:
try:
source_qs = ArticleSource.objects.active_translations(
get_language(),
slug=self.kwargs['source']
)
#source_qs = source_qs.filter(site=Site.objects.get_current().pk)
self._source = source_qs.latest('pk')
except ArticleSource.DoesNotExist:
raise Http404("ArticleSource does not exist for this site")
return self._source
def get_queryset(self):
qs = super(SourceEntriesView, self).get_queryset()
if 'source' in self.kwargs:
qs = qs.filter(sources__pk=self.source.pk)
return qs
def get_context_data(self, **kwargs):
kwargs['source'] = self.source
return super(SourceEntriesView, self).get_context_data(**kwargs)
一旦ajax调用加载此视图并显示按源排序的文章,我就有了10个项目! (好吧,我在测试时尝试4)。
那么为什么它不在主页上工作呢。
以下是我的代码的更多解释:
''' Main article display view '''
class ArticleListView(FormMixin, BaseArticleListView, ContextSourcesMixin):
model = Article
context_object_name = 'article_list'
template_name = 'base_templates/template_press.html'
view_url_name = 'djangocms_press:articles-list'
form_class = SourcesRegionsFilterForm
paginate_by = get_setting('PAGINATION')
def get_form_kwargs(self):
return {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
'data': self.request.GET or None,
'request': self.request,
}
def get(self, request, *args, **kwargs):
"""
Handle the form submissions to filter by Sources and regions
First_object is use for pagination
"""
context = {}
self.object_list = self.get_queryset().order_by("-date_realization")
first_object = 0
if 'article' in self.request.GET:
try:
project_id = int(request.GET['article'])
context['article_render'] = self.object_list.get(pk=project_id)
except (Article.DoesNotExist, ValueError):
pass
form = self.get_form(self.form_class)
if form.is_valid():
if form.cleaned_data['regions']:
self.object_list = self.object_list.filter(
Q(regions__continent=form.cleaned_data['regions']) | Q(global_regions=True)).distinct()
context.update(self.get_context_data(form=form))
context['load_more_url'] = self.get_load_more_url(request, context)
context[self.context_object_name] = self.object_list
context['object_list'] = self.object_list
source_qs = ArticleSource.objects.active_translations(get_language())
context['sources_list'] = source_qs
date_realization_for_articles = Article.objects.values_list('date_realization',
flat=True).distinct()
context['dates_realization'] = date_realization_for_articles.dates('date_realization', 'month', order="DESC")
return self.render_to_response(context)
def get_load_more_url(self, request, context):
args = request.GET.copy()
return '?{}'.format(args.urlencode())
def render_to_json_response(self, context, **response_kwargs):
if 'current_app' not in context:
context['current_app'] = resolve(self.request.path).namespace
c = RequestContext(self.request, context)
html_items_list = render_to_string(
'base_templates/template_press.html',
context,
context_instance=c)
html_items_list = html_items_list.strip()
json_response = {
'html_items_list': html_items_list,
'load_more_url': self.get_load_more_url(self.request, context),
}
return JsonResponse(json_response)
def render_to_response(self, context):
if self.request.is_ajax():
response = self.render_to_json_response(context)
else:
response = super(ArticleListView, self).render_to_response(context)
return response
这是显示文章的主视图。
我的设置,非常简单但更易于使用:
def get_setting(name):
from django.conf import settings
from meta_mixin import settings as meta_settings
default = {
'PRESS_PAGINATION': getattr(settings, 'PRESS_PAGINATION', 4),
}
return default['PRESS_%s' % name]
我也尝试在文章列表网址中传递paginated_by,但结果是一样的。
这是模板的一部分,假设要进行分页:
{% if article_list %}
<div id="articles-list" class="col-md-12">
{% for article in article_list %}
<div class="row article">
<div class="col-md-2">
{{ article.date_realization|date:"F d, Y" }}
</div>
<div class="col-md-2">
{{ article.source }}
</div>
<div class="col-md-2">
{% for region in article.regions.all %}
{{ region.name }}
{% endfor %}
</div>
<div class="col-md-6">
{{ article.title }}
</div>
</div>
{% endfor %}
</div>
{% if is_paginated %}
<section id="content-btn">
<div id="load-more-btn blippar-white-btn" class="col-md-2 col-md-offset-5 col-xs-8 col-xs-offset-2" align="center">
<a id="loadmore" role="button" class="button btn load-more-btn blippar-white-btn" href="{{ load_more_url }}">{% trans 'VIEW MORE' %}</a>
</div>
</section>
<div class="col-lg-12">
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</div>
{% endif %}
{% endif %}
所以,我有两个问题:
如果你有想法或反思导向,我会喜欢它:)
答案 0 :(得分:1)
我假设您使用的是MultipleObjectMixin。
在这种情况下,当您致电context.update(self.get_context_data(form=form))
时会发生分页。在那里查看来源:https://github.com/django/django/blob/master/django/views/generic/list.py
因此,当您调用此函数时,它会将上下文['object_list']设置为分页内容。不幸的是,当你调用context['object_list'] = self.object_list
时,你会将它覆盖几行,因为self.object_list不会受到分页的影响。如果删除此行,则应该没问题。
编辑:因为看起来你使用'article_list'而不是'object_list',所以这里还有其他评论:
context[self.context_object_name] = self.object_list
替换context[self.context_object_name] = context['object_list']
,它会起作用:)答案 1 :(得分:0)
所以,目前我有一个临时解决方案:
<html>
<head>
<title>My first chart using FusionCharts Suite XT</title>
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript">
FusionCharts.ready(function () {
var revenueChart = new FusionCharts({
type: 'doughnut2d',
renderAt: 'chart-container',
width: '450',
height: '450',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Homicides by Weapon",
"subCaption": "USA 2013",
"numberPrefix": "",
"paletteColors": "#0075c2,#1aaf5d,#f2c500,#f45b00,#8e0000",
"bgColor": "#ffffff",
"showBorder": "0",
"use3DLighting": "0",
"showShadow": "0",
"enableSmartLabels": "0",
"startingAngle": "310",
"showLabels": "0",
"showPercentValues": "1",
"showLegend": "1",
"legendShadow": "0",
"legendBorderAlpha": "0",
"defaultCenterLabel": "Total homicides: 11583",
"centerLabel": "Homicides from $label: $value",
"centerLabelBold": "1",
"showTooltip": "0",
"decimals": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0"
},
"data": [
{
"label": "Firearms",
"value": "8454"
},
{
"label": "Knives or cutting instruments",
"value": "1490"
},
{
"label": "Personal Weapons (hands, fists, etc.)",
"value": "687"
},
{
"label": "Other",
"value": "952"
}
]
}
}).render();
});
</script>
</head>
<body>
<div id="chart-container">FusionCharts will render here</div>
</body>
</html>
而不是:
{% for article in page_obj.object_list %}
<div class="row article">
<div class="col-md-2">
{{ article.date_realization|date:"F d, Y" }}
</div>
<div class="col-md-2">
{{ article.source }}
</div>
<div class="col-md-2">
{% for region in article.regions.all %}
{{ region.name }}
{% endfor %}
</div>
<div class="col-md-6">
{{ article.title }}
</div>
</div>
{% endfor %}
article_list成为了object_list。我对此并不满意,因为当我阅读文档时,这不是必要的。