def change_view(self, request, object_id, extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, # don't see where it's used #'lang': current_lang, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language] extra_context['page'] = obj return super(PageAdmin, self).change_view(request, object_id, extra_context)
def test_bug_152(self): """Test bug 152 http://code.google.com/p/django-page-cms/issues/detail?id=152""" self.assertEqual( str(get_placeholders('pages/tests/test1.html')), "[<Placeholder Node: body>]" )
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" form = super(PageAdmin, self).get_form(request, obj, **kwargs) language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title form.base_fields['slug'].label = _('Slug') template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() if len(page_templates) > 0: template_choices = list(page_templates) template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_unicode(template) for placeholder in get_placeholders(template): name = placeholder.name if obj: initial = placeholder.get_content(obj, language, name) else: initial = None form.base_fields[name] = placeholder.get_field(obj, language, initial=initial) return form
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.name for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') # delete content cache, frozen or not for name in p_names: # frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 1)) # not frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 0)) cache.delete(self.PAGE_URL_KEY % (self.id)) cache.delete(PAGE_IS_FIRST_ROOT_KEY % (self.id)) for page in self.get_descendants(): cache.delete(self.PAGE_URL_KEY % (page.id)) cache.delete(PAGE_IS_FIRST_ROOT_KEY % (page.id))
def change_view(self, request, object_id, extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, # don't see where it's used #'lang': current_lang, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [ l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language ] extra_context['page'] = obj return super(PageAdmin, self).change_view(request, object_id, extra_context)
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) cache.delete('PAGE_FIRST_ROOT_ID') cache.delete(self.CHILDREN_KEY % self.id) cache.delete(self.PUB_CHILDREN_KEY % self.id) # XXX: Should this have a depth limit? if self.parent_id: self.parent.invalidate() self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.name for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') # delete content cache, frozen or not for name in p_names: # frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 1)) # not frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 0)) cache.delete(self.PAGE_URL_KEY % (self.id))
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" form = super(PageAdmin, self).get_form(request, obj, **kwargs) language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title form.base_fields['slug'].label = _('Slug') template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() if len(page_templates) > 0: template_choices = list(page_templates) template_choices.insert( 0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_unicode(template) for placeholder in get_placeholders(template): name = placeholder.name if obj: initial = placeholder.get_content(obj, language, name) else: initial = None form.base_fields[name] = placeholder.get_field(obj, language, initial=initial) return form
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ general_fields = list(self.general_fields) # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general', ), } default_fieldsets = list(self.fieldsets) if not request.user.has_perm('pages.can_freeze'): general_module['fields'].remove('freeze_date') if not request.user.has_perm('pages.can_publish'): general_module['fields'].remove('status') default_fieldsets[0][1] = general_module placeholder_fieldsets = [] template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.ctype not in self.mandatory_placeholders: placeholder_fieldsets.append(placeholder.ctype) additional_fieldsets = [] additional_fieldsets.append((_('Content'), { 'fields': placeholder_fieldsets, 'classes': ('module-content', ), })) return default_fieldsets + additional_fieldsets
def save_model(self, request, page, form, change): """Move the page in the tree if necessary and save every placeholder :class:`Content <pages.models.Content>`. """ language = form.cleaned_data['language'] target = form.data.get('target', None) position = form.data.get('position', None) page.save() # if True, we need to move the page if target and position: try: target = self.model.objects.get(pk=target) except self.model.DoesNotExist: pass else: target.invalidate() page.move_to(target, position) for name in self.mandatory_placeholders: data = form.cleaned_data[name] placeholder = PlaceholderNode(name) extra_data = placeholder.get_extra_data(form.data) placeholder.save(page, language, data, change, extra_data=extra_data) for placeholder in get_placeholders(page.get_template()): if(placeholder.ctype in form.cleaned_data and placeholder.ctype not in self.mandatory_placeholders): data = form.cleaned_data[placeholder.ctype] extra_data = placeholder.get_extra_data(form.data) placeholder.save(page, language, data, change, extra_data=extra_data) page.invalidate()
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ general_fields = list(self.general_fields) perms = PagePermission(request.user) # some ugly business to remove freeze_date # from the field list general_module = {"fields": list(self.general_fields), "classes": ("module-general",)} default_fieldsets = list(self.fieldsets) if not perms.check("freeze"): general_module["fields"].remove("freeze_date") if not perms.check("publish"): general_module["fields"].remove("status") default_fieldsets[0][1] = general_module placeholder_fieldsets = [] template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.name not in self.mandatory_placeholders: placeholder_fieldsets.append(placeholder.name) additional_fieldsets = [] additional_fieldsets.append((_("Content"), {"fields": placeholder_fieldsets, "classes": ("module-content",)})) return default_fieldsets + additional_fieldsets
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ general_fields = list(self.general_fields) # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general',), } default_fieldsets = list(self.fieldsets) if not request.user.has_perm('pages.can_freeze'): general_module['fields'].remove('freeze_date') if not request.user.has_perm('pages.can_publish'): general_module['fields'].remove('status') default_fieldsets[0][1] = general_module placeholder_fieldsets = [] template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.ctype not in self.mandatory_placeholders: placeholder_fieldsets.append(placeholder.ctype) additional_fieldsets = [] additional_fieldsets.append((_('Content'), { 'fields': placeholder_fieldsets, 'classes': ('module-content',), })) return default_fieldsets + additional_fieldsets
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) cache.delete('PAGE_FIRST_ROOT_ID') cache.delete(self.CHILDREN_KEY % self.id) cache.delete(self.PUB_CHILDREN_KEY % self.id) # XXX: Should this have a depth limit? if self.parent_id: self.parent.invalidate() self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.ctype for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') # delete content cache, frozen or not for name in p_names: # frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 1)) # not frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 0)) cache.delete(self.PAGE_URL_KEY % (self.id))
def save_model(self, request, page, form, change): """Move the page in the tree if necessary and save every placeholder :class:`Content <pages.models.Content>`. """ language = form.cleaned_data['language'] target = form.data.get('target', None) position = form.data.get('position', None) page.save() # if True, we need to move the page if target and position: try: target = self.model.objects.get(pk=target) except self.model.DoesNotExist: pass else: target.invalidate() page.move_to(target, position) for name in self.mandatory_placeholders: data = form.cleaned_data[name] placeholder = PlaceholderNode(name) extra_data = placeholder.get_extra_data(form.data) placeholder.save(page, language, data, change, extra_data=extra_data) for placeholder in get_placeholders(page.get_template()): if(placeholder.name in form.cleaned_data and placeholder.name not in self.mandatory_placeholders): data = form.cleaned_data[placeholder.name] extra_data = placeholder.get_extra_data(form.data) placeholder.save(page, language, data, change, extra_data=extra_data) page.invalidate()
def modify_placeholder(request, page_id, language_id): """Modify the content of a page.""" page = get_object_or_404(Page, pk=page_id) content_type = request.GET.get('content_type') perm = request.user.has_perm('pages.change_page') if perm and request.method == 'POST': placeholders = get_placeholders(page.get_template()) for placeholder in placeholders: if placeholder.name == content_type: initial = placeholder.get_content(page, language_id, lang_fallback=False) form = forms.Form(request.POST) form.fields[content_type] = placeholder.get_field( page, language_id, initial=initial) if not form.is_valid(): return HttpResponse(form.as_p()) placeholder.save(page, language_id, form.cleaned_data[content_type], True) page.invalidate() # to update last modification date page.save() return HttpResponse('ok') raise Http404("Content type not found in placeholders") raise Http404
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) #model = create_page_model(get_placeholders(template)) form = make_form(self.model, get_placeholders(template)) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() template_choices = list(page_templates) # is default template is not in the list add it if not [ tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE ]: template_choices.insert( 0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): ctype = placeholder.ctype if obj: initial = placeholder.get_content(obj, language, lang_fallback=False) else: initial = None form.base_fields[ctype] = placeholder.get_field(obj, language, initial=initial) return form
def placeholder_content(): """Return content of each placeholder in each language.""" out = {} for p in get_placeholders(self.get_template()): if p.name in ('title', 'slug'): continue # these were already included out[p.name] = language_content(p.name) return out
def placeholder_content(): """Return content of each placeholder in each language.""" out = {} for p in get_placeholders(page.get_template()): if p.ctype in ('title', 'slug'): continue # these were already included out[p.name] = language_content(p.name) return out
def traduction(request, page_id, language_id): """Traduction helper.""" page = Page.objects.get(pk=page_id) context = {} lang = language_id placeholders = get_placeholders(page.get_template()) if Content.objects.get_content(page, language_id, "title") is None: language_error = True return 'pages/traduction_helper.html', locals()
def traduction(request, page_id, language_id): """Traduction helper.""" page = Page.objects.get(pk=page_id) lang = language_id placeholders = get_placeholders(page.get_template()) language_error = Content.objects.get_content(page, language_id, "title") is None return ( "pages/traduction_helper.html", {"page": page, "lang": lang, "language_error": language_error, "placeholders": placeholders}, )
def expose_content(self): """Return all the current content of this page into a `string`. This is used by the haystack framework to build the search index.""" placeholders = get_placeholders(self.get_template()) exposed_content = [] for lang in self.get_languages(): for p_name in [p.name for p in placeholders]: content = self.get_content(lang, p_name, False) if content: exposed_content.append(content) return u"\r\n".join(exposed_content)
def expose_content(self): """Return all the current content of this page into a `string`. This is used by the haystack framework to build the search index.""" placeholders = get_placeholders(self.get_template()) exposed_content = [] for lang in self.get_languages(): for p in placeholders: content = self.get_content(lang, p.ctype, False) if content: exposed_content.append(content) return "\r\n".join(exposed_content)
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) #model = create_page_model(get_placeholders(template)) form = make_form(self.model, get_placeholders(template)) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() template_choices = list(page_templates) # is default template is not in the list add it if not [tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE]: template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): ctype = placeholder.ctype if obj: initial = placeholder.get_content(obj, language, lang_fallback=False) else: initial = None form.base_fields[ctype] = placeholder.get_field(obj, language, initial=initial) return form
def traduction(request, page_id, language_id): """Traduction helper.""" page = Page.objects.get(pk=page_id) lang = language_id placeholders = get_placeholders(page.get_template()) language_error = (Content.objects.get_content(page, language_id, "title") is None) return 'pages/traduction_helper.html', { 'page': page, 'lang': lang, 'language_error': language_error, 'placeholders': placeholders, }
def placeholder_content(): """Return content of each placeholder in each language.""" out = {} for p in get_placeholders(self.get_template()): if p.name in ("title", "slug"): continue # these were already included out[p.name] = language_content(p.name) for p in Content.objects.filter( type__in=["meta_title", "meta_description", "meta_keywords", "meta_author", "fb_page_type", "fb_image"] ): out[p.type] = language_content(p.type) return out
def change_view(self, request, object_id, form_url='', extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [ l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language ] extra_context['page'] = obj response = super(PageAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context) if request.method == 'POST' and isinstance(response, HttpResponseRedirect): if '_continue' in request.POST or '_saveasnew' in request.POST or '_addanother' in request.POST: addlanguage = True else: addlanguage = False if addlanguage: from six.moves import urllib splitted = list(urllib.parse.urlparse(response.url)) query = urllib.parse.parse_qs(splitted[4]) query['language'] = language splitted[4] = urllib.parse.urlencode(query) response = HttpResponseRedirect( urllib.parse.urlunparse(splitted)) return response
def test_placeholder_bug(self): """Test placeholder with django template inheritance works prepoerly. http://code.google.com/p/django-page-cms/issues/detail?id=210 """ p1 = self.new_page(content={'slug':'test', 'one':'one', 'two': 'two'}) template = django.template.loader.get_template('pages/tests/extends.html') context = Context({'current_page': p1, 'lang':'en-us'}) renderer = template.render(context) self.assertTrue('one' in renderer) self.assertTrue('two' in renderer) from pages.utils import get_placeholders self.assertEqual( str(get_placeholders('pages/tests/extends.html')), '[<Placeholder Node: one>, <Placeholder Node: two>]')
def test_placeholder_bug(self): """Test placeholder with django template inheritance works prepoerly. http://code.google.com/p/django-page-cms/issues/detail?id=210 """ p1 = self.new_page(content={'slug':'test', 'one':'one', 'two': 'two'}) template = django.template.loader.get_template('pages/tests/extends.html') context = {'current_page': p1, 'lang':'en-us'} renderer = template.render(context) self.assertTrue('one' in renderer) self.assertTrue('two' in renderer) from pages.utils import get_placeholders self.assertEqual( str(get_placeholders('pages/tests/extends.html')), '[<Placeholder Node: one>, <Placeholder Node: two>]')
def test_placeholder_bug(self): """Test placeholder with django template inheritance works prepoerly. http://code.google.com/p/django-page-cms/issues/detail?id=210 """ p1 = self.new_page(content={"slug": "test", "one": "one", "two": "two"}) template = django.template.loader.get_template("pages/tests/extends.html") context = Context({"current_page": p1, "lang": "en-us"}) renderer = template.render(context) self.assertTrue("one" in renderer) self.assertTrue("two" in renderer) from pages.utils import get_placeholders self.assertEqual( str(get_placeholders("pages/tests/extends.html")), "[<Placeholder Node: one>, <Placeholder Node: two>]" )
def change_view(self, request, object_id, form_url='', extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language] extra_context['page'] = obj response = super(PageAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context) if request.method == 'POST' and isinstance(response, HttpResponseRedirect): if '_continue' in request.POST or '_saveasnew' in request.POST or '_addanother' in request.POST: addlanguage = True else: addlanguage = False if addlanguage: from six.moves import urllib splitted = list(urllib.parse.urlparse(response.url)) query = urllib.parse.parse_qs(splitted[4]) query['language'] = language splitted[4] = urllib.parse.urlencode(query) response = HttpResponseRedirect(urllib.parse.urlunparse(splitted)) return response
def get_last_content(request, page_id): """Get the latest content for a particular type""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) placeholders = get_placeholders(page.get_template()) _template = template.loader.get_template(page.get_template()) for placeholder in placeholders: if placeholder.name == content_type: context = RequestContext(request, { 'current_page': page, 'lang': language_id }) with context.bind_template(_template.template): content = placeholder.render(context) return HttpResponse(content) raise Http404
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) #cache.delete(self.PAGE_TEMPLATE_KEY % (self.id)) p_names = [p.name for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') for name in p_names: cache.delete(self.PAGE_CONTENT_DICT_KEY % (self.id, name)) for lang in settings.PAGE_LANGUAGES: cache.delete(self.PAGE_URL_KEY % (self.id, lang[0])) cache.delete(self.PAGE_URL_KEY % (self.id, "None"))
def content_by_language(self, language): """ Return a list of latest published :class:`Content <pages.models.Content>` for a particluar language. :param language: wanted language, """ placeholders = get_placeholders(self.get_template()) content_list = [] for p in placeholders: try: content = Content.objects.get_content_object(self, language, p.ctype) content_list.append(content) except Content.DoesNotExist: pass return content_list
def render(self, context): request = context.get('request') if not request.user.is_staff: return '' template_name = context.get('template_name') placeholders = get_placeholders(template_name) page = context.get('current_page') lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) form = forms.Form() for p in placeholders: field = p.get_field(page, lang) form.fields[p.name] = field link = '<link href="{}" type="text/css" media="all" rel="stylesheet" />'.format( static('pages/css/inline-edit.css')) return "{}{}".format(form.media, link)
def render(self, context): request = context.get('request') if not request.user.is_staff: return '' template_name = context.get('template_name') placeholders = get_placeholders(template_name) page = context.get('current_page') lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) form = forms.Form() for p in placeholders: field = p.get_field(page, lang) form.fields[p.name] = field link = '<link href="{}" type="text/css" media="all" rel="stylesheet" />'.format( static('pages/css/inline-edit.css') ) return "{}{}".format(form.media, link)
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general', ), } default_fieldsets = list(self.fieldsets) if not request.user.has_perm('pages.can_freeze'): general_module['fields'].remove('freeze_date') if not request.user.has_perm('pages.can_publish'): general_module['fields'].remove('status') default_fieldsets[0][1] = general_module placeholder_fieldsets = [] section_placeholder_fieldsets = defaultdict(list) template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.ctype not in self.mandatory_placeholders and not placeholder.section: placeholder_fieldsets.append(placeholder.ctype) elif placeholder.section: section_placeholder_fieldsets[placeholder.section].append( placeholder.ctype) additional_fieldsets = [] for title, fieldset in section_placeholder_fieldsets.items(): additional_fieldsets.append((title, { 'fields': fieldset, 'classes': ('module-content collapse grp-collapse grp-closed', ), })) additional_fieldsets.append((_('Content'), { 'fields': placeholder_fieldsets, 'classes': ('module-content', ), })) return default_fieldsets + additional_fieldsets
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ general_fields = list(self.general_fields) perms = PagePermission(request.user) # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general',), } default_fieldsets = list(self.fieldsets) if not perms.check('freeze'): general_module['fields'].remove('freeze_date') if not perms.check('publish'): general_module['fields'].remove('status') default_fieldsets[0][1] = general_module placeholder_fieldsets = [] template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.name not in self.mandatory_placeholders: placeholder_fieldsets.append(placeholder.name) additional_fieldsets = [] # meta fields metadata_fieldsets = [f['name'] for f in self.metadata_fields] additional_fieldsets.append((_('Metadata'), { 'fields': metadata_fieldsets, 'classes': ('module-content', 'collapse'), })) additional_fieldsets.append((_('Content'), { 'fields': placeholder_fieldsets, 'classes': ('module-content',), })) return default_fieldsets + additional_fieldsets
def render(self, context): request = context.get('request') if not request.user.is_staff: return '' template_name = context.get('template_name') placeholders = get_placeholders(template_name) page = context.get('current_page') lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) form = forms.Form() for p in placeholders: field = p.get_field(page, lang, initial=p.get_content_from_context(context)) form.fields[p.name] = field template = get_template('pages/inline-edit.html') with context.push(): context['form'] = form content = template.render(context) return content
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general',), } default_fieldsets = list(self.fieldsets) if not request.user.has_perm('pages.can_freeze'): general_module['fields'].remove('freeze_date') if not request.user.has_perm('pages.can_publish'): general_module['fields'].remove('status') if not len(registry): general_module['fields'].remove('delegate_to') default_fieldsets[0][1] = general_module placeholder_fieldsets = [] section_placeholder_fieldsets = defaultdict(list) template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.ctype not in self.mandatory_placeholders and not placeholder.section: placeholder_fieldsets.append(placeholder.ctype) elif placeholder.section: section_placeholder_fieldsets[placeholder.section].append(placeholder.ctype) additional_fieldsets = [] for title, fieldset in section_placeholder_fieldsets.items(): additional_fieldsets.append((title, { 'fields': fieldset, 'classes': ('module-content collapse grp-collapse grp-closed',), })) additional_fieldsets.append((_('Content'), { 'fields': placeholder_fieldsets, 'classes': ('module-content',), })) return default_fieldsets + additional_fieldsets
def render(self, context): request = context.get('request') if not request.user.is_staff: return '' template_name = context.get('template_name') placeholders = get_placeholders(template_name) page = context.get('current_page') lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) form = forms.Form() for p in placeholders: field = p.get_field( page, lang, initial=p.get_content_from_context(context)) form.fields[p.name] = field template = get_template('pages/inline-edit.html') with context.push(): context['form'] = form content = template.render(context) return content
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ additional_fieldsets = [] placeholder_fieldsets = [] template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): if placeholder.name not in self.mandatory_placeholders: placeholder_fieldsets.append(placeholder.name) additional_fieldsets.append((_("Content"), {"fields": placeholder_fieldsets, "classes": ("module-content",)})) # deactived for now, create bugs with page with same slug title given_fieldsets = list(self.declared_fieldsets) return given_fieldsets + additional_fieldsets
def get_form(self, request, obj=None, **kwargs): form = super(PageAdminWithDefaultContent, self).get_form(request, obj, **kwargs) language = get_language_from_request(request) if global_settings.LANGUAGE_CODE == language: # this is the "official" language return form if Content.objects.filter(page=obj, language=language).count(): return form # this is a new page, try to find some default content template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): name = placeholder.name form.base_fields[name] = placeholder.get_field( obj, language, initial=Content.objects.get_content(obj, global_settings.LANGUAGE_CODE, name) ) return form
def get_form(self, request, obj=None, **kwargs): """Get PageForm for the Page model and modify its fields depending on the request.""" form = super(PageAdmin, self).get_form(request, obj, **kwargs) language = get_language_from_request(request, obj) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title form.base_fields['slug'].label = _('Slug') template = get_template_from_request(request, obj) if settings.PAGE_TEMPLATES: template_choices = list(settings.PAGE_TEMPLATES) template_choices.insert(0, (settings.DEFAULT_PAGE_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_unicode(template) for placeholder in get_placeholders(template): widget = self.get_widget(placeholder.widget)() if placeholder.parsed: help_text = _('Note: This field is evaluated as template code.') else: help_text = "" name = placeholder.name if obj: initial = Content.objects.get_content(obj, language, name) else: initial = None if name not in self.mandatory_placeholders: form.base_fields[placeholder.name] = CharField(widget=widget, initial=initial, help_text=help_text, required=False) else: form.base_fields[name].initial = initial form.base_fields[name].help_text = help_text return form
def get_form(self, request, obj=None, **kwargs): form = super(PageAdminWithDefaultContent, self ).get_form(request, obj, **kwargs) language = get_language_from_request(request) if global_settings.LANGUAGE_CODE == language: # this is the "official" language return form if Content.objects.filter(page=obj, language=language).count(): return form # this is a new page, try to find some default content template = get_template_from_request(request, obj) for placeholder in get_placeholders(template): name = placeholder.name form.base_fields[name] = placeholder.get_field(obj, language, initial=Content.objects.get_content(obj, global_settings.LANGUAGE_CODE, name)) return form
def save_model(self, request, obj, form, change): """Move the page in the tree if necessary and save every placeholder Content object. """ language = form.cleaned_data['language'] target = form.data.get('target', None) position = form.data.get('position', None) obj.save() if target and position: try: target = self.model.objects.get(pk=target) except self.model.DoesNotExist: pass else: target.invalidate() obj.move_to(target, position) for mandatory_placeholder in self.mandatory_placeholders: Content.objects.set_or_create_content(obj, language, mandatory_placeholder, form.cleaned_data[mandatory_placeholder]) for placeholder in get_placeholders(obj.get_template()): if placeholder.name in form.cleaned_data: if change: if placeholder.name not in self.mandatory_placeholders: # we need create a new content if revision is enabled if settings.PAGE_CONTENT_REVISION and placeholder.name \ not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST: Content.objects.create_content_if_changed(obj, language, placeholder.name, form.cleaned_data[placeholder.name]) else: Content.objects.set_or_create_content(obj, language, placeholder.name, form.cleaned_data[placeholder.name]) else: Content.objects.set_or_create_content(obj, language, placeholder.name, form.cleaned_data[placeholder.name]) obj.invalidate()
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) cache.delete('PAGE_FIRST_ROOT_ID') self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.name for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') # delete content cache, frozen or not for name in p_names: # frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 1)) # not frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 0)) cache.delete(self.PAGE_URL_KEY % (self.id))
def modify_placeholder(request, page_id): """Modify the content of a page.""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) perm = request.user.has_perm('pages.change_page') if perm and request.method == 'POST': placeholders = get_placeholders(page.get_template()) for placeholder in placeholders: if placeholder.name == content_type: initial = placeholder.get_content( page, language_id, lang_fallback=False) form = forms.Form(request.POST, request.FILES) form.fields[content_type] = placeholder.get_field( page, language_id, initial=initial) if not form.is_valid(): return HttpResponse(form.as_p()) if placeholder.shared: save_page = None else: save_page = page extra_data = placeholder.get_extra_data(form.data) placeholder.save( save_page, language_id, form.cleaned_data[content_type], True, extra_data) if save_page: page.invalidate() # to update last modification date page.save() else: fake_page.invalidate(content_type) return HttpResponse('ok') raise Http404("Content type not found in placeholders") raise Http404
def test_bug_block_without_super(self): """Without the block the placeholder should not be there""" self.assertEqual( str(get_placeholders('pages/tests/block3.html')), "[<Placeholder Node: test>]" )
def validate_pages_json_data(d, preferred_lang): """ Check if an import of d will succeed, and return errors. errors is a list of strings. The import should proceed only if errors is empty. """ from pages.models import Page errors = [] seen_complete_slugs = dict( (lang[0], set()) for lang in settings.PAGE_LANGUAGES) valid_templates = set(t[0] for t in settings.get_page_templates()) valid_templates.add(settings.PAGE_DEFAULT_TEMPLATE) if d[JSON_PAGE_EXPORT_NAME] != JSON_PAGE_EXPORT_VERSION: return [ _('Unsupported file version: %s') % repr(d[JSON_PAGE_EXPORT_NAME]) ], [] pages = d['pages'] for p in pages: # use the complete slug as a way to identify pages in errors slug = p['complete_slug'].get(preferred_lang, None) seen_parent = False for lang, s in list(p['complete_slug'].items()): if lang not in seen_complete_slugs: continue seen_complete_slugs[lang].add(s) if '/' not in s: # root level, no parent req'd seen_parent = True if not seen_parent: parent_slug, ignore = s.rsplit('/', 1) if parent_slug in seen_complete_slugs[lang]: seen_parent = True else: parent = Page.objects.from_path(parent_slug, lang, exclude_drafts=False) if parent and parent.get_complete_slug( lang) == parent_slug: # parent not included, but exists on site seen_parent = True if not slug: slug = s if not slug: errors.append( _("%s has no common language with this site") % (list(p['complete_slug'].values())[0], )) continue if not seen_parent: errors.append( _("%s did not include its parent page and a matching" " one was not found on this site") % (slug, )) if p['template'] not in valid_templates: errors.append( _("%s uses a template not found on this site: %s") % (slug, p['template'])) continue if set(p.ctype for p in get_placeholders(p['template']) if p.ctype not in ('title', 'slug')) != set( p['content'].keys()): errors.append( _("%s template contents are different than our " "template: %s") % (slug, p['template'])) continue return errors
def test_bug_block_super(self): """{{ block.super }} doesn't work""" self.assertEqual( str(get_placeholders('pages/tests/block2.html')), "[<Placeholder Node: body>, <Placeholder Node: body2>]" )