Here are the examples of the python api django.forms.ValidationError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
182 Examples
0
Example 151
Project: geonode Source File: forms.py
def clean(self):
requires_datastore = () if ogc_server_settings.DATASTORE else (
'.csv',
'.kml')
types = [t for t in files.types if t.code not in requires_datastore]
def supported_type(ext):
return any([t.matches(ext) for t in types])
cleaned = super(LayerUploadForm, self).clean()
base_name, base_ext = os.path.splitext(cleaned["base_file"].name)
if base_ext.lower() == '.zip':
# for now, no verification, but this could be unified
pass
elif not supported_type(base_ext.lower()[1:]):
supported = " , ".join([t.name for t in types])
raise forms.ValidationError(
"%s files are supported. You uploaded a %s file" %
(supported, base_ext))
if base_ext.lower() == ".shp":
dbf_file = cleaned["dbf_file"]
shx_file = cleaned["shx_file"]
if dbf_file is None or shx_file is None:
raise forms.ValidationError(
"When uploading Shapefiles, .SHX and .DBF files are also required.")
dbf_name, __ = os.path.splitext(dbf_file.name)
shx_name, __ = os.path.splitext(shx_file.name)
if dbf_name != base_name or shx_name != base_name:
raise forms.ValidationError(
"It looks like you're uploading "
"components from different Shapefiles. Please "
"double-check your file selections.")
if cleaned["prj_file"] is not None:
prj_file = cleaned["prj_file"].name
if os.path.splitext(prj_file)[0] != base_name:
raise forms.ValidationError(
"It looks like you're "
"uploading components from different Shapefiles. "
"Please double-check your file selections.")
return cleaned
0
Example 152
Project: sentry Source File: project_plugin_details.py
def put(self, request, project, plugin_id):
plugin = self._get_plugin(plugin_id)
config = [
serialize_field(project, plugin, c)
for c in plugin.get_config(
project=project,
)
]
cleaned = {}
errors = {}
for field in config:
key = field['name']
value = request.DATA.get(key)
if field.get('required') and not value:
errors[key] = ERR_FIELD_REQUIRED
try:
value = plugin.validate_config_field(
project=project,
name=key,
value=value,
actor=request.user,
)
except (forms.ValidationError, serializers.ValidationError, PluginError) as e:
errors[key] = e.message
if not errors.get(key):
cleaned[key] = value
if not errors:
try:
cleaned = plugin.validate_config(
project=project,
config=cleaned,
actor=request.user,
)
except PluginError as e:
errors['__all__'] = e.message
if errors:
return Response({
'errors': errors,
}, status=400)
for key, value in six.iteritems(cleaned):
if value is None:
plugin.unset_option(
project=project,
key=key,
)
else:
plugin.set_option(
project=project,
key=key,
value=value,
)
context = serialize(
plugin, request.user, PluginWithConfigSerializer(project))
return Response(context)
0
Example 153
Project: sentry Source File: issue.py
def view(self, request, group, **kwargs):
has_auth_configured = self.has_auth_configured()
if not (has_auth_configured and self.is_configured(project=group.project, request=request)):
if self.auth_provider:
required_auth_settings = settings.AUTH_PROVIDERS[self.auth_provider]
else:
required_auth_settings = None
return self.render(self.not_configured_template, {
'title': self.get_title(),
'project': group.project,
'has_auth_configured': has_auth_configured,
'required_auth_settings': required_auth_settings,
})
if self.needs_auth(project=group.project, request=request):
return self.render(self.needs_auth_template, {
'title': self.get_title(),
'project': group.project,
})
if GroupMeta.objects.get_value(group, '%s:tid' % self.get_conf_key(), None):
if self.can_unlink_issues and request.GET.get('unlink'):
return self.handle_unlink_issue(request, group, **kwargs)
return None
prefix = self.get_conf_key()
event = group.get_latest_event()
Event.objects.bind_nodes([event], 'data')
op = request.POST.get('op', 'create')
create_form = self.get_new_issue_form(request, group, event)
link_form = None
if self.can_link_existing_issues:
link_form = self.get_link_existing_issue_form(request, group, event)
if op == 'create':
if create_form.is_valid():
try:
issue_id = self.create_issue(
group=group,
form_data=create_form.cleaned_data,
request=request,
)
except forms.ValidationError as e:
create_form.errors['__all__'] = [u'Error creating issue: %s' % e]
if create_form.is_valid():
GroupMeta.objects.set_value(group, '%s:tid' % prefix, issue_id)
issue_information = {
'title': create_form.cleaned_data['title'],
'provider': self.get_title(),
'location': self.get_issue_url(group, issue_id),
'label': self.get_issue_label(group=group, issue_id=issue_id),
}
Activity.objects.create(
project=group.project,
group=group,
type=Activity.CREATE_ISSUE,
user=request.user,
data=issue_information,
)
issue_tracker_used.send(plugin=self, project=group.project, user=request.user, sender=IssueTrackingPlugin)
return self.redirect(group.get_absolute_url())
elif op == 'link':
if link_form.is_valid():
try:
self.link_issue(
group=group,
form_data=link_form.cleaned_data,
request=request,
)
except forms.ValidationError as e:
link_form.errors['__all__'] = [u'Error creating issue: %s' % e]
if link_form.is_valid():
issue_id = int(link_form.cleaned_data['issue_id'])
GroupMeta.objects.set_value(group, '%s:tid' % prefix, issue_id)
issue_information = {
'title': self.get_issue_title_by_id(request, group, issue_id),
'provider': self.get_title(),
'location': self.get_issue_url(group, issue_id),
'label': self.get_issue_label(group=group, issue_id=issue_id),
}
Activity.objects.create(
project=group.project,
group=group,
type=Activity.CREATE_ISSUE,
user=request.user,
data=issue_information,
)
return self.redirect(group.get_absolute_url())
context = {
'create_form': create_form,
# pass in 'form' for legacy compat
'form': create_form,
'title': self.get_new_issue_title(),
'read_only_fields': self.get_new_issue_read_only_fields(group=group),
'can_link_existing_issues': self.can_link_existing_issues,
'link_form': link_form,
'op': op
}
return self.render(self.create_issue_template, context)
0
Example 154
Project: database-as-a-service Source File: database.py
def clean(self):
cleaned_data = super(CloneDatabaseForm, self).clean()
if 'database_clone' in cleaned_data:
origindatabase = Database.objects.get(
pk=cleaned_data['origin_database_id'])
# for infra in DatabaseInfra.objects.filter(environment=origindatabase.environment,plan=origindatabase.plan):
# if infra.databases.filter(name=cleaned_data['database_clone']):
# self._errors["database_clone"] = self.error_class([_("this name already exists in the selected environment")])
if len(cleaned_data['database_clone']) > 40:
self._errors["database_clone"] = self.error_class(
[_("Database name too long")])
dbs = origindatabase.team.databases_in_use_for(
origindatabase.environment)
database_alocation_limit = origindatabase.team.database_alocation_limit
LOG.debug("dbs: %s | type: %s" % (dbs, type(dbs)))
if (database_alocation_limit != 0 and len(dbs) >= database_alocation_limit):
LOG.warning("The database alocation limit of %s has been exceeded for the team: %s => %s" % (
database_alocation_limit, origindatabase.team, list(dbs)))
raise forms.ValidationError([_("The database alocation limit of %s has been exceeded for the team: %s => %s") % (
database_alocation_limit, origindatabase.team, list(dbs))])
driver = DriverFactory.get_driver_class(
origindatabase.plan.engines[0].name)
if cleaned_data['database_clone'] in driver.RESERVED_DATABASES_NAME:
raise forms.ValidationError(
_("%s is a reserved database name" % cleaned_data['database_clone']))
environment = cleaned_data.get('environment', None)
database_name = cleaned_data.get('database_clone', None)
if Database.objects.filter(name=database_name,
environment=environment):
raise forms.ValidationError(
_("There is already a database called {} on {}".format(database_name,
environment)))
if database_name_evironment_constraint(database_name, environment.name):
raise forms.ValidationError(
_('%s already exists in production!') % database_name
)
if self._errors:
return cleaned_data
return cleaned_data
0
Example 155
Project: database-as-a-service Source File: database.py
def clean(self):
cleaned_data = super(DatabaseForm, self).clean()
# if there is an instance, that means that we are in a edit page and therefore
# it should return the default cleaned_data
if self.instance and self.instance.id:
self._validate_project(cleaned_data)
self._validate_description(cleaned_data)
self._validate_contacts(cleaned_data)
self._validate_team(cleaned_data)
return cleaned_data
if not self.is_valid():
raise forms.ValidationError(self.errors)
if 'plan' in cleaned_data:
plan = cleaned_data.get('plan', None)
if not plan:
self._errors["plan"] = self.error_class(
[_("Plan: This field is required.")])
self._validate_name(cleaned_data)
self._validate_project(cleaned_data)
self._validate_description(cleaned_data)
self._validate_contacts(cleaned_data)
self._validate_team(cleaned_data)
if 'environment' in cleaned_data:
environment = cleaned_data.get('environment', None)
database_name = cleaned_data.get('name', None)
if not environment or environment not in plan.environments.all():
raise forms.ValidationError(
_("Invalid plan for selected environment."))
if Database.objects.filter(name=database_name,
environment=environment):
self._errors["name"] = self.error_class(
[_("this name already exists in the selected environment")])
del cleaned_data["name"]
self._validate_team_resources(cleaned_data)
if database_name_evironment_constraint(database_name, environment.name):
raise forms.ValidationError(
_('%s already exists in production!') % database_name
)
if self._errors:
return cleaned_data
return cleaned_data
0
Example 156
def clean(self):
super(InstanceApplicationForm, self).clean()
if (
BRANDING.get('SHOW_ORGANIZATION_FORM', False) and
BRANDING.get('SHOW_ADMINISTRATIVE_FORM', False)
):
# if both forms are shown
organization = self.cleaned_data.get('organization', False)
if not (
organization or
self.cleaned_data.get("admin_contact_name", None) and
self.cleaned_data.get("admin_contact_email", None) and
self.cleaned_data.get("admin_contact_phone", None)
):
raise forms.ValidationError(
_(
"Choose either an organization or"
" fill in the contact information"
)
)
elif (
BRANDING.get('SHOW_ORGANIZATION_FORM', False) and not
BRANDING.get('SHOW_ADMINISTRATIVE_FORM', False)
):
# raise exception if there is no organization
# and the administrative form is not shown
organization = self.cleaned_data.get('organization', False)
if not organization:
raise forms.ValidationError(_("Choose an organization"))
elif (
BRANDING.get('SHOW_ADMINISTRATIVE_FORM', False) and not
BRANDING.get('SHOW_ORGANIZATION_FORM', False)
):
# if only administrative form is displayed
if not (self.cleaned_data.get("admin_contact_name", None) and
self.cleaned_data.get("admin_contact_email", None) and
self.cleaned_data.get("admin_contact_phone", None)
):
raise forms.ValidationError(
_("Please fill in the contact information")
)
return self.cleaned_data
0
Example 157
Project: hackerunion.org Source File: forms.py
def clean(self):
if not self._errors:
expr = Q()
from_val = self.cleaned_data.get('message_from')
chapter = self.cleaned_data.get('chapter')
need_user = False
# ignore emails that are internal
if self.ignore_internal and self.get_header(settings.INTERNAL_EMAIL_HEADER):
raise forms.ValidationError, "Cannot process internal emails"
# ignore emails that are missing a message id [and is not a reply]
if self.require_id and (self.require_id != MailForm.NEW_MAIL or not self.is_reply()) and not self.get_thread_id():
raise forms.ValidationError, "Message is missing an ID"
if self.leaders_only:
expr &= Q(userprofile__is_leader=True)
self.members_only = True
need_user = True
if self.members_only:
if not chapter:
raise forms.ValidationError, "A valid chapter is required"
expr &= Q(userprofile__chapter=chapter)
self.insiders_only = True
need_user = True
if self.insiders_only:
expr &= Q(email__iexact=from_val)
need_user = True
users = User.objects.filter(expr)
# validate from if restrictions are requested
if not users.exists():
if need_user:
raise forms.ValidationError, "Unauthorized posting."
self._user = users[0]
# disallow emails without any content
if not self.get_best_content(generate=False):
raise forms.ValidationError, "Email cannot be blank"
# TODO replace CID in html version with inline base64 encoded images
return self.cleaned_data
0
Example 158
def clean(self, value, gender=None):
super(CZBirthNumberField, self).__init__(value)
if value in EMPTY_VALUES:
return u''
match = re.match(birth_number, value)
if not match:
raise ValidationError(self.error_messages['invalid_format'])
birth, id = match.groupdict()['birth'], match.groupdict()['id']
# Three digits for verificatin number were used until 1. january 1954
if len(id) == 3:
return u'%s' % value
# Birth number is in format YYMMDD. Females have month value raised by 50.
# In case that all possible number are already used (for given date),
# the month field is raised by 20.
if gender is not None:
if gender == 'f':
female_const = 50
elif gender == 'm':
female_const = 0
else:
raise ValidationError(self.error_messages['invalid_gender'])
month = int(birth[2:4]) - female_const
if (not 1 <= month <= 12):
if (not 1 <= (month - 20) <= 12):
raise ValidationError(self.error_messages['invalid'])
day = int(birth[4:6])
if not (1 <= day <= 31):
raise ValidationError(self.error_messages['invalid'])
# Fourth digit has been added since 1. January 1954.
# It is modulo of dividing birth number and verification number by 11.
# If the modulo were 10, the last number was 0 (and therefore, the whole
# birth number wasn't divisable by 11. These number are no longer used (since 1985)
# and the condition 'modulo == 10' can be removed in 2085.
modulo = int(birth + id[:3]) % 11
if (modulo == int(id[-1])) or (modulo == 10 and id[-1] == '0'):
return u'%s' % value
else:
raise ValidationError(self.error_messages['invalid'])
0
Example 159
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
0
Example 160
Project: mollyproject Source File: forms.py
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data['method'] in ('html5', 'html5request', 'gears','manual', 'geocoded', 'other', 'favourite'):
if cleaned_data['method'] == 'geocoded':
if not cleaned_data['name'].strip():
raise forms.ValidationError(_("You must enter a location"))
results = geocode(cleaned_data['name'])
if len(results) > 0:
cleaned_data.update(results[0])
cleaned_data['longitude'], cleaned_data['latitude'] = cleaned_data['location']
# Ignore alternatives for postcodes
if not re.match(POSTCODE_RE, cleaned_data['name'].upper()):
cleaned_data['alternatives'] = results[1:]
else:
cleaned_data['alternatives'] = []
else:
raise forms.ValidationError(_("Unable to find a location that matches '%s'.") % cleaned_data['name'])
for key in ('latitude', 'longitude', 'accuracy'):
if cleaned_data.get(key) is None:
self._errors[key] = ErrorList(['method requires that ' + key + ' must be specified'])
if not self._errors:
cleaned_data['location'] = cleaned_data['longitude'], cleaned_data['latitude']
if not cleaned_data.get('name'):
try:
cleaned_data['name'] = reverse_geocode(
self.cleaned_data['longitude'],
self.cleaned_data['latitude'])[0]['name']
except:
cleaned_data['name'] = u"↝ %f, %f" % (self.cleaned_data['longitude'], self.cleaned_data['latitude'])
elif cleaned_data['method'] in ('denied', 'error'):
for key in ('latitude', 'longitude', 'accuracy'):
if cleaned_data.get(key) is None:
self._errors[key] = ErrorList(['method requires that ' + key + ' must be specified'])
else:
self._errors['method'] = ErrorList(['method is required'])
return cleaned_data
0
Example 161
Project: addons-server Source File: forms.py
def clean_tags(request, tags):
target = [slugify(t, spaces=True, lower=True) for t in tags.split(',')]
target = set(filter(None, target))
min_len = amo.MIN_TAG_LENGTH
max_len = Tag._meta.get_field('tag_text').max_length
max_tags = amo.MAX_TAGS
total = len(target)
denied = (Tag.objects.values_list('tag_text', flat=True)
.filter(tag_text__in=target, denied=True))
if denied:
# L10n: {0} is a single tag or a comma-separated list of tags.
msg = ngettext('Invalid tag: {0}', 'Invalid tags: {0}',
len(denied)).format(', '.join(denied))
raise forms.ValidationError(msg)
restricted = (Tag.objects.values_list('tag_text', flat=True)
.filter(tag_text__in=target, restricted=True))
if not acl.action_allowed(request, 'Addons', 'Edit'):
if restricted:
# L10n: {0} is a single tag or a comma-separated list of tags.
msg = ngettext('"{0}" is a reserved tag and cannot be used.',
'"{0}" are reserved tags and cannot be used.',
len(restricted)).format('", "'.join(restricted))
raise forms.ValidationError(msg)
else:
# Admin's restricted tags don't count towards the limit.
total = len(target - set(restricted))
if total > max_tags:
num = total - max_tags
msg = ngettext('You have {0} too many tags.',
'You have {0} too many tags.', num).format(num)
raise forms.ValidationError(msg)
if any(t for t in target if len(t) > max_len):
raise forms.ValidationError(
_('All tags must be %s characters or less after invalid characters'
' are removed.' % max_len))
if any(t for t in target if len(t) < min_len):
msg = ngettext("All tags must be at least {0} character.",
"All tags must be at least {0} characters.",
min_len).format(min_len)
raise forms.ValidationError(msg)
return target
0
Example 162
def clean(self):
cleaned_data = super(SavedSearchForm, self).clean()
# check that no freetext word is used in both places
title_include = set(
x.lower() for x in cleaned_data['title_include'].split()
if x.strip()
)
title_exclude = set(
x.lower() for x in cleaned_data['title_exclude'].split()
if x.strip()
)
if title_include & title_exclude:
raise forms.ValidationError(
'Mutual overlap in title words: {}'.format(
', '.join(title_include & title_exclude)
)
)
# check tags
tags_include = set(
x.name for x in cleaned_data.get('tags_include', [])
)
tags_exclude = set(
x.name for x in cleaned_data.get('tags_exclude', [])
)
if tags_include & tags_exclude:
raise forms.ValidationError(
'Mutual overlap in tags: {}'.format(
', '.join(tags_include & tags_exclude)
)
)
# check channels
channels_include = set(
x.name for x in cleaned_data.get('channels_include', [])
)
channels_exclude = set(
x.name for x in cleaned_data.get('channels_exclude', [])
)
if channels_include & channels_exclude:
raise forms.ValidationError(
'Mutual overlap in channels: {}'.format(
', '.join(channels_include & channels_exclude)
)
)
any_data = False
for key, value in cleaned_data.items():
if key == 'name':
# doesn't count
continue
if value:
any_data = True
break
if not any_data:
raise forms.ValidationError('Nothing entered')
return cleaned_data
0
Example 163
Project: kuma Source File: forms.py
def clean_current_rev(self):
"""
If a current revision is supplied in the form, compare it against
what the docuement claims is the current revision. If there's a
difference, then an edit has occurred since the form was constructed
and we treat it as a mid-air collision.
"""
current_rev = self.cleaned_data.get('current_rev', None)
if not current_rev:
# If there's no current_rev, just bail.
return current_rev
try:
doc_current_rev = self.instance.docuement.current_revision.id
if unicode(current_rev) != unicode(doc_current_rev):
if (self.section_id and self.instance and
self.instance.docuement):
# This is a section edit. So, even though the revision has
# changed, it still might not be a collision if the section
# in particular hasn't changed.
orig_ct = (Revision.objects
.get(pk=current_rev)
.get_section_content(self.section_id))
curr_ct = (self.instance
.docuement.current_revision
.get_section_content(self.section_id))
if orig_ct != curr_ct:
# Oops. Looks like the section did actually get
# changed, so yeah this is a collision.
url = reverse(
'wiki.docuement_revisions',
kwargs={'docuement_path': self.instance.docuement.slug}
)
raise forms.ValidationError(MIDAIR_COLLISION % {'url': url})
return current_rev
else:
# No section edit, so this is a flat-out collision.
url = reverse(
'wiki.docuement_revisions',
kwargs={'docuement_path': self.instance.docuement.slug}
)
raise forms.ValidationError(MIDAIR_COLLISION % {'url': url})
except Docuement.DoesNotExist:
# If there's no docuement yet, just bail.
return current_rev
0
Example 164
Project: remo Source File: tasks.py
@task
def send_remo_mail(subject, recipients_list, sender=None,
message=None, email_template=None, data=None,
headers=None):
"""Send email from /sender/ to /recipients_list/ with /subject/ and
/message/ as body.
"""
# Make sure that there is either a message or a template
if not data:
data = {}
# If there is no body for the email and not a template
# to render, then do nothing.
if not message and not email_template:
return
# If there is both an email body, submitted by the user,
# and a template to render as email body, then add
# user's input to extra_content key
elif message and email_template:
data.update({'extra_content': message})
# Make sure that there is a recipient
if not recipients_list:
return
if not headers:
headers = {}
data.update({'SITE_URL': settings.SITE_URL,
'FROM_EMAIL': settings.FROM_EMAIL})
# Make sure subject is one line.
subject = subject.replace('\n', ' ')
for recipient in recipients_list:
to = ''
if (isinstance(recipient, long) and
User.objects.filter(pk=recipient).exists()):
user = User.objects.get(pk=recipient)
to = '%s <%s>' % (user.get_full_name(), user.email)
ctx_data = {'user': user,
'userprofile': user.userprofile}
data.update(ctx_data)
else:
try:
validate_email(recipient)
to = recipient
except forms.ValidationError:
return
if email_template:
message = render_to_string(email_template, data)
if not sender:
email = EmailMessage(subject=subject, body=message,
from_email=settings.FROM_EMAIL,
to=[to], headers=headers)
else:
email = EmailMessage(subject=subject, body=message,
from_email=sender, to=[to], cc=[sender],
headers=headers)
email.send()
0
Example 165
Project: zamboni Source File: forms.py
def clean_upload(self):
upload = self.cleaned_data['upload']
errors = []
if upload.size > self.max_size:
errors.append({
'type': 'error',
'message': _('Packaged app too large for submission. Packages '
'must be smaller than %s.' % filesizeformat(
self.max_size)),
'tier': 1,
})
# Immediately raise an error, do not process the rest of the view,
# which would read the file.
raise self.persist_errors(errors, upload)
manifest = None
try:
# Be careful to keep this as in-memory zip reading.
safe_zip = SafeUnzip(upload, 'r')
safe_zip.is_valid() # Will throw ValidationError if necessary.
manifest = safe_zip.extract_path('manifest.webapp')
except forms.ValidationError as e:
errors.append({
'type': 'error',
'message': ''.join(e.messages),
'tier': 1,
})
except Exception as e:
errors.append({
'type': 'error',
'message': _('Error extracting manifest from zip file.'),
'tier': 1,
})
finally:
safe_zip.close()
origin = None
if manifest:
try:
origin = WebAppParser.decode_manifest(manifest).get('origin')
except forms.ValidationError as e:
errors.append({
'type': 'error',
'message': ''.join(e.messages),
'tier': 1,
})
if origin:
try:
verify_app_domain(origin, packaged=True, exclude=self.addon)
except forms.ValidationError, e:
errors.append({
'type': 'error',
'message': ''.join(e.messages),
'tier': 1,
})
if errors:
raise self.persist_errors(errors, upload)
# Everything passed validation.
self.file_upload = FileUpload.from_post(
upload, upload.name, upload.size, user=self.user)
0
Example 166
Project: zamboni Source File: tasks.py
@task
@use_master
def fetch_icon(pk, file_pk=None, **kw):
"""
Downloads a webapp icon from the location specified in the manifest.
Returns False if icon was not able to be retrieved
If `file_pk` is not provided it will use the file from the app's
`current_version`.
"""
webapp = Webapp.objects.get(pk=pk)
log.info(u'[1@None] Fetching icon for webapp %s.' % webapp.name)
if file_pk:
file_obj = File.objects.get(pk=file_pk)
else:
file_obj = (webapp.current_version and
webapp.current_version.all_files[0])
manifest = webapp.get_manifest_json(file_obj)
if not manifest or 'icons' not in manifest:
# Set the icon type to empty.
webapp.update(icon_type='')
return
try:
biggest = max(int(size) for size in manifest['icons'])
except ValueError:
log.error('No icon to fetch for webapp "%s"' % webapp.name)
return False
icon_url = manifest['icons'][str(biggest)]
if icon_url.startswith('data:image'):
image_string = icon_url.split('base64,')[1]
content = base64.decodestring(image_string)
else:
if webapp.is_packaged:
# Get icons from package.
if icon_url.startswith('/'):
icon_url = icon_url[1:]
try:
zf = SafeUnzip(private_storage.open(file_obj.file_path))
zf.is_valid()
content = zf.extract_path(icon_url)
except (KeyError, forms.ValidationError): # Not found in archive.
log.error(u'[Webapp:%s] Icon %s not found in archive'
% (webapp, icon_url))
return False
else:
if not urlparse.urlparse(icon_url).scheme:
icon_url = webapp.origin + icon_url
try:
response = _fetch_content(icon_url)
except Exception, e:
log.error(u'[Webapp:%s] Failed to fetch icon for webapp: %s'
% (webapp, e))
# Set the icon type to empty.
webapp.update(icon_type='')
return False
try:
content = get_content_and_check_size(
response, settings.MAX_ICON_UPLOAD_SIZE)
except ResponseTooLargeException:
log.warning(u'[Webapp:%s] Icon exceeds maximum size.' % webapp)
return False
log.info('Icon fetching completed for app "%s"; saving icon' % webapp.name)
save_icon(webapp, content)
0
Example 167
Project: wikicoding Source File: forms.py
def check_spam(self):
"""Check that user or IP address does not perform content edits that
are not allowed.
current_revision can be any object inheriting from models.BaseRevisionMixin
"""
request = self.request
user = None
ip_address = None
if request.user.is_authenticated():
user = request.user
else:
ip_address = request.META.get('REMOTE_ADDR', None)
if not (user or ip_address):
raise forms.ValidationError(ugettext('Spam protection failed to find both a logged in user and an IP address.'))
def check_interval(from_time, max_count, interval_name):
from_time = timezone.now() - timedelta(minutes=settings.REVISIONS_MINUTES_LOOKBACK)
revisions = self.revision_model.objects.filter(
created__gte=from_time,
)
if user:
revisions = revisions.filter(user=user)
if ip_address:
revisions = revisions.filter(ip_address=ip_address)
revisions = revisions.count()
if revisions >= max_count:
raise forms.ValidationError(ugettext('Spam protection: You are only allowed to create or edit %(revisions)d article(s) per %(interval_name)s.') %
{'revisions': max_count,
'interval_name': interval_name,})
if not settings.LOG_IPS_ANONYMOUS:
return
if request.user.has_perm('wiki.moderator'):
return
from_time = timezone.now() - timedelta(minutes=settings.REVISIONS_MINUTES_LOOKBACK)
if request.user.is_authenticated():
per_minute = settings.REVISIONS_PER_MINUTES
else:
per_minute = settings.REVISIONS_PER_MINUTES_ANONYMOUS
check_interval(from_time, per_minute,
_('minute') if settings.REVISIONS_MINUTES_LOOKBACK==1 else (_('%d minutes') % settings.REVISIONS_MINUTES_LOOKBACK),)
from_time = timezone.now() - timedelta(minutes=60)
if request.user.is_authenticated():
per_hour = settings.REVISIONS_PER_MINUTES
else:
per_hour = settings.REVISIONS_PER_MINUTES_ANONYMOUS
check_interval(from_time, per_hour, _('hour'))
0
Example 168
def clean(self):
if any(self.errors):
return
recording = self.instance
# we're using '_forms' to avoid clashing with forms import, e.g.
# for ValidationError
_forms = sorted(
[f for f in self.forms if 'timestamp' in f.cleaned_data],
key=lambda f: f.cleaned_data['timestamp']
)
first_timestamp = _forms[0].cleaned_data['timestamp']
last_timestamp = _forms[-1].cleaned_data['timestamp']
# TODO: check that first timestamp isn't before start of speech?
if first_timestamp < recording.start_datetime:
raise forms.ValidationError(
_("Start time is before recording start time!"))
# TODO: check that delta from first to last timestamp isn't longer
# than length of audio
# This is slightly complicated because we don't seem to cache this
# metadata anywhere? Might make sense to add to Recording?
delta = (last_timestamp - first_timestamp).seconds
if delta >= recording.audio_duration:
raise forms.ValidationError(
_('Difference between timestamps is too long for the uploaded audio'))
previous_timestamp = None
for form in _forms:
timestamp = form.cleaned_data['timestamp']
if previous_timestamp:
if timestamp <= previous_timestamp:
raise forms.ValidationError(
_('Timestamps must be distinct'))
previous_timestamp = timestamp
0
Example 169
Project: yournextrepresentative Source File: forms.py
def check_party_and_constituency_are_selected(self, cleaned_data):
'''This is called by the clean method of subclasses'''
for election_data in self.elections_with_fields:
election = election_data.slug
election_name = election_data.name
standing_status = cleaned_data.get(
'standing_' + election, 'standing'
)
if standing_status != 'standing':
continue
# Make sure that there is a party selected; we need to do this
# from the clean method rather than single field validation
# since the party field that should be checked depends on the
# selected constituency.
post_id = cleaned_data['constituency_' + election]
if not post_id:
message = _("If you mark the candidate as standing in the "
"{election}, you must select a post")
raise forms.ValidationError(message.format(
election=election_name
))
# Check that that post actually exists:
if not Post.objects.filter(extra__slug=post_id).exists():
message = _("An unknown post ID '{post_id}' was specified")
raise forms.ValidationError(
message.format(post_id=post_id)
)
try:
party_set = PartySet.objects.get(postextra__slug=post_id)
except PartySet.DoesNotExist:
message = _("Could not find parties for the post with ID "
"'{post_id}' in the {election}")
raise forms.ValidationError(
message.format(post_id=post_id, election=election_name)
)
party_field = 'party_' + party_set.slug + '_' + election
try:
party_id = int(cleaned_data[party_field], 10)
except ValueError:
party_id = None
if not Organization.objects.filter(
classification='Party', id=party_id).exists():
message = _("You must specify a party for the {election}")
raise forms.ValidationError(message.format(election=election_name))
return cleaned_data
0
Example 170
Project: Nitrate Source File: forms.py
def process_case(self, case):
# Check author
element = 'author'
if case.get(element, {}).get('value'):
try:
author = User.objects.get(email=case[element]['value'])
author_id = author.id
except User.DoesNotExist:
raise forms.ValidationError(
self.error_messages['element_could_not_found'] % (
element, case[element]['value']))
else:
raise forms.ValidationError(
self.error_messages['element_is_required'] % element)
# Check default tester
element = 'defaulttester'
if case.get(element, {}).get('value'):
try:
default_tester = User.objects.get(email=case[element]['value'])
default_tester_id = default_tester.id
except User.DoesNotExist:
raise forms.ValidationError(
self.error_messages['element_could_not_found'] % (
element, case[element]['value']))
else:
default_tester_id = None
# Check priority
element = 'priority'
if case.get(element, {}).get('value'):
try:
priority = Priority.objects.get(value=case[element]['value'])
priority_id = priority.id
except Priority.DoesNotExist:
raise forms.ValidationError(
self.error_messages['element_could_not_found'] % (
element, case[element]['value']))
else:
raise forms.ValidationError(
self.error_messages['element_is_required'] % element)
# Check automated status
element = 'automated'
if case.get(element, {}).get('value'):
is_automated = case[element][
'value'] == 'Automatic' and True or False
else:
is_automated = False
# Check status
element = 'status'
if case.get(element, {}).get('value'):
try:
case_status = TestCaseStatus.objects.get(
name=case[element]['value'])
case_status_id = case_status.id
except TestCaseStatus.DoesNotExist:
raise forms.ValidationError(
self.error_messages['element_could_not_found'] % (
element, case[element]['value']))
else:
raise forms.ValidationError(
self.error_messages['element_is_required'] % element)
# Check category
# *** Ugly code here ***
# There is a bug in the XML file, the category is related to product.
# But unfortunate it did not defined product in the XML file.
# So we have to define the category_name at the moment then get the
# product from the plan.
# If we did not found the category of the product we will create one.
element = 'categoryname'
if case.get(element, {}).get('value'):
category_name = case[element]['value']
else:
raise forms.ValidationError(
self.error_messages['element_is_required'] % element)
# Check or create the tag
element = 'tag'
if case.get(element, {}):
tags = []
if isinstance(case[element], dict):
tag, create = TestTag.objects.get_or_create(
name=case[element]['value'])
tags.append(tag)
if isinstance(case[element], list):
for tag_name in case[element]:
tag, create = TestTag.objects.get_or_create(
name=tag_name['value'])
tags.append(tag)
else:
tags = None
new_case = {
'summary': case.get('summary', {}).get('value', ''),
'author_id': author_id,
'author': author,
'default_tester_id': default_tester_id,
'priority_id': priority_id,
'is_automated': is_automated,
'case_status_id': case_status_id,
'category_name': category_name,
'notes': case.get('notes', {}).get('value', ''),
'action': case.get('action', {}).get('value', ''),
'effect': case.get('expectedresults', {}).get('value', ''),
'setup': case.get('setup', {}).get('value', ''),
'breakdown': case.get('breakdown', {}).get('value', ''),
'tags': tags,
}
return new_case
0
Example 171
Project: Nitrate Source File: forms.py
def clean(self, data, initial=None):
"""
Check the file content type is XML or not
"""
f = super(CasePlanXMLField, self).clean(data, initial)
if f is None:
return None
elif not data and initial:
return initial
if not data.content_type == 'text/xml':
raise forms.ValidationError(self.error_messages['invalid_file'])
# We need to get a file object for PIL. We might have a path or we
# might have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
xml_file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
xml_file = data.read()
else:
xml_file = data['content']
# Replace line breaks for XML interpret
xml_file = xml_file.replace('\n', '')
xml_file = xml_file.replace('&testopia_', '&')
# Insert clean code here
try:
xml = XML2Dict()
self.xml_data = xml.fromstring(xml_file)
if not self.xml_data.get('testopia'):
raise forms.ValidationError(
self.error_messages['root_element_is_needed'])
if not self.xml_data['testopia'].get(
'version') != settings.TESTOPIA_XML_VERSION:
raise forms.ValidationError(
self.error_messages['xml_version_is_incorrect'])
if not self.xml_data['testopia'].get('testcase'):
raise forms.ValidationError(
self.error_messages['test_case_element_is_needed'])
new_case_from_xml = []
if isinstance(self.xml_data['testopia']['testcase'], list):
for case in self.xml_data['testopia']['testcase']:
new_case_from_xml.append(self.process_case(case))
elif isinstance(self.xml_data['testopia']['testcase'], dict):
new_case_from_xml.append(
self.process_case(self.xml_data['testopia']['testcase']))
else:
raise forms.ValidationError(
self.error_messages['test_case_element_is_needed'])
except Exception, error:
raise forms.ValidationError('%s: %s' % (
self.error_messages['interpret_error'],
error
))
except SyntaxError, error:
raise forms.ValidationError('%s: %s' % (
self.error_messages['interpret_error'],
error
))
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return new_case_from_xml
0
Example 172
@property
def qs(self):
if not hasattr(self, '_qs'):
q_base = Q()
qs = self.queryset.all()
for name, filter_ in self.filters.iteritems():
try:
if self.is_bound:
data = self.form[name].data
else:
data = self.form.initial.get(name, self.form[name].field.initial)
val = self.form.fields[name].clean(data)
if val or val is False or val is 0: # Stop passing it when there's val!
# TODO: what if I want to check that the field is null?
# TODO: - check that a date field has NO date
# TODO: - check that a relationship doesn't exist (company w/out employees)
# TODO: - check filter all users without bio field filled out...
result = filter_.filter(val)
if result:
q_base &= result # Stop passing it the qs!!
except forms.ValidationError:
pass
self._qs = qs.filter(q_base).distinct()
if self._meta.order_by:
try:
value = self.form.fields[ORDER_BY_FIELD].clean(self.form[ORDER_BY_FIELD].data)
if value:
self._qs = self._qs.order_by(value)
except forms.ValidationError:
pass
return self._qs
0
Example 173
def clean(self):
"""
Adds validation to check that no two links have the same anchor or URL
and that all links have both an anchor and URL.
"""
if any(self.errors):
return
anchors = []
urls = []
duplicates = False
for form in self.forms:
if form.cleaned_data:
anchor = form.cleaned_data['anchor']
url = form.cleaned_data['url']
# Check that no two links have the same anchor or URL
if anchor and url:
if anchor in anchors:
duplicates = True
anchors.append(anchor)
if url in urls:
duplicates = True
urls.append(url)
if duplicates:
raise forms.ValidationError(
_('Links must have unique anchors and URLs.'),
code='duplicate_links'
)
# Check that all links have both an anchor and URL
if url and not anchor:
raise forms.ValidationError(
_('All links must have an anchor.'),
code='missing_anchor'
)
elif anchor and not url:
raise forms.ValidationError(
_('All links must have a URL.'),
code='missing_URL'
)
0
Example 174
Project: onepercentclub-site Source File: forms.py
def clean_csv_file(self):
csv_file = self.cleaned_data['csv_file']
# Universal newlines
# Ugly hack - but works for now
csv_string = '\n'.join(csv_file.read().splitlines())
csv_file = StringIO.StringIO(csv_string)
# TODO: Use chardet
# Ref: https://github.com/dokterbob/django-newsletter/blob/master/newsletter/admin_forms.py#L86
sniffer = csv.Sniffer()
# Python's CSV code eats only UTF-8
csv_file = codecs.EncodedFile(csv_file, self.charset)
try:
if self.dialect:
# Override dialect, don't autodetect
dialect = self.dialect
else:
# Sniff dialect
dialect = sniffer.sniff(
csv_string,
delimiters=self.delimiters
)
# Sniff for a header
has_header = sniffer.has_header(
csv_string
)
except csv.Error, e:
raise forms.ValidationError(
_('Could not read CSV file: %s' % e.message)
)
# Read CSV file
reader = csv.reader(csv_file,
dialect=dialect, encoding=self.charset
)
if has_header:
# Update mapping using header
header = reader.next()
for (key, value) in self.field_mapping.items():
if isinstance(key, basestring):
# Key is string, derive number using header
try:
header_index = header.index(key)
except ValueError:
error_message = 'Field %s not found in CSV header.'
# Try again with outer spaces removed, and everything
# lowercased - but only when no duplicates result
header = [f.strip().lower() for f in header]
new_key = key.lower()
if not has_duplicate_items(header):
try:
header_index = header.index(new_key)
except ValueError:
raise Exception(error_message % new_key)
else:
raise Exception(error_message % key)
self.field_mapping[header_index] = value
# Field found, remove from field mapping
del self.field_mapping[key]
# Split the iterator such that we can validate
(reader, validate_fieldcount, validate_csv) = itertools.tee(reader, 3)
# Validate field count
validation_row = validate_fieldcount.next()
if len(self.field_mapping) > len(validation_row):
raise forms.ValidationError(
'Less fields in CSV (%d) than specified in field mapping (%d).' % (
len(validation_row), len(self.field_mapping)
)
)
# Validate CSV
if self.validate_csv:
self.validate_csv(validate_csv)
self.cleaned_data['csv_reader'] = reader
return csv_file
0
Example 175
def clean(self, value, gender=None):
super(CZBirthNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
match = re.match(birth_number, value)
if not match:
raise ValidationError(self.error_messages['invalid_format'])
birth, id = match.groupdict()['birth'], match.groupdict()['id']
# Three digits for verification number were used until 1. january 1954
if len(id) == 3:
return '%s' % value
# Birth number is in format YYMMDD. Females have month value raised by 50.
# In case that all possible number are already used (for given date),
# the month field is raised by 20.
month = int(birth[2:4])
if (not 1 <= month <= 12) and (not 21 <= month <= 32) and \
(not 51 <= month <= 62) and (not 71 <= month <= 82):
raise ValidationError(self.error_messages['invalid'])
day = int(birth[4:6])
if not (1 <= day <= 31):
raise ValidationError(self.error_messages['invalid'])
# Fourth digit has been added since 1. January 1954.
# It is modulo of dividing birth number and verification number by 11.
# If the modulo were 10, the last number was 0 (and therefore, the whole
# birth number wasn't divisable by 11. These number are no longer used (since 1985)
# and the condition 'modulo == 10' can be removed in 2085.
modulo = int(birth + id[:3]) % 11
if (modulo == int(id[-1])) or (modulo == 10 and id[-1] == '0'):
return '%s' % value
else:
raise ValidationError(self.error_messages['invalid'])
0
Example 176
Project: openode Source File: __init__.py
def process_emailed_question(
from_address, subject, body_text, stored_files,
tags=None, group_id=None
):
"""posts question received by email or bounces the message"""
#a bunch of imports here, to avoid potential circular import issues
from openode.forms import AskByEmailForm
from openode.models import ReplyAddress, User
from openode.mail import messages
reply_to = None
try:
#todo: delete uploaded files when posting by email fails!!!
data = {
'sender': from_address,
'subject': subject,
'body_text': body_text
}
form = AskByEmailForm(data)
if form.is_valid():
email_address = form.cleaned_data['email']
user = User.objects.get(email__iexact=email_address)
if user.can_post_by_email() is False:
raise PermissionDenied(messages.insufficient_reputation(user))
body_text = form.cleaned_data['body_text']
stripped_body_text = user.strip_email_signature(body_text)
signature_not_detected = (
stripped_body_text == body_text and user.email_signature
)
#ask for signature response if user's email has not been
#validated yet or if email signature could not be found
if user.email_isvalid is False or signature_not_detected:
reply_to = ReplyAddress.objects.create_new(
user=user,
reply_action='validate_email'
).as_email_address()
message = messages.ask_for_signature(user, footer_code=reply_to)
raise PermissionDenied(message)
tagnames = form.cleaned_data['tagnames']
title = form.cleaned_data['title']
#defect - here we might get "too many tags" issue
if tags:
tagnames += ' ' + ' '.join(tags)
user.post_thread(
title=title,
tags=tagnames.strip(),
body_text=stripped_body_text,
by_email=True,
email_address=from_address,
group_id=group_id
)
else:
raise ValidationError()
except User.DoesNotExist:
bounce_email(email_address, subject, reason='unknown_user')
except User.MultipleObjectsReturned:
bounce_email(email_address, subject, reason='problem_posting')
except PermissionDenied, error:
bounce_email(
email_address,
subject,
reason='permission_denied',
body_text=unicode(error),
reply_to=reply_to
)
except ValidationError:
if from_address:
bounce_email(
from_address,
subject,
reason='problem_posting',
)
0
Example 177
Project: openode Source File: forms.py
def clean(self, username):
""" validate username """
if self.skip_clean == True:
logging.debug('username accepted with no validation')
return username
if self.user_instance is None:
pass
elif isinstance(self.user_instance, User):
if username == self.user_instance.username:
logging.debug('username valid')
return username
else:
raise TypeError('user instance must be of type User')
try:
username = super(UserNameField, self).clean(username)
except forms.ValidationError:
raise forms.ValidationError(self.error_messages['required'])
username_re_string = const.USERNAME_REGEX_STRING
#attention: here we check @ symbol in two places: input and the regex
if openode_settings.ALLOW_EMAIL_ADDRESS_IN_USERNAME is False:
if '@' in username:
raise forms.ValidationError(self.error_messages['noemail'])
username_re_string = username_re_string.replace('@', '')
username_regex = re.compile(username_re_string, re.UNICODE)
if self.required and not username_regex.search(username):
raise forms.ValidationError(self.error_messages['invalid'])
if username in self.RESERVED_NAMES:
raise forms.ValidationError(self.error_messages['forbidden'])
if slugify(username) == '':
raise forms.ValidationError(self.error_messages['meaningless'])
try:
user = self.db_model.objects.get(
**{'%s' % self.db_field: username}
)
if user:
if self.must_exist:
logging.debug('user exists and name accepted b/c here we validate existing user')
return username
else:
raise forms.ValidationError(self.error_messages['taken'])
except self.db_model.DoesNotExist:
if self.must_exist:
logging.debug('user must exist, so raising the error')
raise forms.ValidationError(self.error_messages['missing'])
else:
logging.debug('user name valid!')
return username
except self.db_model.MultipleObjectsReturned:
logging.debug('error - user with this name already exists')
raise forms.ValidationError(self.error_messages['multiple-taken'])
0
Example 178
Project: horizon Source File: forms.py
def __init__(self, request, *args, **kwargs):
super(CreateImageForm, self).__init__(request, *args, **kwargs)
if (api.glance.get_image_upload_mode() == 'off' or
not policy.check((("image", "upload_image"),), request)):
self._hide_file_source_type()
if not policy.check((("image", "set_image_location"),), request):
self._hide_url_source_type()
# GlanceV2 feature removals
if api.glance.VERSIONS.active >= 2:
# NOTE: GlanceV2 doesn't support copy-from feature, sorry!
self._hide_is_copying()
if not getattr(settings, 'IMAGES_ALLOW_LOCATION', False):
self._hide_url_source_type()
if (api.glance.get_image_upload_mode() == 'off' or not
policy.check((("image", "upload_image"),), request)):
# Neither setting a location nor uploading image data is
# allowed, so throw an error.
msg = _('The current Horizon settings indicate no valid '
'image creation methods are available. Providing '
'an image location and/or uploading from the '
'local file system must be allowed to support '
'image creation.')
messages.error(request, msg)
raise ValidationError(msg)
if not policy.check((("image", "publicize_image"),), request):
self._hide_is_public()
self.fields['disk_format'].choices = IMAGE_FORMAT_CHOICES
try:
kernel_images = api.glance.image_list_detailed(
request, filters={'disk_format': 'aki'})[0]
except Exception:
kernel_images = []
msg = _('Unable to retrieve image list.')
messages.error(request, msg)
if kernel_images:
choices = [('', _("Choose an image"))]
for image in kernel_images:
choices.append((image.id, image))
self.fields['kernel'].choices = choices
else:
del self.fields['kernel']
try:
ramdisk_images = api.glance.image_list_detailed(
request, filters={'disk_format': 'ari'})[0]
except Exception:
ramdisk_images = []
msg = _('Unable to retrieve image list.')
messages.error(request, msg)
if ramdisk_images:
choices = [('', _("Choose an image"))]
for image in ramdisk_images:
choices.append((image.id, image))
self.fields['ramdisk'].choices = choices
else:
del self.fields['ramdisk']
0
Example 179
Project: horizon Source File: forms.py
def handle(self, request, data):
try:
usages = quotas.tenant_limit_usages(self.request)
availableGB = usages['maxTotalVolumeGigabytes'] - \
usages['gigabytesUsed']
availableVol = usages['maxTotalVolumes'] - usages['volumesUsed']
snapshot_id = None
image_id = None
volume_id = None
source_type = data.get('volume_source_type', None)
az = data.get('availability_zone', None) or None
if (data.get("snapshot_source", None) and
source_type in ['', None, 'snapshot_source']):
# Create from Snapshot
snapshot = self.get_snapshot(request,
data["snapshot_source"])
snapshot_id = snapshot.id
if (data['size'] < snapshot.size):
error_message = (_('The volume size cannot be less than '
'the snapshot size (%sGiB)')
% snapshot.size)
raise ValidationError(error_message)
az = None
elif (data.get("image_source", None) and
source_type in ['', None, 'image_source']):
# Create from Snapshot
image = self.get_image(request,
data["image_source"])
image_id = image.id
image_size = functions.bytes_to_gigabytes(image.size)
if (data['size'] < image_size):
error_message = (_('The volume size cannot be less than '
'the image size (%s)')
% filesizeformat(image.size))
raise ValidationError(error_message)
properties = getattr(image, 'properties', {})
min_disk_size = (getattr(image, 'min_disk', 0) or
properties.get('min_disk', 0))
if (min_disk_size > 0 and data['size'] < min_disk_size):
error_message = (_('The volume size cannot be less than '
'the image minimum disk size (%sGiB)')
% min_disk_size)
raise ValidationError(error_message)
elif (data.get("volume_source", None) and
source_type in ['', None, 'volume_source']):
# Create from volume
volume = self.get_volume(request, data["volume_source"])
volume_id = volume.id
if data['size'] < volume.size:
error_message = (_('The volume size cannot be less than '
'the source volume size (%sGiB)')
% volume.size)
raise ValidationError(error_message)
else:
if type(data['size']) is str:
data['size'] = int(data['size'])
if availableGB < data['size']:
error_message = _('A volume of %(req)iGiB cannot be created '
'as you only have %(avail)iGiB of your '
'quota available.')
params = {'req': data['size'],
'avail': availableGB}
raise ValidationError(error_message % params)
elif availableVol <= 0:
error_message = _('You are already using all of your available'
' volumes.')
raise ValidationError(error_message)
metadata = {}
volume = cinder.volume_create(request,
data['size'],
data['name'],
data['description'],
data['type'],
snapshot_id=snapshot_id,
image_id=image_id,
metadata=metadata,
availability_zone=az,
source_volid=volume_id)
message = _('Creating volume "%s"') % data['name']
messages.info(request, message)
return volume
except ValidationError as e:
self.api_error(e.messages[0])
return False
except Exception:
redirect = reverse("horizon:project:volumes:index")
exceptions.handle(request,
_("Unable to create volume."),
redirect=redirect)
0
Example 180
Project: manila-ui Source File: forms.py
def handle(self, request, data):
try:
# usages = quotas.tenant_limit_usages(self.request)
# availableGB = usages['maxTotalShareGigabytes'] - \
# usages['gigabytesUsed']
# availableVol = usages['maxTotalShares'] - usages['sharesUsed']
snapshot_id = None
source_type = data.get('share_source_type', None)
share_network = data.get('share_network', None)
if (data.get("snapshot", None) and
source_type in [None, 'snapshot']):
# Create from Snapshot
snapshot = self.get_snapshot(request,
data["snapshot"])
snapshot_id = snapshot.id
if (data['size'] < snapshot.size):
error_message = _('The share size cannot be less than the '
'snapshot size (%sGiB)') % snapshot.size
raise ValidationError(error_message)
else:
if type(data['size']) is str:
data['size'] = int(data['size'])
#
# if availableGB < data['size']:
# error_message = _('A share of %(req)iGB cannot be created as '
# 'you only have %(avail)iGB of your quota '
# 'available.')
# params = {'req': data['size'],
# 'avail': availableGB}
# raise ValidationError(error_message % params)
# elif availableVol <= 0:
# error_message = _('You are already using all of your '
# 'available'
# ' shares.')
# raise ValidationError(error_message)
metadata = {}
try:
set_dict, unset_list = utils.parse_str_meta(data['metadata'])
if unset_list:
msg = _("Expected only pairs of key=value.")
raise ValidationError(message=msg)
metadata = set_dict
except ValidationError as e:
self.api_error(e.messages[0])
return False
share = manila.share_create(
request,
size=data['size'],
name=data['name'],
description=data['description'],
proto=data['share_proto'],
share_network=share_network,
snapshot_id=snapshot_id,
share_type=data['share_type'],
is_public=data['is_public'],
metadata=metadata,
availability_zone=data['availability_zone'])
message = _('Creating share "%s"') % data['name']
messages.success(request, message)
return share
except ValidationError as e:
self.api_error(e.messages[0])
return False
except Exception:
exceptions.handle(request, ignore=True)
self.api_error(_("Unable to create share."))
return False
0
Example 181
Project: unisubs Source File: forms.py
def clean_draft(self):
data = self.cleaned_data['draft']
if data.size > SUBTITLE_FILESIZE_LIMIT_KB * 1024:
raise forms.ValidationError(fmt(
_(u'File size must be less than %(size)s kb.'),
size=SUBTITLE_FILESIZE_LIMIT_KB))
parts = data.name.rsplit('.', 1)
self.extension = parts[-1].lower()
if self.extension not in babelsubs.get_available_formats():
raise forms.ValidationError(fmt(_(
u'Unsupported format. Please upload one of '
u'the following: %(formats)s'),
formats=", ".join(SUBTITLE_FILE_FORMATS)))
text = data.read()
encoding = chardet.detect(text)['encoding']
if not encoding:
raise forms.ValidationError(_(u'Can not detect file encoding'))
# For xml based formats we can't just convert to unicode, as the parser
# will complain that the string encoding doesn't match the encoding
# declaration in the xml file if it's not utf-8.
is_xml = self.extension in ('dfxp', 'ttml', 'xml')
decoded = force_unicode(text, encoding) if not is_xml else text
try:
# we don't know the language code yet, since we are early in the
# clean process. Set it to blank for now and we'll set it to the
# correct value in save()
self._parsed_subtitles = load_subtitles('', decoded,
self.extension)
except TypeError, e:
raise forms.ValidationError(e)
except ValueError, e:
raise forms.ValidationError(e)
data.seek(0)
return data
0
Example 182
Project: unisubs Source File: forms.py
def clean(self):
if self.video.is_writelocked:
raise forms.ValidationError(_(
u'Somebody is subtitling this video right now. Try later.'))
from_language_code = self.cleaned_data.get('from_language_code')
language_code = self.cleaned_data['language_code']
subtitle_language = self.video.subtitle_language(language_code)
if from_language_code:
# If this is a translation, we'll retrieve the source
# language/version here so we can use it later.
self.from_sl = self.video.subtitle_language(from_language_code)
if self.from_sl is None:
raise forms.ValidationError(fmt(
_(u'Invalid from language: %(language)s'),
language=get_language_label(from_language_code)))
self.from_sv = self.from_sl.get_tip(public=True)
if self.from_sv is None:
raise forms.ValidationError(fmt(
_(u'%(language)s has no public versions'),
language=get_language_label(from_language_code)))
else:
self.from_sl = None
self.from_sv = None
# If this SubtitleLanguage already exists, we need to verify a few
# things about it before we let the user upload a set of subtitles to
# it.
if subtitle_language:
# Verify that it's not writelocked.
self._verify_not_writelocked(subtitle_language)
# Make sure there are no translation conflicts. Basically, fail if
# any of the following are true:
#
# 1. The user specified that this was a translation, but the
# existing SubtitleLanguage is *not* a translation.
# 2. The user specified that this was a translation, and the
# existing language is a translation, but of a different language
# than the user gave.
self._verify_no_translation_conflict(subtitle_language,
from_language_code)
# If we are translating from another version, check that the number of
# subtitles matches the source.
self._verify_translation_subtitle_counts(from_language_code)
workflow = self.video.get_workflow()
if not workflow.user_can_edit_subtitles(self.user, language_code):
raise forms.ValidationError(_(
u"Sorry, we can't upload your subtitles because this "
u"language is moderated."))
# Videos that are part of a team have a few more restrictions.
team_video = self.video.get_team_video()
if team_video:
# You can only upload to a language with a subtitle/translate task
# open if that task is assigned to you, or if it's unassigned and
# you can assign yourself.
self._verify_no_blocking_subtitle_translate_tasks(team_video,
language_code)
# You cannot upload at all to a language that has a review or
# approve task open.
self._verify_no_blocking_review_approve_tasks(team_video,
language_code)
return self.cleaned_data