def _has_changed(self, initial, data): if initial is not None and not isinstance(initial, basestring): initial = edit_string_for_tags( [o.tag for o in initial.select_related("tag")]) if data is not None and not isinstance(data, basestring): data = edit_string_for_tags( [o.tag for o in data.select_related("tag")]) return super(TagWidget, self)._has_changed(initial, data)
def test_recreation_of_tag_list_string_representations(self): plain = Tag.objects.create(name='plain') spaces = Tag.objects.create(name='spa ces') comma = Tag.objects.create(name='com,ma') self.assertEqual(edit_string_for_tags([plain]), u'plain') self.assertEqual(edit_string_for_tags([plain, spaces]), u'"spa ces", plain') self.assertEqual(edit_string_for_tags([plain, spaces, comma]), u'"com,ma", "spa ces", plain') self.assertEqual(edit_string_for_tags([plain, comma]), u'"com,ma", plain') self.assertEqual(edit_string_for_tags([comma, spaces]), u'"com,ma", "spa ces"')
def test_recreation_of_tag_list_string_representations(self): plain = Tag(name="plain") spaces = Tag(name="spa ces") comma = Tag(name="com,ma") self.assertEqual(edit_string_for_tags([plain]), "plain") self.assertEqual(edit_string_for_tags([plain, spaces]), '"spa ces", plain') self.assertEqual( edit_string_for_tags([plain, spaces, comma]), '"com,ma", "spa ces", plain' ) self.assertEqual(edit_string_for_tags([plain, comma]), '"com,ma", plain') self.assertEqual(edit_string_for_tags([comma, spaces]), '"com,ma", "spa ces"')
def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) if 'instance' in kwargs: #Update mode obj = kwargs['instance'] else: #Creation mode obj = None if obj: if obj.status == Entry.PUBLISHED_STATUS: initial_tags = edit_string_for_tags(obj.tags_list) else: initial_tags = ','.join(obj.drafted_tags) initial_other_authors = [user.username for user in obj.authors] self.fields['other_authors'].label = "Author(s)" if obj.front_image: initial_image = type('ImgTemp', (object,), { "url": force_text(obj.front_image), '__unicode__': lambda self : unicode(self.url)})() self.fields['front_image_upload'].initial = initial_image else: initial_tags = None initial_other_authors = [] self.fields['tags'].initial=initial_tags #Get all available tags and set it inside the form field. These will be used by tag-it plugin to perform #the autocomplet on the widget self.fields['tags'].available_tags = json.dumps([ tag.name for tag in Tag.objects.all()]) self.fields['other_authors'].initial = ", ".join(initial_other_authors)
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe(html)
def get_initial(self): """ We want to populate the form with data from the two associated models, and so we have to use initial, not instance, as this is not a ModelForm. So we basically slurp and serialize two models. """ review = self.get_object() # Dumbest possible serialization that could work # @todo: this isn't very DRY. artwork = review.artwork initial = dict( review_id=review.pk, artwork_name=artwork.name, artwork_kind=artwork.kind, artwork_creator=artwork.creator, artwork_year=artwork.year, artwork_season=review.season, artwork_episode=review.episode, spider_quantity=review.spider_quantity, spider_quality=edit_string_for_tags(review.spider_quality.all()), summary=review.summary ) return initial
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) if attrs is None: attrs = {} attrs.update({'class': 'taggit-tags'}) return super(TagWidget, self).render(name, value, attrs)
def reprocess_tags(self): self.stdout.write( 'Reprocessing tags (lowercasing, slugifying, etc.)...') project_total = Project.objects.count() # Use an iterator so the queryset isn't stored in memory # This may take a long time but should be memory efficient for i, project in enumerate(Project.objects.iterator()): old_tags_objs = list(project.tags.all()) if old_tags_objs: old_tags = sorted([t.name for t in old_tags_objs]) old_tag_string = edit_string_for_tags(old_tags_objs) new_tags = parse_tags(old_tag_string) # Update the tags on the project if they are different # Note: "parse_tags" handles sorting if new_tags != old_tags: if not self.dry_run: self.stdout.write( '[{}/{}] Setting tags on "{}"'.format( i + 1, project_total, project.slug, )) project.tags.set(*new_tags) else: self.stdout.write( '[{}/{}] Not setting tags on "{}" (dry run)'. format( i + 1, project_total, project.slug, ))
def render(self, name, value, attrs=None): list_view = reverse('taggit_autocomplete-list') if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) html = super(TagAutocomplete, self).render(name, value, attrs) # Activate tag-it in this field js = u""" <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { (function($) { $(document).ready(function() { $("#%(id)s").tagit({ caseSensitive: false, allowSpaces: true, tagSource: function(search, showChoices) { options = this; $.getJSON("%(source)s", { q: search.term.toLowerCase() }, function(data) { showChoices(options._subtractArray(data, options.assignedTags())); }); } }); }); })(jQuery); }, false); </script> """ % ({ 'id': attrs['id'], 'source': list_view }) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) rendered = super(TaggitLiveWidget, self).render(name, value, attrs) url = reverse("taggit_autocomplete_list") js = '<script type="text/javascript">(function($) { $("#%s").taggit_live({callback: "%s"}); })(jQuery || django.jQuery);</script>' % (attrs['id'], url) return rendered + mark_safe(js)
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe(html)
def render(self, name, value, attrs=None): if attrs is not None: attrs = dict(self.attrs.items() + attrs.items()) if value is not None and not isinstance(value, basestring): value = [ edit_string_for_tags([o.tag]) for o in value.select_related("tag") ] else: if value is not None: value = value.split(',') else: value = [] html = super(TagAutocomplete, self).render("%s_dummy" % name, ",".join(value), attrs) allow_add = "false" if 'allow_add' in attrs and attrs['allow_add']: allow_add = "true" js_config = u"""{startText: "%s", \ preFill: prefill, \ allowAdd: %s, \ allowAddMessage: "%s"}""" % ( escapejs(_("Enter Tag Here")), allow_add, escapejs(_("Please choose an existing tag")), ) js = u"""<script type="text/javascript">jQuery = django.jQuery; \ jQuery().ready(function() { \ var prefill = []; jQuery.each(jQuery('input[name="%s_dummy"]').val().split(','),function(i,v){prefill.push({'value': v})}); jQuery("#%s").autoSuggest("%s", \ %s); });</script>""" % (name, attrs['id'], reverse('taggit-list'), js_config) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): attrs.update({"class": "hidden"}) tags = [] if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags # suitable for editing by the user tags = [o.tag for o in value.select_related('tag')] value = edit_string_for_tags(tags) elif value is not None: tags = [Tag(name=n.replace('"', '')) for n in split_strip(value)] json_view = reverse('taggit_autocomplete_jqueryui_tag_list') html = u'<div class="selector"><ul class="tags">' for tag in tags: html += (u''' <li data-tag="%(name)s"> <span class="name">%(name)s</span> <a class="remove" href="#">X</a> </li>''' % {'name': tag.name}) html += '</ul>' html += super(TagAutocomplete, self).render(name, value, attrs) html += u'<input type="text" id="%s_autocomplete"/></div>' % attrs['id'] js = u''' <script type="text/javascript"> (function (root) { root.taggit_init = root.taggit_init || []; root.taggit_init.push(['#%s_autocomplete', '%s']); })(window); </script>''' % (attrs['id'], json_view) return mark_safe("\n".join([html, js]))
def list_tags(request): try: tags = Tag.objects.filter(name__icontains=request.GET['q']) data = [{'value': edit_string_for_tags([t]), 'name': t.name} for t in tags] except MultiValueDictKeyError: data = "" return HttpResponse(simplejson.dumps(data), content_type='application/json')
def render(self, name, value, attrs=None, renderer=None): """ Render HTML code """ options = '' if value is not None and not isinstance(value, six.string_types): value = [o.tag for o in value.select_related('tag')] value = edit_string_for_tags(value) options = [ '<option value="{value}" selected>{value}</option>'.format( value=escape(six.text_type(o))) for o in parse_tags(value)] options = '\n'.join(options) html = super(TagAutocompleteWidget, self).render( name, value, attrs, renderer=renderer ) html = """<div style="display: none">%(input)s</div><select id="%(objectid)s_select2" name="%(objectid)s_select2" multiple>%(options)s</select> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { window.Froide.components.tagautocomplete.setupTagging('%(objectid)s', '%(sourceurl)s', { noResults: '%(noResults)s', searching: '%(searching)s' }) }); </script>""" % dict( input=html, objectid=attrs['id'], sourceurl=self.autocomplete_url, options=options, noResults=_('No results'), searching=_('Searching…') ) return mark_safe(html)
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['raw_url'] = bundle.obj.get_raw_url() bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() bundle.data['description_rendered'] = \ linebreaksbr(urlize(bundle.obj.description)) bundle.data['views'] = bundle.obj.views bundle.data['favs'] = bundle.obj.favs() if bundle.data['publish_date']: bundle.data['publish_date'] = \ date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A') log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append({ 'created': entry.created, 'user': entry.user, 'code': entry.code, 'diff': entry.diff }) bundle.data['log_entries'] = bundle_log_entries return bundle
def render(self, name, value, attrs=None): tags = [] if value is not None and not isinstance(value, str): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags # suitable for editing by the user tags = [o.tag for o in value.select_related('tag')] value = edit_string_for_tags(tags) elif value is not None: tags = split_strip(value) json_view = reverse('taggit_autocomplete_jqueryui_tag_list') html = '<div class="selector"><ul class="tags">' for tag in tags: html += (''' <li data-tag="%(name)s"> <span class="name">%(name)s</span> <a class="remove" href="#">X</a> </li>''' % {'name': tag}) html += '</ul>' html += super(TagAutocomplete, self).render(name, value, attrs) html += '<input type="text" id="%s_autocomplete"/></div>' % attrs['id'] js = ''' <script type="text/javascript"> (function (root) { root.taggit_init = root.taggit_init || []; root.taggit_init.push(['#%s_autocomplete', '%s']); })(window); </script>''' % (attrs['id'], json_view) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): list_view = reverse('taggit_autocomplete-list') if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) html = super(TagAutocomplete, self).render(name, value, attrs) # Activate tag-it in this field js = u""" <script type="text/javascript"> (function($) { $(document).ready(function() { $("#%(id)s").tagit({ caseSensitive: false, tagSource: function(search, showChoices) { options = this; $.getJSON("%(source)s", { q: search.term.toLowerCase() }, function(data) { showChoices(options._subtractArray(data, options.assignedTags())); }); } }); }); })(jQuery); </script> """ % ({ 'id': attrs['id'], 'source': list_view }) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) attrs['class'] = (attrs.get('class', '') + ' django-taggit-ac').strip() attrs['data-src'] = reverse('taggit_autocomplete-list') return super(TagAutocomplete, self).render(name, value, attrs)
def dehydrate(self, bundle): bundle.data["embed_url"] = bundle.obj.get_embed_url() bundle.data["raw_url"] = bundle.obj.get_raw_url() bundle.data["tags_list"] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data["full_absolute_url"] = bundle.obj.get_full_absolute_url() bundle.data["description_rendered"] = linebreaksbr( urlize(bundle.obj.description) ) bundle.data["views"] = bundle.obj.views bundle.data["favs"] = bundle.obj.favs() if bundle.data["publish_date"]: bundle.data["publish_date"] = date( bundle.data["publish_date"], "M d, Y \\a\\t h:i A" ) log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append( { "created": entry.created, "user": entry.user, "code": entry.code, "diff": entry.diff, } ) bundle.data["log_entries"] = bundle_log_entries return bundle
def render(self, name, value, attrs=None): if attrs is not None: attrs = dict(self.attrs.items() + attrs.items()) if value is not None and not isinstance(value, basestring): value = [edit_string_for_tags([o.tag]) for o in value.select_related("tag")] else: if value is not None: value = value.split(",") else: value = [] html = super(TagAutocomplete, self).render("%s_dummy" % name, ",".join(value), attrs) allow_add = "false" if "allow_add" in attrs and attrs["allow_add"]: allow_add = "true" js_config = u"""{startText: "%s", \ preFill: prefill, \ allowAdd: %s, \ allowAddMessage: "%s"}""" % ( escapejs(_("Enter Tag Here")), allow_add, escapejs(_("Please choose an existing tag")), ) js = u"""<script type="text/javascript">jQuery = django.jQuery; \ jQuery().ready(function() { \ var prefill = []; jQuery.each(jQuery('input[name="%s_dummy"]').val().split(','),function(i,v){prefill.push({'value': v})}); jQuery("#%s").autoSuggest("%s", \ %s); });</script>""" % ( name, attrs["id"], reverse("taggit-list"), js_config, ) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if attrs is not None: attrs = dict(self.attrs.items() + attrs.items()) list_view = reverse("taggit-list") if value is not None and not isinstance(value, basestring): value = simplejson.dumps( [{"value": u"%s" % edit_string_for_tags([o.tag])} for o in value.select_related("tag")] ) else: value = [] html = super(TagAutocomplete, self).render(name + "_dummy", u"", attrs) allow_add = "false" if "allow_add" in attrs and attrs["allow_add"]: allow_add = "true" js_config = ( u'{startText: "%s", \ preFill: %s, \ allowAdd: %s, \ allowAddMessage: "%s"}' % (escapejs(_("Enter Tag Here")), value, allow_add, escapejs(_("Please choose an existing tag"))) ) js = ( u'<script type="text/javascript">jQuery = django.jQuery; \ jQuery().ready(function() { jQuery("#%s").autoSuggest("%s", \ %s); });</script>' % (attrs["id"], list_view, js_config) ) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if value is not None: if isinstance(value, basestring): value = parse_tags(value) else: value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) return super(TagWidget, self).render(name, value, attrs)
def render(self, name, value, attrs=None): if value is not None: if isinstance(value, basestring): value = parse_tags(value) else: value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) return super(TagWidget, self).render(name, value, attrs)
def __init__(self, *args, **kwargs): self.page = kwargs.pop('page') super(PageEditForm, self).__init__(*args, **kwargs) if self.page.pk: self.fields['tags'].initial = edit_string_for_tags( self.page.tags.all()) self.fields['prev_revision'].queryset = self.page.revisions.all() self.fields['prev_revision'].initial = self.page.last_revision()
def taggit(request): if request.current_page: tags = get_page_tags(request.current_page) return {'taggit': {'tags': tags, 'edit_string': edit_string_for_tags(tags)} } return {}
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, str): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) rendered = super(TaggitLiveWidget, self).render(name, value, attrs) url = reverse("taggit_autocomplete_list") js = '<script type="text/javascript">(function($) { $("#%s").taggit_live({callback: "%s"}); })(jQuery || django.jQuery);</script>' % ( attrs['id'], url) return rendered + mark_safe(js)
def page_edit(request, pk): try: page = Page.objects.get(pk=pk) except Page.DoesNotExist: return redirect(reverse("astoraccount:404")) # Find the proper form for the page. form_cls = None for form in get_forms(): if type(page.specific) == form._meta.model: form_cls = form break form = None form_data = dict(instance=page.specific, initial={ "tags": edit_string_for_tags( page.specific.tags.all()).replace('"', '') }) if request.method == "POST": form = form_cls(request.POST, request.FILES, **form_data) if form.is_valid(): page = form.save() request.user.add_activity( number=Activity.UPDATE_PAGE, content_object=page, message="Analysis updated: \"%s\" id=%d type=%s" % (page.specific.title, page.id, page.specific.verbose_name.title())) action = request.POST.get("action_type", "save_draft") if action == "save_draft": messages.success(request, _("The draft has been saved."), fail_silently=True) else: pub_page = page.publish() messages.success( request, _("The analysis has been saved and published."), fail_silently=True) request.user.add_activity( number=Activity.UPDATE_PAGE, content_object=page, message="Analysis published: \"%s\" id=%d type=%s" % (page.specific.title, page.id, page.specific.verbose_name.title())) else: if form_cls: form = form_cls(**form_data) return render(request, "astoraccount/page_edit.html", {"form": form})
def render(self, name, value, attrs=None, renderer=None): if value is not None and not isinstance(value, six.string_types): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) final_attrs = self.build_attrs(attrs, extra_attrs={"name": name}) return mark_safe(render_to_string('taggit_bootstrap/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': value if value else '', 'id': final_attrs['id'] }))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags([o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_tag_it_tag_list') html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe("\n".join([html,]))
def edit_tags(value): """ Convert the "tags" value of a model into a string for use as form field value, e.g.: value="{{ f.value|edit_tags|default_if_none:'' }}" """ if value is not None and not isinstance(value, str): return edit_string_for_tags(value) return value
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags([o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_autocomplete_modified_tag_list') html = super(TagAutocomplete, self).render(name, value, attrs) js = u'<script type="text/javascript">jQuery().ready(function() { jQuery("#%s").autocomplete("%s", { multiple: true }); });</script>' % (attrs['id'], json_view) return mark_safe("\n".join([html, js]))
def _has_changed(self, initial, data): """ Called by BaseForm._get_changed_data, which sends this the form's initial value for the field and the raw value that was submitted to the form, *before it has been through any clean() methods.* This means that the initial data will (usually) be a related Tag manager, while the raw data will (usually) be a string. So, they're both converted to strings before sending them to the regular change comparison. """ if initial is not None and not isinstance(initial, basestring): initial = edit_string_for_tags([o.tag for o in initial.select_related("tag")]) if data is not None and not isinstance(data, basestring): data = edit_string_for_tags([o.tag for o in data.select_related("tag")]) return super(TagWidget, self)._has_changed(initial, data)
def render(self, name, value, attrs=None, renderer=None): """ Render HTML code """ if value is not None and not isinstance(value, six.string_types): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) # django-tagging case_sensitive = 'true' if not getattr( settings, 'FORCE_LOWERCASE_TAGS', False) else 'false' max_tag_lentgh = getattr(settings, 'MAX_TAG_LENGTH', 50) # django-tagging-autocomplete-tagit autocomplete_min_length = getattr(settings, 'TAGGING_AUTOCOMPLETE_MIN_LENGTH', 3) remove_confirmation = 'true' if getattr( settings, 'TAGGING_AUTOCOMPLETE_REMOVE_CONFIRMATION', True) else 'false' animate = 'true' if getattr(settings, 'TAGGING_AUTOCOMPLETE_ANIMATE', True) else 'false' html = super(TagAutocompleteTagIt, self).render(name, value, attrs, renderer=renderer) # Subclass this field in case you need to add some custom behaviour like custom callbacks js = """<script type="text/javascript">window.init_jQueryTagit = window.init_jQueryTagit || []; window.init_jQueryTagit.push({{ objectId: '{objectid}', sourceUrl: '{sourceurl}', fieldName: '{fieldname}', minLength: {minlength}, removeConfirmation: {removeConfirmation}, caseSensitive: {caseSensitive}, animate: {animate}, maxLength: {maxLength}, maxTags: {maxTags}, allowSpaces: true, onTagAdded : null, onTagRemoved: null, onTagClicked: null, onMaxTagsExceeded: null, placeholderText: '{placeholderText}', kind: '{kind}' }}); </script>""".format( objectid=attrs['id'], sourceurl=self.autocomplete_url() if callable(self.autocomplete_url) else self.autocomplete_url, fieldname=name, minlength=autocomplete_min_length, removeConfirmation=remove_confirmation, caseSensitive=case_sensitive, animate=animate, maxLength=max_tag_lentgh, maxTags=self.max_tags, placeholderText=_('Enter comma-separated tags here'), kind=self.tag_filter or '') return mark_safe("\n".join([html, js]))
def list_tags(request): try: tags = Tag.objects.filter(name__icontains=request.GET['q']) data = [{ 'value': edit_string_for_tags([t]), 'name': t.name } for t in tags] except MultiValueDictKeyError: data = "" return HttpResponse(simplejson.dumps(data), mimetype='application/json')
def render(self, name, value, attrs=None): list_view = reverse('taggit_tag_list') if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related('tag')]) html = super(TagAutocompleteWidget, self).render(name, value, attrs) js = u""" <script> $(function() {{ function split( val ) {{ return val.split( /,\s*/ ); }} function extractLast( term ) {{ return split( term ).pop(); }} $("#{id}")// don't navigate away from the field on tab when selecting an item .bind( "keydown", function( event ) {{ if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {{ event.preventDefault(); }} }}) .autocomplete({{ source: function( request, response ) {{ $.getJSON( "{source}", {{ term: extractLast( request.term ) }}, response ); }}, search: function() {{ // custom minLength var term = extractLast( this.value ); if ( term.length < 2 ) {{ return false; }} }}, focus: function() {{ // prevent value inserted on focus return false; }}, select: function( event, ui ) {{ var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push( "" ); this.value = terms.join( ", " ); return false; }} }}); }}); </script> """.format(id=attrs['id'], source=list_view) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags( [o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_autocomplete_modified_tag_list') html = super(TagAutocomplete, self).render(name, value, attrs) js = u'<script type="text/javascript">jQuery().ready(function() { jQuery("#%s").autocomplete("%s", { multiple: true }); });</script>' % ( attrs['id'], json_view) return mark_safe("\n".join([html, js]))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags( [o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_tag_it_tag_list') html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe("\n".join([ html, ]))
def render(self, name, value, attrs=None): attrs={'placeholder':'add new tags here'} print '----CustomTagWidjget render exicuted' #print "widget attrs", attrs #print "widget value",value #print "widget name",name if value is not None and not isinstance(value, basestring): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) #remove all quotes from tag values when rendered on form #value = re.sub(r'"', '', value) value = ""#remove exising values from form return super(CustomTagWidget, self).render(name, value, attrs)
def render(self, name, value, attrs=None, renderer=None): """ Render HTML code """ options = '' if value is not None and not isinstance(value, six.string_types): value = [o.tag for o in value.select_related('tag')] value = edit_string_for_tags(value) options = [ '<option value="{value}" selected>{value}</option>'.format( value=escape(six.text_type(o))) for o in parse_tags(value)] options = '\n'.join(options) html = super(TagAutocompleteWidget, self).render( name, value, attrs, renderer=renderer ) html = """<div style="display: none">%(input)s</div><select id="%(objectid)s_select2" name="%(objectid)s_select2" multiple>%(options)s</select> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { $('#%(objectid)s_select2').on('change.select2', function(e) { var tagString = $(this).select2('data').map(function(el){ return '"' + el.id + '"'; }).join(', '); $('#%(objectid)s').val(tagString); }).select2({ width: '75%%', tags: true, tokenSeparators: [',', ' '], ajax: { url: '%(sourceurl)s', data: function (params) { if (params.term.length === 0) { return null; } return { query: params.term }; }, processResults: function(data) { return { results: data.map(function(el) { return { id: el, text: el } }) } } } }) }); </script>""" % dict( input=html, objectid=attrs['id'], sourceurl=self.autocomplete_url, options=options ) return mark_safe(html)
def render(self, name, value, attrs={}): if value is not None and not isinstance(value, six.string_types): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) final_attrs = self.build_attrs(attrs, name=name) return mark_safe( render_to_string( 'taggit_bootstrap/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': value if value else '', 'id': final_attrs['id'] }))
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags([o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_autocomplete_modified_tag_list') if 'class' in attrs: attrs['class'] += ' autocomplete' else: attrs['class'] = 'autocomplete' attrs['autocomplete-url'] = json_view html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe(html)
def render(self, name, value, attrs=None): attrs = {'placeholder': 'add new tags here'} print 'TODO: core.models.CustomTagWidget move to widget file' #print "widget attrs", attrs #print "widget value",value #print "widget name",name if value is not None and not isinstance(value, basestring): value = edit_string_for_tags( [o.tag for o in value.select_related("tag")]) #remove all quotes from tag values when rendered on form value = re.sub(r'"', '', value) #value = ""#remove exising values from form return super(CustomTagWidget, self).render(name, value, attrs)
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['raw_url'] = bundle.obj.get_raw_url() bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() bundle.data['description_rendered'] = linebreaksbr(urlize(bundle.obj.description)) bundle.data['views'] = bundle.obj.views bundle.data['favs'] = bundle.obj.favs() if bundle.data['publish_date']: bundle.data['publish_date'] = date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A') return bundle
def dehydrate(self, bundle): bundle.data["embed_url"] = bundle.obj.get_embed_url() bundle.data["raw_url"] = bundle.obj.get_raw_url() bundle.data["tags_list"] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data["full_absolute_url"] = bundle.obj.get_full_absolute_url() bundle.data["description_rendered"] = linebreaksbr(urlize(bundle.obj.description)) bundle.data["views"] = bundle.obj.views bundle.data["favs"] = bundle.obj.favs() if bundle.data["publish_date"]: bundle.data["publish_date"] = date(bundle.data["publish_date"], "M d, Y \\a\\t h:i A") return bundle
def export_csv(cls, queryset): fields = ("id", "name", "email", "fax", "contact", "address", "url", ('classification', lambda x: x.classification.name if x.classification else None), "jurisdiction__slug", ("categories", lambda x: edit_string_for_tags(x.categories.all())), "other_names", "website_dump", "description", "request_note", "parent__name", ('regions', lambda obj: ','.join(str(x.id) for x in obj.regions.all()))) return export_csv(queryset, fields)
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() if bundle.data['user'].data['profile']['is_pro']: bundle.data['views'] = bundle.obj.views bundle.data['favs'] = bundle.obj.favs() if bundle.data['publish_date']: bundle.data['publish_date'] = date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A') return bundle
def _has_changed(self, initial, data): """ Whether the input value has changed. Used for recording in django_admin_log. Because initial is passed as a queryset, and data is a string, we need to turn the former into a string and run the latter through a function which cleans it up and sorts the tags in it. """ if initial is None: initial = "" elif hasattr(initial, 'select_related'): initial_vals = [o.tag for o in initial.select_related("tag")] initial = edit_string_for_tags(initial_vals) else: try: if len(initial) == 0: initial = "" else: initial = edit_string_for_tags(initial) except TypeError, ValueError: initial = ""
def export_csv(cls, queryset): fields = ( "id", "name", "email", "fax", "contact", "address", "url", ('classification', lambda x: x.classification.name if x.classification else None), "jurisdiction__slug", ("categories", lambda x: edit_string_for_tags(x.categories.all())), "other_names", "website_dump", "description", "request_note", "parent__name", ('regions', lambda obj: ','.join(str(x.id) for x in obj.regions.all())) ) return export_csv(queryset, fields)
def render(self, name, value, attrs=None): if value is not None and not isinstance(value, basestring): # value contains a list a TaggedItem instances # Here we retrieve a comma-delimited list of tags suitable for editing by the user. value = edit_string_for_tags( [o.tag for o in value.select_related('tag')]) json_view = reverse('taggit_autocomplete_modified_tag_list') if 'class' in attrs: attrs['class'] += ' autocomplete' else: attrs['class'] = 'autocomplete' attrs['autocomplete-url'] = json_view html = super(TagAutocomplete, self).render(name, value, attrs) return mark_safe(html)
def export_csv(cls, queryset): from django.utils import six if six.PY3: import csv else: import unicodecsv as csv s = six.StringIO() fields = ( "id", "name", "email", "contact", "address", "url", "classification", "jurisdiction__slug", "tags", "other_names", "website_dump", "description", "request_note", "parent__name", ) writer = csv.DictWriter(s, fields) writer.writeheader() for pb in queryset: d = {'tags': edit_string_for_tags(pb.tags.all())} for field in fields: if field in d: continue value = pb for f in field.split('__'): value = getattr(value, f) if value is None: break if value is None: d[field] = "" else: d[field] = value writer.writerow(d) s.seek(0) if six.PY3: return s.read() return s.read().decode('utf-8')
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['raw_url'] = bundle.obj.get_raw_url() bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() bundle.data['description_rendered'] = linebreaksbr( urlize(bundle.obj.description)) bundle.data['views'] = bundle.obj.views bundle.data['favs'] = bundle.obj.favs() if bundle.data['publish_date']: bundle.data['publish_date'] = date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A') return bundle
def __init__(self, *args, **kwargs): tags = kwargs.pop('tags', []) if tags: kwargs['initial'] = {'tags': edit_string_for_tags(tags)} autocomplete_url = kwargs.pop('autocomplete_url', None) if autocomplete_url is not None: self.tags_autocomplete_url = autocomplete_url super(TagObjectForm, self).__init__(*args, **kwargs) self.fields['tags'] = TagField( label=_("Tags"), widget=TagAutocompleteWidget( attrs={'placeholder': _('Tags')}, autocomplete_url=self.tags_autocomplete_url), help_text=_("Comma separated and quoted"))
def init_from_proposal(cls, proposal): # Right now this code smells a bit esp. with regards to tags form = cls( initial={ 'title': proposal.title, 'description': proposal.description, 'abstract': proposal.abstract, 'tags': edit_string_for_tags(proposal.tags.all()), 'language': proposal.language, 'speaker': proposal.speaker, 'additional_speakers': proposal.additional_speakers.all(), 'track': proposal.track, 'duration': proposal.duration, 'audience_level': proposal.audience_level, 'available_timeslots': proposal.available_timeslots.all(), }) return form