def construct(request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: try: form.changed_data.remove('d_tags') except: pass if len(form.changed_data) > 0: change_message.append(_('Changed %s. \n') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s". \n') % {'name': force_unicode(added_object._meta.verbose_name), 'object': force_unicode(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_('Changed %(list)s for %(name)s "%(object)s". \n') % {'list': get_text_list(changed_fields, _('and')), 'name': force_unicode(changed_object._meta.verbose_name), 'object': force_unicode(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append(_('Deleted %(name)s "%(object)s". \n') % {'name': force_unicode(deleted_object._meta.verbose_name), 'object': force_unicode(deleted_object)}) change_message = ' '.join(change_message) return change_message or _('Nothing changed.')
def revision_set_comment(form, formsets=None): """ Sets comment for revision based on changed fields """ change_message = [] if form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added %(name)s "%(object)s".') % {'name': force_text(added_object._meta.verbose_name), 'object': force_text(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append( _('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_text(changed_object._meta.verbose_name), 'object': force_text(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted %(name)s "%(object)s".') % {'name': force_text(deleted_object._meta.verbose_name), 'object': force_text(deleted_object)}) change_message = ' '.join(change_message) set_comment( change_message or _('No fields changed.'))
def parse_tags(obj, d_tags, msg=''): try: #d_tags = ['"%s"' % x.strip() for x in d_tags.split(',') if len(x.name) > 1] d_tags = ['"%s"' % x.strip() for x in d_tags.split(',') if x.strip() != ''] tags = ['"%s"' % x.name for x in obj.tags] tags_added = diff_lists(d_tags, tags) tags_removed = diff_lists(tags, d_tags) if (tags_added or tags_removed) and msg == 'Nothing changed': msg = _('Changed: \n') if tags_added: msg += _('Tags added: %s' % get_text_list(tags_added, _('and'))) if tags_added and tags_removed: msg += '\n' if tags_removed: msg += _('Tags removed: %s' % get_text_list(tags_removed, _('and'))) return msg except: return ''
def _construct_change_message(request, form, formsets): """ Construct a change message from a changed object. Можно использовать для reversion. """ change_message = [] if form.changed_data: change_message.append(_("Changed %s.") % get_text_list(form.changed_data, _("and"))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added %(name)s "%(object)s".') % {"name": force_unicode(added_object._meta.verbose_name), "object": force_unicode(added_object)} ) for changed_object, changed_fields in formset.changed_objects: change_message.append( _('Changed %(list)s for %(name)s "%(object)s".') % { "list": get_text_list(changed_fields, _("and")), "name": force_unicode(changed_object._meta.verbose_name), "object": force_unicode(changed_object), } ) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted %(name)s "%(object)s".') % { "name": force_unicode(deleted_object._meta.verbose_name), "object": force_unicode(deleted_object), } ) change_message = " ".join(change_message) return change_message or _("No fields changed.")
def log_objects_related(user, **kwargs): message_parts = [] for added_object in kwargs.get("created", ()): message_parts.append('added %(name)s "%(object)s"' % {'name': force_unicode(added_object._meta.verbose_name), 'object': force_unicode(added_object)}) for changed_object, changed_fields in kwargs.get("changed", ()): message_parts.append('changed %(list)s for %(name)s "%(object)s"' % {'list': get_text_list(changed_fields, 'and'), 'name': force_unicode(changed_object._meta.verbose_name), 'object': force_unicode(changed_object)}) for deleted_object in kwargs.get("deleted", ()): message_parts.append('deleted %(name)s "%(object)s"' % {'name': force_unicode(deleted_object._meta.verbose_name), 'object': force_unicode(deleted_object)}) message = get_text_list(message_parts, "and").capitalize() prefix_object = kwargs.get("prefix_object", None) if prefix_object: return "%s: %s: %s" % (prefix_object._meta.verbose_name.capitalize(), prefix_object.pk, message) return message
def construct_change_message(self, request, form, formsets, add=False): from django.utils.encoding import force_text from django.utils.text import get_text_list from django.utils.translation import ugettext as _ if (request.POST.get('post') and request.POST.get('post') == 'Yes') or not request.POST.get('filter_previous'): print "Creating change message" change_message = [] if add: change_message.append(_('Added.')) elif form.changed_data: change_message.append(_('Changed {}.'.format(get_text_list(form.changed_data, _('and'))))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added {name} "{object}".'.format(name=force_text(added_object._meta.verbose_name), object=force_text(added_object)))) for changed_object, changed_fields in formset.changed_objects: change_message.append(_( 'Changed {list} for {name} "{object}"'.format( list=get_text_list(changed_fields, _('and')), name=force_text( changed_object._meta.verbose_name), object=force_text(changed_object)))) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted {name} "{object}".'.format( name=force_text(deleted_object._meta.verbose_name), object=force_text(deleted_object)))) change_message = ' '.join(change_message) return change_message or _('No fields changed.') else: print "Not creating change message" return _('No fields changed.')
def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object """ change_message = [] if form.changed_data: change_message.append( _('Changed {0}.'.format( get_text_list(form.changed_data, _('and'))))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added {0} "{1}".'.format( force_text(added_object._meta.verbose_name), force_text(added_object)))) for changed_object, changed_fields in formset.changed_objects: change_message.append( _('Changed {0} for {1} "{2}".'.format( get_text_list(changed_fields, _('and')), force_text(changed_object._meta.verbose_name), force_text(changed_object)))) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted {0} "{1}".'.format( force_text(deleted_object._meta.verbose_name), force_text(deleted_object)))) change_message = ' '.join(change_message) return change_message or _('No fields changed.')
def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s".') % {'name': added_object._meta.verbose_name, 'object': force_unicode(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': changed_object._meta.verbose_name, 'object': force_unicode(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append(_('Deleted %(name)s "%(object)s".') % {'name': deleted_object._meta.verbose_name, 'object': force_unicode(deleted_object)}) change_message = ' '.join(change_message) return change_message or _('No fields changed.')
def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: change_message.append(_("Changed %s.") % get_text_list(form.changed_data, _("and"))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added %(name)s "%(object)s".') % {"name": added_object._meta.verbose_name, "object": added_object} ) for changed_object, changed_fields in formset.changed_objects: change_message.append( _('Changed %(list)s for %(name)s "%(object)s".') % { "list": get_text_list(changed_fields, _("and")), "name": changed_object._meta.verbose_name, "object": changed_object, } ) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted %(name)s "%(object)s".') % {"name": deleted_object._meta.verbose_name, "object": deleted_object} ) change_message = " ".join(change_message) return change_message or _("No fields changed.")
def construct_change_message(request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form and form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: # Translators: A message in the version history of an item saying that an object with the name (name) of the type (object) has been created in the registry. change_message.append(_('Added %(name)s "%(object)s".') % {'name': force_text(added_object._meta.verbose_name), 'object': force_text(added_object)}) for changed_object, changed_fields in formset.changed_objects: # Translators: A message in the version history of an item saying that an object with the name (name) of the type (object) has been changed in the registry. change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_text(changed_object._meta.verbose_name), 'object': force_text(changed_object)}) for deleted_object in formset.deleted_objects: # Translators: A message in the version history of an item saying that an object with the name (name) of the type (object) has been deleted from the registry. change_message.append(_('Deleted %(name)s "%(object)s".') % {'name': force_text(deleted_object._meta.verbose_name), 'object': force_text(deleted_object)}) change_message = ' '.join(change_message) return change_message or _('No fields changed.')
def save_change(self, request, form, formsets=None): """ Saves the object in the "change" stage and returns an HttpResponseRedirect. `form` is a bound Form instance that's verified to be valid. `formsets` is a sequence of InlineFormSet instances that are verified to be valid. """ from django.contrib.admin.models import LogEntry, CHANGE opts = self.model._meta new_object = form.save(commit=True) pk_value = new_object._get_pk_val() if formsets: for formset in formsets: formset.save() # Construct the change message. change_message = [] if form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s".') % {'name': added_object._meta.verbose_name, 'object': added_object}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': changed_object._meta.verbose_name, 'object': changed_object}) for deleted_object in formset.deleted_objects: change_message.append(_('Deleted %(name)s "%(object)s".') % {'name': deleted_object._meta.verbose_name, 'object': deleted_object}) change_message = ' '.join(change_message) if not change_message: change_message = _('No fields changed.') LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(self.model).id, pk_value, force_unicode(new_object), CHANGE, change_message) msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object} if "_continue" in request.POST: request.user.message_set.create(message=msg + ' ' + _("You may edit it again below.")) if '_popup' in request.REQUEST: return HttpResponseRedirect(request.path + "?_popup=1") else: return HttpResponseRedirect(request.path) elif "_saveasnew" in request.POST: request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object}) return HttpResponseRedirect("../%s/" % pk_value) elif "_addanother" in request.POST: request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name)) return HttpResponseRedirect("../add/") else: request.user.message_set.create(message=msg) return HttpResponseRedirect("../")
def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: changed_data_msg = [] for field in form.changed_data: initial=form.initial.get(field) try: value=getattr(form.instance, field) except: value=form.initial.get(field) #ForeignKey try: if type(form.instance._meta.get_field(field)) == models.fields.related.ForeignKey: initial = getattr(form.instance, field).__class__.objects.get(pk=initial) except: pass #ManyToManyFields try: if type(form.instance._meta.get_field(field)) == models.fields.related.ManyToManyField: value = value.all().values_list('pk', flat=True) except: pass #Choices try: if type(form.instance._meta.get_field(field)) == models.fields.CharField and hasattr(form.instance._meta.get_field(field), 'choices'): try: initial = dict(type(form.instance)._meta.get_field(field).get_choices())[initial] except: pass try: value = dict(type(form.instance)._meta.get_field(field).get_choices())[value] except: pass except: pass if initial != value: changed_data_msg.append(u'%s de %s para %s' % (force_unicode(field), force_unicode(initial), force_unicode(value))) if changed_data_msg: change_message.append(_(u'Changed %s.') % get_text_list(changed_data_msg, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_(u'Added %(name)s "%(object)s".') % {'name': force_unicode(added_object._meta.verbose_name), 'object': force_unicode(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_(u'Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_unicode(changed_object._meta.verbose_name), 'object': force_unicode(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append(_(u'Deleted %(name)s "%(object)s".') % {'name': force_unicode(deleted_object._meta.verbose_name), 'object': force_unicode(deleted_object)}) change_message = ' '.join(change_message) return change_message or _(u'No fields changed.')
def form(self, form): obj = form.instance action = self._discover_action(obj) message_parts = [] if action == History.ADDITION: for field_name, field in self._form_fields_filter(form): message_parts.append( _("%(attribute)s set to '%(value)s'") % {"attribute": field.label, "value": self._get_form_field_value(form, field_name)} ) elif action == History.CHANGE: for field_name, field in self._form_fields_filter(form): message_parts.append( _("%(attribute)s changed to '%(value)s'") % {"attribute": field.label, "value": self._get_form_field_value(form, field_name)} ) if message_parts: message = u"%s." % get_text_list(message_parts, _(u"and")) else: message = "" return History.objects.create(content_object=obj, message=message, action=action)
def change_view(self, request, object_id, form_url='', extra_context=None): message = get_object_or_404(Message, id=object_id) if not self.has_change_permission(request, message): raise PermissionDenied if request.method == 'POST': form = ChangeContestMessageForm(message.kind, request, request.POST, instance=message) if form.is_valid(): if form.changed_data: change_message = _("Changed %s.") % \ get_text_list(form.changed_data, _("and")) else: change_message = _("No fields changed.") if 'kind' in form.changed_data and \ form.cleaned_data['kind'] == 'PUBLIC': msg = form.save(commit=False) msg.mail_sent = False msg.save() else: form.save() super(MessageAdmin, self).log_change(request, message, change_message) return redirect('contest_messages', contest_id=request.contest.id) else: form = ChangeContestMessageForm(message.kind, request, instance=message) return TemplateResponse(request, 'admin/questions/change_message.html', {'form': form, 'message': message})
def clean_file(self): ''' Validation on uploaded file. Checks if file extension is allowed. ''' uploaded_file = self.cleaned_data['file'] #If file not actually submitted, skip clean. if not uploaded_file: return None try: #Check for allowed extensions: ext = os.path.splitext(uploaded_file.name)[1] ext = ext[1:] #get rid of . ext = ext.lower() #make lowercase if ext not in settings.ALLOWED_UPLOAD_EXTENSIONS: valid_files = ['.%s' % i for i in settings.ALLOWED_UPLOAD_EXTENSIONS] valid_files = get_text_list(valid_files, ', and') raise forms.ValidationError( 'Not a valid file! Only %s files are allowed!' % valid_files ) #Check for allowed file size: if uploaded_file.size > settings.MAXIMUM_UPLOAD_SIZE_BYTES: raise forms.ValidationError( 'File is too large! Only files with size <= %s MB are allowed!' % settings.MAXIMUM_UPLOAD_SIZE_MB ) except AttributeError: #Means that the uploaded_file is not a File object but rather a string #denoting an existing file that we do not want changed. pass #Otherwise, everything checks out: return uploaded_file
def handle(self, *args, **options): if len(args) != 0: raise CommandError("Command doesn't accept any arguments") locale = options.get('locale') domain = options.get('domain') verbosity = int(options.get('verbosity')) process_all = options.get('all') extensions = options.get('extensions') symlinks = options.get('symlinks') ignore_patterns = options.get('ignore_patterns') if options.get('use_default_ignore_patterns'): ignore_patterns += ['CVS', '.*', '*~'] ignore_patterns = list(set(ignore_patterns)) no_wrap = options.get('no_wrap') no_obsolete = options.get('no_obsolete') if domain == 'djangojs': extensions = handle_extensions(extensions or ['js']) else: extensions = handle_extensions(extensions or ['html']) if verbosity > 1: sys.stdout.write('examining files with the extensions: %s\n' % get_text_list(list(extensions), 'and')) make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns, no_wrap, no_obsolete)
def check_unique_together(sender, **kwargs): """ Check models unique_together manually. Django enforced unique together only the database level, but some databases (e.g. SQLite) don't support this. """ instance = kwargs["instance"] for field_names in sender._meta.unique_together: model_kwargs = {} for field_name in field_names: try: data = getattr(instance, field_name) except FieldDoesNotExist: # e.g.: a missing field, which is however necessary. # The real exception on model creation should be raised. continue model_kwargs[field_name] = data query_set = sender.objects.filter(**model_kwargs) if instance.pk != None: # Exclude the instance if it was saved in the past query_set = query_set.exclude(pk=instance.pk) count = query_set.count() if count > 0: field_names = get_text_list(field_names, _('and')) msg = _(u"%(model_name)s with this %(field_names)s already exists.") % { 'model_name': unicode(instance.__class__.__name__), 'field_names': unicode(field_names) } raise IntegrityError(msg)
def as_value(self, data, context): # The queries of the current URL, not using sequences here # since the order of sorting arguments matter url = URLObject(context['request'].get_full_path()) queries = url.query.dict name, orderings = data['with'], data['by'] query = self.find_query(queries.get(name), orderings, orderings[0]) url = url.set_query_param(name, query) # If this isn't a block tag we probably only want the URL if not self._meta.block: return url label = self.nodelist.render(context) if not label.strip(): raise TemplateSyntaxError("No label was specified") parts = [] for part in query.split(','): part = part.strip() if part.startswith('-'): part = part.lstrip('-') # Translators: Used in title of descending sort fields text = _("'%(sort_field)s' (desc)") else: # Translators: Used in title of ascending sort fields text = _("'%(sort_field)s' (asc)") parts.append(text % {'sort_field': part}) # Translators: Used for the link/form input title excluding the sort fields title = (_('Sort by: %(sort_fields)s') % {'sort_fields': get_text_list(parts, _('and'))}) extra_context = dict(data, title=title, label=label, url=url, query=query) return render_to_string(self.using(data), extra_context, context)
def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance.pk is None: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance representation, # suitable to be an item in a list. _('%(class_name)s %(instance)s') % { 'class_name': p._meta.verbose_name, 'instance': p} ) params = {'class_name': self._meta.model._meta.verbose_name, 'instance': self.instance, 'related_objects': get_text_list(objs, _('and'))} msg = _("Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s") raise ValidationError(msg, code='deleting_protected', params=params)
def handle_noargs(self, *args, **options): locale = options.get('locale') domain = options.get('domain') verbosity = int(options.get('verbosity')) process_all = options.get('all') extensions = options.get('extensions') symlinks = options.get('symlinks') ignore_patterns = options.get('ignore_patterns') if options.get('use_default_ignore_patterns'): ignore_patterns += ['CVS', '.*', '*~'] ignore_patterns = list(set(ignore_patterns)) no_wrap = options.get('no_wrap') no_location = options.get('no_location') no_obsolete = options.get('no_obsolete') if domain == 'djangojs': exts = extensions if extensions else ['js'] else: exts = extensions if extensions else ['html', 'txt'] extensions = handle_extensions(exts) if verbosity > 1: self.stdout.write('examining files with the extensions: %s\n' % get_text_list(list(extensions), 'and')) make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns, no_wrap, no_location, no_obsolete, self.stdout)
def clean_detail_record(self, record): try: record['inspection_date'] = parse_date(record['inspection_date'], '%m/%d/%Y') except KeyError: # Sometimes the inspection_date is missing, for whatever reason. # Raise a warning in this case. self.logger.info('Record %r has no inspection_date. Skipping.', record) raise SkipRecord record['violations'] = [(i[0], i[1] == 'Yes') for i in detail_violations_re.findall(record['violations'])] # Determine the notes (a textual representation of which violations, # if any, were corrected during the inspection). corrected_violations = [v[0] for v in record['violations'] if v[1]] if record['violations']: if not corrected_violations: if len(corrected_violations) == 1: note_bit = 'violation was not' else: note_bit = 'violations were not' elif len(corrected_violations) == 1: if len(record['violations']) == 1: note_bit = 'violation was' else: note_bit = '%s violation was' % corrected_violations[0] else: # Multiple corrected violations. note_bit = '%s violations were' % get_text_list(corrected_violations, 'and') notes = 'The %s corrected during the inspection.' % note_bit else: # There's no need for notes if there were no violations. notes = '' record['notes'] = notes return record
def clean(self, value): """ Checks that the given string has no profanities in it. This does a simple check for whether each profanity exists within the string, so 'f**k' will catch 'm**********r' as well. Raises a ValidationError such as: Watch your mouth! The words "f--k" and "s--t" are not allowed here. """ value= value.lower() # normalize words_seen= [w for w in settings.PROFANITIES_LIST if w in value] if words_seen: from django.utils.text import get_text_list plural= len(words_seen) raise forms.ValidationError, ungettext("Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], _('and')) """ Cleans non-allowed HTML from the input """ value= super(CleanCharField, self).clean(value) soup= BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): comment.extract() for tag in soup.findAll(True): if tag.name not in self.valid_tags: tag.hidden= True tag.attrs= [(attr, val) for attr, val in tag.attrs if attr in self.valid_attrs] return soup.renderContents().decode('utf8')
def get_unique_error_message(self, unique_check): if len(unique_check) == 1: return ugettext("Please correct the duplicate data for %(field)s.") % {"field": unique_check[0]} else: return ugettext("Please correct the duplicate data for %(field)s, " "which must be unique.") % { "field": get_text_list(unique_check, unicode(_("and"))) }
def get_rendered_byline_html(self): """ Return a pretty HTML link list of all the Authors in the bylines. """ author_list = self.get_byline_list() author_list.sort(key=lambda x: x.name) return get_text_list(['<a href="%s">%s</a>' % (i.get_absolute_url(), i.name) for i in author_list], "and")
def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag: '%s', expected %s" % (command, get_text_list(["'%s'" % p for p in parse_until])), ) raise self.error(token, "Invalid block tag: '%s'" % command)
def construct_change_message(self, form): change_message = [] if form.changed_data: lst = get_text_list(form.changed_data, _('and')) change_message.append(_('Changed %s.') % lst) change_message = u' '.join(change_message) return unicode(change_message or _('No fields changed.'))
def construct_change_message(request, form, formsets=None): """ Constructs a change message from a changed form and optionally a list of formsets. """ change_message = [] labels = None use_labels = getattr(settings, "USERLOG_LABEL_NAMES", False) if form.changed_data: if use_labels is True: labels = [form.fields[field].label for field in form.changed_data] change_message.append(_("Changed %s." % get_text_list(labels or form.changed_data, _("and")))) if formsets: for formset in formsets: # New objects for obj in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s".') % { "name": force_unicode(obj._meta.verbose_name), "object": force_unicode(obj) }) # Changed objects for obj, changed_fields in formset.changed_objects: labels = None # TODO: figure out a reliable way of solving this # if use_labels is True: # labels = [f.verbose_name for f in obj._meta.fields if f.name in changed_fields] change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % { "list": get_text_list(labels or changed_fields, _("and")), "name": force_unicode(obj._meta.verbose_name), "object": force_unicode(obj) }) # Deleted objects for obj in formset.deleted_objects: change_message.append(_('Deleted %(name) "%(object)".') % { "name": force_unicode(obj._meta.verbose_name), "object": force_unicode(obj) }) change_message = " ".join(change_message) return change_message or _("No fields changed.")
def get_help_text(self, field_name, model_name): searchable_fields = self.related_search_fields.get(field_name, None) if searchable_fields: help_kwargs = { 'model_name': model_name, 'field_list': get_text_list(searchable_fields, _('and')), } return _('Use el campo de la izquierda para buscar en %(model_name)s escriba cualquier %(field_list)s.') % help_kwargs return ''
def get_help_text(self, field_name, model_name): searchable_fields = self.related_search_fields.get(field_name, None) if searchable_fields: help_kwargs = { 'model_name': model_name, 'field_list': get_text_list(searchable_fields, _('and')), } return _('Use the left field to do %(model_name)s lookups in the fields %(field_list)s.') % help_kwargs return ''
def change_message(self): change_message = [] if self.org_obj is None: change_message.append(_("Added.")) elif self.form_obj.changed_data: change_message.append(_("Changed %s.") % get_text_list(self.form_obj.changed_data, _("and"))) change_message = " ".join(change_message) return change_message or _("No fields changed.")
def get_unique_error_message(self, unique_check): if len(unique_check) == 1: return ugettext( "Please correct the duplicate data for %(field)s.") % { "field": unique_check[0], } else: return ugettext("Please correct the duplicate data for %(field)s, " "which must be unique.") % { "field": get_text_list(unique_check, unicode(_("and"))), }
def get_change_message(self): """ If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ if self.change_message and self.change_message[0] == "[": try: change_message = json.loads(self.change_message) except json.JSONDecodeError: return self.change_message messages = [] for sub_message in change_message: if "added" in sub_message: if sub_message["added"]: sub_message["added"]["name"] = gettext( sub_message["added"]["name"]) messages.append( gettext("Added {name} “{object}”.").format( **sub_message["added"])) else: messages.append(gettext("Added.")) elif "changed" in sub_message: sub_message["changed"]["fields"] = get_text_list( [ gettext(field_name) for field_name in sub_message["changed"]["fields"] ], gettext("and"), ) if "name" in sub_message["changed"]: sub_message["changed"]["name"] = gettext( sub_message["changed"]["name"]) messages.append( gettext("Changed {fields} for {name} “{object}”."). format(**sub_message["changed"])) else: messages.append( gettext("Changed {fields}.").format( **sub_message["changed"])) elif "deleted" in sub_message: sub_message["deleted"]["name"] = gettext( sub_message["deleted"]["name"]) messages.append( gettext("Deleted {name} “{object}”.").format( **sub_message["deleted"])) change_message = " ".join(msg[0].upper() + msg[1:] for msg in messages) return change_message or gettext("No fields changed.") else: return self.change_message
def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until]), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'" % (token.lineno, command))
def get_change_message(form): """ Creates a list of changes made from a form. """ change_message = [] if not form: return '' if form.changed_data: change_message = (ugettext('Changed %s.') % get_text_list(form.changed_data, ugettext('and'))) return change_message or ugettext('No fields changed.')
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.sumarizador.filtros: context['para'] = get_text_list([ objeto.nombre_completo() for objeto in self.sumarizador.filtros ], " y ") else: context['para'] = 'todo el país' pk = self.kwargs.get('pk') categoria = get_object_or_404(Categoria, id=pk) context['object'] = categoria context['categoria_id'] = categoria.id resultados = self.get_resultados(categoria) context['resultados'] = resultados context['show_plot'] = settings.SHOW_PLOT # Agregamos al contexto el modo de elección; para cada partido decidimos # qué porcentaje vamos a visualizar (porcentaje_positivos o # porcentaje_validos) dependiendo del tipo de elección. context['modo_eleccion'] = settings.MODO_ELECCION # Para no hardcodear las opciones en el html las agregamos al contexto. context['modo_paso'] = settings.ME_OPCION_PASO context['modo_generales'] = settings.ME_OPCION_GEN context['mostrar_electores'] = not settings.OCULTAR_CANTIDADES_DE_ELECTORES if settings.SHOW_PLOT: chart = self.get_plot_data(context['resultados']) context['plot_data'] = chart context['chart_values'] = [v['y'] for v in chart] context['chart_keys'] = [v['key'] for v in chart] context['chart_colors'] = [v['color'] for v in chart] # Las pestañas de categorías que se muestran son las que sean # comunes a todas las mesas filtradas. # Para el cálculo se filtran categorías activas que estén relacionadas # a las mesas. categorias = self.sumarizador.categorias() if self.ocultar_sensibles: categorias = categorias.exclude(sensible=True) context['categorias'] = categorias.order_by('id') context['distritos'] = Distrito.objects.all().prefetch_related( 'secciones_politicas', 'secciones', 'secciones__circuitos' ).order_by('numero') return context
def test_get_text_list(self): self.assertEqual(text.get_text_list(['a', 'b', 'c', 'd']), 'a, b, c or d') self.assertEqual(text.get_text_list(['a', 'b', 'c'], 'and'), 'a, b and c') self.assertEqual(text.get_text_list(['a', 'b'], 'and'), 'a and b') self.assertEqual(text.get_text_list(['a']), 'a') self.assertEqual(text.get_text_list([]), '') with override('ar'): self.assertEqual(text.get_text_list(['a', 'b', 'c']), "a، b أو c")
def check_model_is_unique_with_conditions(model_instance, unique_fields, qs_conditions=None, error_message=None, error_field=None, case_insensitive=False): """ Checks the given model instance is unique with respect to ``unique_fields``. ``qs_conditions`` is a dict with additional keyword args added to the queryset when performing the unique check. For example, to skip the unique check for inactive items. ``error_message`` specified the error to display of the unique check fails. If ``None``, one is automatically created. ``error_field`` is the field to which to assign the error message, or None to just assign to the ``__all__`` list. ``case_insensitive`` indicates to perform insensitive string matching on the field values. Eg.:: def clean(): check_model_unique_with_conditions(self, ('name', 'type'), {'is_active': True}) """ model = type(model_instance) filter_kwargs = {(f + ('__iexact' if case_insensitive else '')): getattr(model_instance, f) for f in unique_fields} if qs_conditions is not None: filter_kwargs.update(qs_conditions) qs = model.objects.filter(**filter_kwargs) if model_instance.pk is not None: qs = qs.exclude(pk=model_instance.pk) if qs.count() > 0: if error_message is None: model_name = str(model._meta.verbose_name) field_labels = [ model._meta.get_field(f).verbose_name for f in unique_fields ] field_labels = str(get_text_list(field_labels, _('and'))) error_message = _('A {} with this {} already exists.').format( model_name, field_labels) if error_field is None: raise ValidationError(error_message) else: raise ValidationError({error_field: [error_message]})
def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ from django.utils.encoding import force_text from django.utils.text import get_text_list change_message = [] if form.changed_data: change_message.append( _('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append( _('Added %(name)s "%(object)s".') % { 'name': force_text( added_object._meta.verbose_name), 'object': force_text(added_object) }) for changed_object, changed_fields in formset.changed_objects: change_message.append( _('Changed %(list)s for %(name)s "%(object)s".') % { 'list': get_text_list(changed_fields, _('and')), 'name': force_text( changed_object._meta.verbose_name), 'object': force_text(changed_object) }) for deleted_object in formset.deleted_objects: change_message.append( _('Deleted %(name)s "%(object)s".') % { 'name': force_text( deleted_object._meta.verbose_name), 'object': force_text(deleted_object) }) change_message = ' '.join(change_message) return change_message or _('No fields changed.')
def get_change_message(self): """ If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ if self.change_message and self.change_message[0] == '[': try: change_message = json.loads(self.change_message) except json.JSONDecodeError: return self.change_message messages = [] for sub_message in change_message: if 'added' in sub_message: if sub_message['added']: sub_message['added']['name'] = gettext( sub_message['added']['name']) messages.append( gettext('Added {name} “{object}”.').format( **sub_message['added'])) else: messages.append(gettext('Added.')) elif 'changed' in sub_message: sub_message['changed']['fields'] = get_text_list([ gettext(field_name) for field_name in sub_message['changed']['fields'] ], gettext('and')) if 'name' in sub_message['changed']: sub_message['changed']['name'] = gettext( sub_message['changed']['name']) messages.append( gettext('Changed {fields} for {name} “{object}”.'). format(**sub_message['changed'])) else: messages.append( gettext('Changed {fields}.').format( **sub_message['changed'])) elif 'deleted' in sub_message: sub_message['deleted']['name'] = gettext( sub_message['deleted']['name']) messages.append( gettext('Deleted {name} “{object}”.').format( **sub_message['deleted'])) change_message = ' '.join(msg[0].upper() + msg[1:] for msg in messages) return change_message or gettext('No fields changed.') else: return self.change_message
def get_module_description(self) -> str: collecting = { "date of birth": self.collect_date_of_birth, "gender": self.collect_gender, "headphone type": True, # "headphone make": self.collect_headphone_make, # "headphone model": self.collect_headphone_model, # "headphone label": self.collect_headphone_label, "device make and model": True, "OS name and version": True, } text = get_text_list( [key for key, value in collecting.items() if value], "and") return "Collecting " + text
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", len(bad_words)) % get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) return comment
def save(self, *args, **kwargs): # TODO Mandar con Exception no con ValidationError if normalize( 'NFKD', u'%s %s' % (self.first_name, self.last_name)).encode( 'ascii', 'ignore').lower() in list( normalize('NFKD', u'%s %s' % (c['first_name'], c['last_name'])).encode( 'ascii', 'ignore').lower() for c in Person.objects.values('first_name', 'last_name').exclude( pk=self.pk).filter(identity_type=self.identity_type, identity_num=self.identity_num)): raise Exception( _(u'%(model_name)s with this %(field_label)s already exists.') % { 'model_name': _('Person'), 'field_label': get_text_list( (capfirst(_('first name')), capfirst(_('last name')), capfirst(_('number')), capfirst(_('Type'))), _('and')), }) if Person.objects.exclude(id=self.id).filter( identity_type=self.identity_type, identity_num=self.identity_num).count() > 0: raise Exception( _(u'%(model_name)s with this %(field_label)s already exists.') % { 'model_name': _('Person'), 'field_label': get_text_list((capfirst(_('number')), capfirst(_('Type'))), _('and')), }) super(Person, self).save(*args, **kwargs)
def construct_change_message(form=None, formsets=None): """ Construct a description text message with a brief explanation of the changes. """ message = [] if form and form.changed_data: message.append( _(u'Changed fields: %s.') % get_text_list(form.changed_data, _('and'))) if formsets: message.extend(construct_message_from_formset(formsets)) message = u'\n'.join(message) return message or _(u'No fields changed.')
def hasNoProfanities(field_data, all_data): """ Checks that the given string has no profanities in it. This does a simple check for whether each profanity exists within the string, so 'f**k' will catch 'm**********r' as well. Raises a ValidationError such as: Watch your mouth! The words "f--k" and "s--t" are not allowed here. """ field_data = field_data.lower() # normalize words_seen = [w for w in settings.PROFANITIES_LIST if w in field_data] if words_seen: from django.utils.text import get_text_list plural = len(words_seen) > 1 raise ValidationError, ngettext("Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and')
def description(self): descriptions = [i.description for i in self.operations if i.description] # we want to group the description of all of the attachments together attachment_count = len(self.attachments.all()) if attachment_count: descriptions.append( ungettext( 'added %(count)s attachment', 'added %(count)s attachments', attachment_count ) % {'count': attachment_count} ) return get_text_list(descriptions, 'and')
def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], 'or'), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command))
def clean_content(self): """ If REVIEWS_ALLOW_PROFANITIES is False, check that the review doesn't contain anything in PROFANITIES_LIST. """ content = self.cleaned_data["content"] if REVIEWS_ALLOW_PROFANITIES == False: bad_words = [w for w in settings.PROFANITIES_LIST if w in content.lower()] if bad_words: plural = len(bad_words) > 1 raise forms.ValidationError(ngettext( "he word %s is not allowed here.", "The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) return content
def test_get_text_list(self): self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d") self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c") self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b") self.assertEqual(text.get_text_list(["a"]), "a") self.assertEqual(text.get_text_list([]), "") with override("ar"): self.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c")
def action_message_to_list(action: LogEntry) -> list: """ Retrieves a formatted list with all actions taken by a user given a log entry object """ messages = [] if action.change_message and action.change_message[0] == "[": try: change_message = json.loads(action.change_message) except json.JSONDecodeError: return [action.change_message] for sub_message in change_message: if "added" in sub_message: if sub_message["added"]: sub_message["added"]["name"] = gettext( sub_message["added"]["name"]) messages.append( gettext("Added {name} “{object}”.").format( **sub_message["added"])) else: messages.append(gettext("Added.")) elif "changed" in sub_message: sub_message["changed"]["fields"] = get_text_list( [ gettext(field_name) for field_name in sub_message["changed"]["fields"] ], gettext("and"), ) if "name" in sub_message["changed"]: sub_message["changed"]["name"] = gettext( sub_message["changed"]["name"]) messages.append( gettext("Changed {fields} for {name} “{object}”."). format(**sub_message["changed"])) else: messages.append( gettext("Changed {fields}.").format( **sub_message["changed"])) elif "deleted" in sub_message: sub_message["deleted"]["name"] = gettext( sub_message["deleted"]["name"]) messages.append( gettext("Deleted {name} “{object}”.").format( **sub_message["deleted"])) return messages if len(messages) else [action.change_message]
def handle(self, **options): last_week = timezone.now() - timedelta(days=7) flagging_filter = ( Q(last_crawled=None) | Q(last_crawled__lt=last_week) ) & Q( skip_crawl=False ) flagged_blogs = Blog.objects.filter(flagging_filter).distinct() log.debug( 'Notifying %s blog owners about blog crawling errors', flagged_blogs.count(), ) if not settings.DEBUG: yes_or_no = input('Are you sure you want to continue? [y/N]: ') if yes_or_no.lower().strip()[:1] != 'y': return # Skip crawls on these blogs in future, until the feed_url changes notified = set() notify_failed = set() ids = flagged_blogs.order_by('user').distinct('user').values_list( 'user', flat=True ) users = User.objects.filter(id__in=ids) zulip_members = Z.get_members() admins = User.objects.filter(is_staff=True).exclude(hacker=None) links = [Z.get_pm_link(admin, zulip_members) for admin in admins] links = get_text_list(links, 'or') debug = settings.DEBUG for user in Z.guess_zulip_emails(users, zulip_members): blogs = flagged_blogs.filter(user=user) if Z.notify_uncrawlable_blogs(user, blogs, links, debug=debug): notified.add(user.email) else: notify_failed.add(user.email) # Logging notification success/failure if notified: flagged_blogs.filter(user__email__in=notified).update( skip_crawl=True ) log.debug( 'Notified %s blog owners and turned off crawling', len(notified), ) if notify_failed: log.debug('Failed to notify %s users:', len(notify_failed)) log.debug('\n'.join(notify_failed))
def check_unique_together(sender, **kwargs): """ Check models unique_together manually. Because Django will only enforced unique together at database level with UNIQUE, but some databases (e.g. SQLite) doesn't support this. NOTE: SQLite supports UNIQUE since 2.0 (from 2001) ! usage: from django.db.models import signals from django_tools.model_utils import check_unique_together signals.pre_save.connect(check_unique_together, sender=MyModelClass) or use: from django_tools.model_utils import auto_add_check_unique_together auto_add_check_unique_together(MyModelClass) This will add the signal only if a Database doesn't support UNIQUE, see below. """ instance = kwargs["instance"] for field_names in sender._meta.unique_together: model_kwargs = {} for field_name in field_names: try: data = getattr(instance, field_name) except FieldDoesNotExist: # e.g.: a missing field, which is however necessary. # The real exception on model creation should be raised. continue model_kwargs[field_name] = data query_set = sender.objects.filter(**model_kwargs) if instance.pk != None: # Exclude the instance if it was saved in the past query_set = query_set.exclude(pk=instance.pk) count = query_set.count() if count > 0: field_names = get_text_list(field_names, _('and')) msg = _(u"%(model_name)s with this %(field_names)s already exists." ) % { 'model_name': unicode(instance.__class__.__name__), 'field_names': unicode(field_names) } raise IntegrityError(msg)
def clean_identity_numxx(self): identity_num = self.cleaned_data['identity_num'] identity_type = self.cleaned_data['identity_type'] if Person.objects.exclude(id=self.instance.person.id).filter( identity_type=self.instance.person.identity_type, identity_num=self.instance.person.identity_num).count() > 0: raise forms.ValidationError( _(u'%(model_name)s with this %(field_label)s already exists.xxx' ) % { 'model_name': capfirst(_('Person')), 'field_label': get_text_list( (capfirst(_('number')), capfirst(_('Type'))), _('and')), }) return identity_num
def validate(self, value): super(ImageURLField, self).validate(value) if value == '' or not self.validate_image: return try: filesize, dimensions, format = self._get_image_details(value) if dimensions is None or format is None: raise forms.ValidationError( 'Could not retrieve image details from this URL.') if self.max_filesize is not None and filesize > self.max_filesize: raise forms.ValidationError( 'The image at this URL is %s large - it must be at most %s.' % ( filesizeformat(filesize), filesizeformat(self.max_filesize))) if self.min_filesize is not None and filesize < self.min_filesize: raise forms.ValidationError( 'The image at this URL is %s large - it must be at least %s.' % ( filesizeformat(filesize), filesizeformat(self.min_filesize))) if self.max_width is not None and dimensions[0] > self.max_width: raise forms.ValidationError( 'The image at this URL is %s pixels wide - it must be at most %s pixels.' % ( dimensions[0], self.max_width)) if self.min_width is not None and dimensions[0] < self.min_width: raise forms.ValidationError( 'The image at this URL is %s pixels wide - it must be at least %s pixels.' % ( dimensions[0], self.min_width)) if self.max_height is not None and dimensions[1] > self.max_height: raise forms.ValidationError( 'The image at this URL is %s pixels high - it must be at most %s pixels.' % ( dimensions[1], self.max_height)) if self.min_height is not None and dimensions[1] < self.min_height: raise forms.ValidationError( 'The image at this URL is %s pixels high - it must be at least %s pixels.' % ( dimensions[1], self.min_height)) if self.image_formats is not None and format not in self.image_formats: raise forms.ValidationError( 'The image at this URL is in %s format - %s %s.' % ( format, len(self.image_formats) == 1 and 'the only accepted format is' or 'accepted formats are', get_text_list(self.image_formats))) except IOError: raise forms.ValidationError('Could not load an image from this URL.') return value
def validate_ml_unique(self): form_errors = [] if not hasattr(self.instance._meta, 'translation_model'): return for check in self.instance._meta.translation_model._meta.unique_together[:]: lookup_kwargs = {'language_code': GLL.language_code} for field_name in check: #local_name = "%s_%s" % (field_name, self.use_language) if self.cleaned_data.get(field_name) is not None: lookup_kwargs[field_name] = self.cleaned_data.get( field_name) if len(check ) == 2 and 'master' in check and 'language_code' in check: continue qs = self.instance._meta.translation_model.objects.filter( **lookup_kwargs) if self.instance.pk is not None: qs = qs.exclude(master=self.instance.pk) if qs.count(): model_name = capfirst(self.instance._meta.verbose_name) field_labels = [] for field_name in check: if field_name == "language_code": field_labels.append(_("language")) elif field_name == "master": continue else: field_labels.append( self.instance._meta.translation_model._meta. get_field_by_name(field_name)[0].verbose_name) field_labels = get_text_list(field_labels, _('and')) form_errors.append( _(u"%(model_name)s with this %(field_label)s already exists.") % \ {'model_name': unicode(model_name), 'field_label': unicode(field_labels)} ) if form_errors: # Raise the unique together errors since they are considered # form-wide. raise ValidationError(form_errors)
def hand_clean_Select(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get('pk', None): if not self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance representation, # suitable to be an item in a list. _('%(class_name)s %(instance)s') % { 'class_name': p._meta.verbose_name, 'instance': p }) params = { 'class_name': self._meta.model._meta.verbose_name, 'instance': self.instance, 'related_objects': get_text_list(objs, _('and')), } msg = _( "Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s") raise ValidationError(msg, code='deleting_protected', params=params) else: if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return
def hasNoProfanities(field_data, all_data): """ Checks that the given string has no profanities in it. This does a simple check for whether each profanity exists within the string, so 'f**k' will catch 'm**********r' as well. Raises a ValidationError such as: Watch your mouth! The words "f--k" and "s--t" are not allowed here. """ bad_words = [ 'asshat', 'asshead', 'asshole', 'c**t', 'f**k', 'gook', 'nigger', 'shit' ] # all in lower case field_data = field_data.lower() # normalize words_seen = [w for w in bad_words if field_data.find(w) > -1] if words_seen: from django.utils.text import get_text_list plural = len(words_seen) > 1 raise ValidationError, ngettext("Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and')
def log_change(self, request, obj, message): """ Log that an object has been successfully changed. """ if not message: return content_type = ContentType.objects.get_for_model(obj, for_concrete_model=False) if hasattr(obj, "new_pk"): # We are renaming an existing object. # a) Save the new record in the right database old_pk = obj.pk obj.pk = obj.new_pk obj.save(using=request.database) # b) All linked fields need updating. for related in obj._meta.get_fields(): if ( (related.one_to_many or related.one_to_one) and related.auto_created and not related.concrete ): related.related_model._base_manager.using(request.database).filter( **{related.field.name: old_pk} ).update(**{related.field.name: obj}) # c) Move the comments to the new key Comment.objects.using(request.database).filter( content_type__pk=content_type.pk, object_pk=old_pk ).update(object_pk=obj.pk) # d) Delete the old record obj.pk = old_pk obj.delete(using=request.database) obj.pk = obj.new_pk entry = Comment( user_id=request.user.pk, content_type_id=content_type.pk, object_pk=str(obj.pk), object_repr=str(obj)[:200], type="change", comment=message if isinstance(message, str) else "Changed %s." % get_text_list(message[0]["changed"]["fields"], "and"), ) entry.save(using=request.database) return entry
def change_view(self, request, object_id, form_url='', extra_context=None): message = get_object_or_404(Message, id=object_id) if not self.has_change_permission(request, message): raise PermissionDenied if request.method == 'POST': form = ChangeContestMessageForm(message.kind, request, request.POST, instance=message) if form.is_valid(): if form.changed_data: change_message = _("Changed %s.") % get_text_list( form.changed_data, _("and")) else: change_message = _("No fields changed.") if ('kind' in form.changed_data and form.cleaned_data['kind'] == 'PUBLIC'): msg = form.save(commit=False) msg.mail_sent = False msg.save() else: form.save() super(MessageAdmin, self).log_change(request, message, change_message) return redirect('contest_messages', contest_id=request.contest.id) else: form = ChangeContestMessageForm(message.kind, request, instance=message) return TemplateResponse( request, 'admin/questions/change_message.html', { 'form': form, 'message': message }, )
def get_change_message(self): """ If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ if self.change_message and self.change_message[0] == '[': try: json_data = ast.literal_eval(self.change_message) msg = json.dumps(json_data) change_message = json.loads(msg) except ValueError: return self.change_message messages = [] for sub_message in change_message: if 'added' in sub_message: if sub_message['added']: sub_message['added']['name'] = ugettext(sub_message['added']['name']) messages.append(ugettext('Added {name} "{object}".').format(**sub_message['added'])) else: messages.append(ugettext('Added.')) elif 'changed' in sub_message: sub_message['changed']['fields'] = get_text_list( sub_message['changed']['fields'], ugettext('and') ) if 'name' in sub_message['changed']: sub_message['changed']['name'] = ugettext(sub_message['changed']['name']) messages.append(ugettext('Changed {fields} for {name} "{object}".').format( **sub_message['changed'] )) else: messages.append(ugettext('Changed {fields}.').format(**sub_message['changed'])) elif 'deleted' in sub_message: sub_message['deleted']['name'] = ugettext(sub_message['deleted']['name']) messages.append(ugettext('Deleted {name} "{object}".').format(**sub_message['deleted'])) change_message = ' '.join(msg[0].upper() + msg[1:] for msg in messages) return change_message or ugettext('No fields changed.') else: return self.change_message
def clean_url(self): data = self.cleaned_data['url'] url = urlsplit(data) if not url.scheme and not url.netloc: m = re.match('^([^@]+@[^/]+):(.*)', url.path) if m: # user@host:... is equivalent to a ssh url url = urlsplit("ssh://%s/%s" % (m.group(1), m.group(2))) if not url.scheme: raise forms.ValidationError( "The remote URL must be an absolute URL.") if url.scheme == 'ssh': raise forms.ValidationError( "Gareth cannot fetch from ssh based remotes.") if url.scheme not in SUPPORTED_GIT_PROTOCOLS: raise forms.ValidationError( "'%s' is not an acceptable url scheme. Gareth only accepts %s urls." % (url.scheme, get_text_list(SUPPORTED_GIT_PROTOCOLS, 'and'))) return data