def safe_summary(self, encoded): assert encoded.startswith('sha1$$') hash = encoded[6:] return OrderedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(hash)), ])
class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True}), ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password
class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user's password, but you can change the password using " "<a href=\"{}\">this form</a>." ), ) class Meta: model = UserModel fields = '__all__' field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get('password') if password: password.help_text = password.help_text.format('../password/') user_permissions = self.fields.get('user_permissions') if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related('content_type') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial.get('password')
class Portlet(models.Model): name = models.CharField(256, null=False, label=_('Portlet Type')) schema = models.CharField(128, db_index=True) active = models.BooleanField(default=True, label=_('Active')) tag = models.CharField(128, label=_('Tag Name'), null=False) type_name = models.CharField(label=_('Type Name')) description = models.TextField() info = models.TextField() class Meta: name = 'ui.portlet' def get_info(self): info = self.info if self.type_name: tp = import_string(self.type_name) info = tp.get_info() return { 'id': self.pk, 'name': gettext(self.name), 'tag': self.tag, 'description': self.description, 'info': info, } @api.classmethod def search_portlets(cls): res = [] for p in Portlet.objects.filter(active=True): res.append(p.get_info()) return {'portlets': res}
class Contacts(models.Model): user = models.ForeignKey('auth.user', null=False, default=get_current_user) partner = models.ForeignKey('res.partner', verbose_name=_('Partner')) active = models.BooleanField(default=True, verbose_name=_('Active')) class Meta: name = 'calendar.contacts'
def safe_summary(self, encoded): algorithm, salt, data = encoded.split('$', 2) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('salt'), salt), (_('hash'), mask_hash(data, show=3)), ])
class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = UserModel fields = ("username",) field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
def safe_summary(self, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('iterations'), iterations), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(hash)), ])
class CashboxLine(models.Model): coin_value = models.FloatField(verbose_name=_('Coin/Bill Value'), null=False) number = models.IntegerField(verbose_name=_('#Coins/Bills')) # subtotal = models.FloatField() cashbox = models.ForeignKey('account.bank.statement.cashbox', verbose_name=_('Cashbox')) currency = models.ForeignKey('res.currency', proxy='cashbox.currency') class Meta: name = 'account.cashbox.line'
def safe_summary(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split('$', 4) assert algorithm == self.algorithm salt, checksum = data[:22], data[22:] return OrderedDict([ (_('algorithm'), algorithm), (_('work factor'), work_factor), (_('salt'), mask_hash(salt)), (_('checksum'), mask_hash(checksum)), ])
class Attendee(models.Model): """Calendar Attendee Information""" STATUS = ( ('action', _('Needs Action')), ('uncertain', _('Uncertain')), ('declined', _('Declined')), ('accepted', _('Accepted')), ) status = models.ChoiceField( STATUS, readonly=True, default='needs-action', help_text="Status of the attendee's participation" ) partner = models.ForeignKey('res.partner', 'Contact', readonly=True) email = models.EmailField(verbose_name=_('Email'), help_text="Email of Invited Person") availability = models.ChoiceField( (('free', _('Free')), ('busy', _('Busy'))), verbose_name=_('Free/Busy'), readonly=True ) access_token = models.CharField(64, 'Invitation Token') event = models.ForeignKey('calendar.event', _('Meeting linked'), ondelete=models.CASCADE) class Meta: name = 'calendar.attendee' verbose_name = 'Calendar Attendee Information' verbose_name_plural = 'Calendar Attendee Informations'
def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _('midnight') if self.data.minute == 0 and self.data.hour == 12: return _('noon') return '%s %s' % (self.f(), self.a())
class AdminPasswordChangeForm(forms.Form): """ A form used to change the password of a user in the admin interface. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } required_css_class = 'required' password1 = forms.CharField( label=_("Password"), widget=forms.PasswordInput(attrs={'autofocus': True}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password (again)"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): """Save the new password.""" password = self.cleaned_data["password1"] self.user.set_password(password) if commit: self.user.save() return self.user @property def changed_data(self): data = super().changed_data for name in self.fields: if name not in data: return [] return ['password']
class ServerActionLine(models.Model): server_action = models.ForeignKey(ServerAction, null=False, on_delete=models.CASCADE) field = models.ForeignKey('content.field') value = models.TextField() type = models.SelectionField( ( ('value', _('Value')), ('expr', _('Python Expression')), ), label=_('Evaluation Type') ) class Meta: name = 'ui.action.server.line'
class Filter(models.Model): name = models.CharField(256, null=False, verbose_name=_('Name')) user = models.ForeignKey('auth.user', on_delete=models.CASCADE) domain = models.TextField() context = models.TextField() sort = models.TextField() params = models.TextField() is_default = models.BooleanField(default=False) is_shared = models.BooleanField(default=True) action = models.ForeignKey('ui.action', verbose_name=_('Action')) # query = models.ForeignKey('ir.query') active = models.BooleanField(default=True) class Meta: name = 'ui.filter'
class ViewAction(Action): view = models.ForeignKey('ui.view', label=_('View')) class Meta: name = 'ui.action.view' def _get_info(self, context): from orun.contrib.admin.models.ui import View res = super()._get_info(context) # it's a system class if self.qualname: admin_class = import_string(self.qualname) res.update(admin_class.render(None)) del res['qualname'] view = res.get('view') if view and view['id']: res['template'] = View.objects.get(pk=view['id']).get_content() return res @api.classmethod def get_view(cls, id): if isinstance(id, list): id = id[0] view = apps['ui.view'].objects.get(pk=id) return { 'content': view.render({}), 'type': view.view_type, }
class ClientAction(Action): tag = models.CharField(512) target = models.SelectionField( ( ('current', 'Current Window'), ('new', 'New Window'), ('fullscreen', 'Full Screen'), ('main', 'Main Action of Current Window'), ), default='current', ) model_name = models.CharField(label=_('Model')) context = models.TextField() params = models.TextField() view = models.ForeignKey('ui.view') class Meta: name = 'ui.action.client' @api.method(request=True) def get_view(self, id, request): vw = self.objects.get(id) if vw.view: return { 'content': vw.view.render({}), }
def validate_ipv46_address(value): try: validate_ipv4_address(value) except ValidationError: try: validate_ipv6_address(value) except ValidationError: raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
class AppConfig(orun.AppConfig): name = _('Pwa') version = '0.1' auto_install = False installable = True #fixtures = ['actions.xml', 'menu.xml'] #demo = ['demo.json'] dependencies = ['base']
def change_password(self, old_password, new_password): # check user password print(self.env.user) user = auth.authenticate(username=self.env.user.username, password=old_password) if user and new_password: user.set_password(new_password) user.save() return self.env.user_id raise PermissionDenied(_('Invalid password!'))
class WindowActionView(models.Model): window_action = models.ForeignKey(WindowAction, null=False) sequence = models.SmallIntegerField() view = models.ForeignKey('ui.view') view_mode = models.SelectionField(WindowAction.VIEW_MODE, label=_('View Type')) class Meta: name = 'ui.action.window.view' title_field = 'view'
class Stage(models.Model): """ Model for case stages. This models the main stages of a document management flow. Main CRM objects (leads, opportunities, project issues, ...) will now use only stages, instead of state and stages. Stages are for example used to display the kanban view of records. """ name = models.CharField( 128, verbose_name=_('Stage Name'), null=False, translate=True ) sequence = models.IntegerField( verbose_name=_('Sequence'), default=1, help_text="Used to order stages. Lower is better." ) probability = models.FloatField( verbose_name=_('Probability (%)'), null=False, default=10.0, help_text="This percentage depicts the default/average probability of the Case for this stage to be a success") on_change = models.BooleanField( verbose_name=_('Change Probability Automatically'), help_text="Setting this stage will change the probability automatically on the opportunity.") requirements = models.TextField( verbose_name=_('Requirements'), help_text="Enter here the internal requirements for this stage (ex: Offer sent to customer). It will appear as a tooltip over the stage's name." ) team_id = models.ForeignKey( 'crm.team', verbose_name='Sales Team', ondelete=models.CASCADE, help_text='Specific team that uses this stage. Other teams will not be able to see or use this stage.' ) legend_priority = models.TextField( verbose_name=_('Priority Management Explanation'), translate=True, help_text='Explanation text to help users using the star and priority mechanism on stages or issues that are in this stage.' ) fold = models.BooleanField( verbose_name=_('Folded in Pipeline'), help_text='This stage is folded in the kanban view when there are no records in that stage to display.' ) # This field for interface only team_count = models.IntegerField('team_count', compute='_compute_team_count') @api.record def default_get(self, fields): """ Hack : when going from the pipeline, creating a stage with a sales team in context should not create a stage for the current Sales Team only """ ctx = dict(self.env.context) if ctx.get('default_team_id') and not ctx.get('crm_team_mono'): ctx.pop('default_team_id') return super(Stage, self.with_context(ctx)).default_get(fields) @api.records def _compute_team_count(self): for stage in self: stage.team_count = self.env['crm.team'].search_count([]) class Meta: name = "crm.stage" verbose_name = "CRM Stages" ordering = ('sequence', 'name', 'id')
class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput, ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user
class ServerAction(Action): sequence = models.IntegerField(default=5) model = models.ForeignKey('content.type', null=False) code = models.TextField(label=_('Python Code')) actions = models.ManyToManyField('self') target_model = models.ForeignKey('content.type') target_field = models.ForeignKey('content.field') lines = models.OneToManyField('ui.action.server.line') class Meta: name = 'ui.action.server'
class Rule(models.Model): name = models.CharField(128, verbose_name=_('object name'), null=False) active = models.BooleanField(default=True) content_type = models.ForeignKey('content.type', null=False, db_index=True, on_delete=models.DB_CASCADE) groups = models.ManyToManyField('auth.group') domain = models.TextField() class Meta: name = 'ir.rule'
def safe_summary(self, encoded): (algorithm, variety, version, time_cost, memory_cost, parallelism, salt, data) = self._decode(encoded) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('variety'), variety), (_('version'), version), (_('memory cost'), memory_cost), (_('time cost'), time_cost), (_('parallelism'), parallelism), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(data)), ])
class Alarm(models.Model): name = models.ChoiceField(verbose_name=_('Name'), translate=True, null=False) alarm_type = models.ChoiceField( ( ('notification', 'Notification'), ('email', 'Email') ), verbose_name=_('Type'), null=False, default='email' ) duration = models.IntegerField(verbose_name=_('Remind Before'), null=False, default=1) interval_unit = models.ChoiceField( ( ('minutes', 'Minute(s)'), ('hours', 'Hour(s)'), ('days', 'Day(s)') ), 'Interval Unit', null=False, default='hours' ) duration_minutes = models.IntegerField( verbose_name=_('Duration in minutes'), compute='_compute_duration_minutes', store=True, help_text="Duration in minutes" ) class Meta: name = 'calendar.alarm' verbose_name = 'Event Alarm'
def prepare_meta_class(cls, opts): fields = opts.local_fields user_model = settings.AUTH_USER_MODEL fields['created_by'] = ForeignKey( user_model, verbose_name=_('Created by'), on_insert_value=current_user_id, auto_created=True, editable=False, deferred=True, db_index=False, copy=False, db_constraint=False, ) fields['created_on'] = DateTimeField(auto_now_add=True, verbose_name=_('Created on'), auto_created=True, editable=False, deferred=True, copy=False) fields['updated_by'] = ForeignKey( user_model, verbose_name=_('Updated by'), on_update_value=current_user_id, auto_created=True, editable=False, deferred=True, db_index=False, copy=False, db_constraint=False, ) fields['updated_on'] = DateTimeField(auto_now=True, verbose_name=_('Updated on'), auto_created=True, editable=False, deferred=True, copy=False)
class Action(models.Model): name = models.CharField(128, _('Name'), null=False, translate=True) action_type = models.CharField(32, _('Action Type'), null=False) usage = models.TextField(label=_('Usage')) description = models.TextField(label=_('Description')) # external_id = models.CharField(label=_('External ID'), getter='get_external_id') groups = models.ManyToManyField('auth.group') binding_model = models.ForeignKey('content.type', on_delete=models.CASCADE) binding_type = models.SelectionField( ( ('action', _('Action')), ('print', _('Print')), ), default='action', ) multiple = models.BooleanField(default=False, label='Restrict to lists') qualname = models.CharField(help_text='System qualified name') class Meta: name = 'ui.action' field_groups = { 'list_fields': ['name', 'action_type', 'usage'] } def save(self, *args, **kwargs): if not self.action_type: self.action_type = self.__class__._meta.name super(Action, self).save(*args, **kwargs) def get_action(self): return apps[self.action_type].objects.get(pk=self.pk) @api.classmethod def load(cls, name_or_id, context=None): try: name_or_id = int(name_or_id) except ValueError: if isinstance(name_or_id, str): name_or_id = ref(name_or_id) info = cls.get(name_or_id).get_action()._get_info(context) info['type'] = info.pop('action_type') return info def execute(self): raise NotImplemented() @classmethod def get_bindings(cls, model): r = defaultdict(list) # TODO: optimize filter by name (plain query) obj = apps['content.type'].objects.get_by_natural_key(model) for action in cls.objects.filter(binding_model_id=obj.pk): r[action.binding_type].append(action) return r def _get_info(self, context): return self.to_dict(exclude=['groups'])
class BankStatement(models.Model): name = models.CharField(verbose_name='Reference', states={'open': {'readonly': False}}, copy=False, readonly=True) reference = models.CharField(verbose_name='External Reference', states={'confirm': {'readonly': False}}, copy=False, readonly=True) date = models.DateField(null=False, states={'confirm': {'readonly': True}}) date_done = models.DateTimeField(verbose_name=_('Closed On')) balance_start = models.MonetaryField(verbose_name=_('Starting Balance'), states={'confirm': {'readonly': True}}) balance_end_real = models.MonetaryField('Ending Balance', states={'confirm': [('readonly', True)]}) accounting_date = models.DateField(verbose_name="Accounting Date", help_text="If set, the accounting entries created during the bank statement reconciliation process will be created at this date.\n" "This is useful if the accounting period in which the entries should normally be booked is already closed.", states={'open': [('readonly', False)]}, readonly=True) state = models.ChoiceField([('open', 'New'), ('confirm', 'Validated')], verbose_name='Status', null=False, readonly=True, copy=False, default='open') currency = models.ForeignKey('res.currency', compute='_compute_currency', verbose_name="Currency") journal = models.ForeignKey('account.journal', verbose_name='Journal', null=False, states={'confirm': [('readonly', True)]}, default=_default_journal) journal_type = models.ChoiceField(proxy='journal.type', help_text="Technical field used for usability purposes") company = models.ForeignKey( 'res.company', proxy='journal.company', verbose_name='Company', store=True, readonly=True, default=lambda self: self.env.company ) total_entry_encoding = models.MonetaryField('Transactions Subtotal', compute='_end_balance', store=True, help_text="Total of transaction lines.") balance_end = models.MonetaryField('Computed Balance', compute='_end_balance', store=True, help_text='Balance as calculated based on Opening Balance and transaction lines') difference = models.MonetaryField(compute='_end_balance', store=True, help_text="Difference between the computed ending balance and the specified ending balance.") lines = models.OneToManyField('account.bank.statement.line', 'statement', verbose_name='Statement lines', states={'confirm': [('readonly', True)]}, copy=True) move_lines = models.OneToManyField('account.move.line', 'statement', verbose_name='Entry lines', states={'confirm': [('readonly', True)]}) move_line_count = models.IntegerField(compute="_get_move_line_count") all_lines_reconciled = models.BooleanField(compute='_check_lines_reconciled') user = models.ForeignKey('res.users', verbose_name='Responsible', required=False, default=lambda self: self.env.user) cashbox_start = models.ForeignKey('account.bank.statement.cashbox', verbose_name="Starting Cashbox") cashbox_end = models.ForeignKey('account.bank.statement.cashbox', verbose_name="Ending Cashbox") is_difference_zero = models.BooleanField(compute='_is_difference_zero', verbose_name='Is zero', help_text="Check if difference is zero.") class Meta: name = 'account.bank.statement' verbose_name = _('Bank Statement')
class AuthConfig(AppConfig): name = 'orun.contrib.auth' verbose_name = _("Authentication and Authorization") dependencies = ['orun.contrib.contenttypes'] def ready(self): post_migrate.connect( create_permissions, dispatch_uid="orun.contrib.auth.management.create_permissions" ) last_login_field = apps['auth.user'].last_login # Register the handler only if UserModel.last_login is a field. if isinstance(last_login_field, DeferredAttribute): from .models import update_last_login user_logged_in.connect(update_last_login, dispatch_uid='update_last_login') checks.register(check_user_model, checks.Tags.models) checks.register(check_models_permissions, checks.Tags.models)
class ProductionLot(models.Model): name = models.CharField( 100, label=_('Lot/Serial'), null=False, help_text=_('Unique Lot/Serial Number'), default=lambda self: self.env['ir.sequence'].next_by_code( 'stock.lot.serial'), ) ref = models.CharField( 100, label=_('Internal Reference'), help_text= _("Internal reference number in case it differs from the manufacturer's lot/serial number" )) product = models.ForeignKey('product.product', label=_('Product'), null=False, check_company=True, filter=lambda self: self.domain_product_id()) product_uom = models.ForeignKey('uom.uom', label=_('Unit of Measure'), related='product.uom', stored=True) quants = models.OneToManyField('stock.quant', readonly=True) product_qty = models.DecimalField(label=_('Quantity'), getter='get_product_qty') description = models.HtmlField(label=_('Description')) display_complete = models.BooleanField(getter='get_display_complete') company = models.ForeignKey('res.company', label=_('Company'), null=False, stored=True, db_index=True) class Meta: name = 'stock.production.lot' verbose_name = 'Lot/Serial'
def action_your_pipeline(self): action = self.env.ref('crm.crm_lead_opportunities_tree_view').read()[0] user_team_id = self.env.user.sale_team_id.id if not user_team_id: user_team_id = self.search([], limit=1).id action['help'] = _( """<p class='o_view_nocontent_smiling_face'>Add new opportunities</p><p> Looks like you are not a member of a Sales Team. You should add yourself as a member of one of the Sales Team. </p>""") if user_team_id: action[ 'help'] += "<p>As you don't belong to any Sales Team, Odoo opens the first one by default.</p>" action_context = safe_eval(action['context'], {'uid': self.env.uid}) if user_team_id: action_context['default_team_id'] = user_team_id action['context'] = action_context return action
def get_text_list(list_, last_word=gettext_lazy('or')): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if len(list_) == 0: return '' if len(list_) == 1: return force_text(list_[0]) return '%s %s %s' % ( # Translators: This string is used as a separator between list elements _(', ').join(force_text(i) for i in list_[:-1]), force_text(last_word), force_text(list_[-1]))
def safe_summary(self, encoded): return OrderedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(encoded, show=3)), ])
def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _('PM') return _('AM')
def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _('p.m.') return _('a.m.')
"Commonly-used date structures" from orun.utils.translation import pgettext_lazy, ugettext_lazy as _ WEEKDAYS = { 0: _('Monday'), 1: _('Tuesday'), 2: _('Wednesday'), 3: _('Thursday'), 4: _('Friday'), 5: _('Saturday'), 6: _('Sunday') } WEEKDAYS_ABBR = { 0: _('Mon'), 1: _('Tue'), 2: _('Wed'), 3: _('Thu'), 4: _('Fri'), 5: _('Sat'), 6: _('Sun') } WEEKDAYS_REV = { 'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday': 5, 'sunday': 6 } MONTHS = { 1: _('January'), 2: _('February'), 3: _('March'), 4: _('April'), 5: _('May'), 6: _('June'), 7: _('July'), 8: _('August'), 9: _('September'), 10: _('October'), 11: _('November'), 12: _('December') } MONTHS_3 = { 1: _('jan'), 2: _('feb'), 3: _('mar'), 4: _('apr'), 5: _('may'), 6: _('jun'), 7: _('jul'), 8: _('aug'), 9: _('sep'), 10: _('oct'), 11: _('nov'), 12: _('dec') } MONTHS_3_REV = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12 } MONTHS_AP = { # month names in Associated Press style 1: pgettext_lazy('abbrev. month', 'Jan.'),
def read_object(self, obj, trans=False, **attrs): ct = self.app['ir.model'] if not isinstance(obj, dict): values = obj.getchildren() obj = dict(obj.attrib) else: values = obj.get('children', []) if 'fields' not in obj: obj['fields'] = {} for child in values: if child.tag == 'field': field_name = child.attrib['name'] if 'ref' in child.attrib: try: obj['fields'][field_name] = ref(self.app, child.attrib['ref']) except: print('Error reading xml file file: ref:', child.attrib['ref'], self.app, self.options['filename']) raise elif 'eval' in child.attrib: obj['fields'][field_name] = eval(child.attrib['eval'], {'ref': functools.partial(ref, self.app)}) elif 'model' in child.attrib: obj['fields'][field_name] = ct.objects.only('pk').filter(ct.c.name == child.attrib['model']).first().pk elif 'file' in child.attrib: obj['fields'][field_name] = open( os.path.join(self.app_config.root_path, child.attrib['file']), encoding='utf-8' ).read() else: s = child.text if child.attrib.get('translate', trans): s = (s,) obj['fields'][field_name] = s obj_name = obj.pop('id') obj_id = None Model = self.app[obj['model']] values = obj['fields'] # # ui.view special case # if Model._meta.name == 'ui.view' and 'template_name' in values: # template_name = values['template_name'] # values['template_name'] = self.app_config.schema + ':' + template_name # assert '..' not in template_name # template_name = os.path.join(self.app_config.path, self.app_config.template_folder, template_name) # with open(template_name, encoding='utf-8') as f: # values['content'] = f.read() Object = app['ir.object'] can_update = not (obj.get('noupdate', False) and True) try: obj_id = Object.objects.filter(Object.c.name == obj_name).one() if can_update != obj_id.can_update: obj_id.can_update = can_update obj_id.save() instance = obj_id.object if not can_update: return instance except ObjectDoesNotExist: instance = Model() pk = instance.pk children = {} for k, v in values.items(): # Check if there's a list of objects field = instance._meta.fields.get(k) if isinstance(v, list) and isinstance(field, models.OneToManyField): children[k] = v elif isinstance(v, tuple) and isinstance(field, models.CharField) and not field.translate: children[k] = _(v[0]) else: setattr(instance, *get_prep_value(Model, k, field, v)) instance.save() if pk is None: obj_id = Object.create( app_label=self.app_config.app_label, name=obj_name, object_id=instance.pk, model=instance._meta.name, can_update=not (obj.get('noupdate', False) and True), ) for child, v in children.items(): # Delete all items getattr(instance, child).delete() # Re-eval the xml data instance._meta.fields_dict[k].deserialize(v, instance) return instance
def clean_ipv6_address(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")): """ Cleans an IPv6 address string. Validity is checked by calling is_valid_ipv6_address() - if an invalid address is passed, ValidationError is raised. Replaces the longest continuous zero-sequence with "::" and removes leading zeroes and makes sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is found, return the plain IPv4 address (default=False). error_message: An error message used in the ValidationError. Returns: A compressed IPv6 address, or the same value """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 if not is_valid_ipv6_address(ip_str): raise ValidationError(error_message, code='invalid') # This algorithm can only handle fully exploded # IP strings ip_str = _explode_shorthand_ip_string(ip_str) ip_str = _sanitize_ipv4_mapping(ip_str) # If needed, unpack the IPv4 and return straight away # - no need in running the rest of the algorithm if unpack_ipv4: ipv4_unpacked = _unpack_ipv4(ip_str) if ipv4_unpacked: return ipv4_unpacked hextets = ip_str.split(":") for index in range(len(hextets)): # Remove leading zeroes if '.' not in hextets[index]: hextets[index] = hextets[index].lstrip('0') if not hextets[index]: hextets[index] = '0' # Determine best hextet to compress if hextets[index] == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 # Compress the most suitable hextet if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets result = ":".join(hextets) return result.lower()
try: validate_ipv6_address(potential_ip) except ValidationError: raise ValidationError(self.message, code=self.code) url = value # The maximum length of a full host name is 253 characters per RFC 1034 # section 3.1. It's defined to be 255 bytes or less, but this includes # one byte for the length of the name and one byte for the trailing dot # that's used to indicate absolute names in DNS. if len(urlsplit(value).netloc) > 253: raise ValidationError(self.message, code=self.code) integer_validator = RegexValidator( _lazy_re_compile('^-?\d+\Z'), message=_('Enter a valid integer.'), code='invalid', ) def validate_integer(value): return integer_validator(value) class EmailValidator(object): message = _('Enter a valid email address.') code = 'invalid' user_regex = _lazy_re_compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string re.IGNORECASE)
def validate_ipv6_address(value): if not is_valid_ipv6_address(value): raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')