class UserDemo(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=30) telephone = models.CharField( max_length=11, validators=[validators.RegexValidator(r'1[3456789]\d{9}')])
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from django.utils.translation import ugettext_lazy as _ from django.core import validators as django_validators name_validator = django_validators.RegexValidator( r'^[\w.~-]+$', _('Enter a valid username. This value may contain only letters, ' 'numbers and ~/./-/_ characters.'), 'invalid')
class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( '昵称', max_length=30, unique=True, help_text='昵称长度4-20个字符,支持中英文、数字、-、_', validators=[ validators.RegexValidator('^[a-zA-Z0-9-_\u4e00-\u9fa5]+$', '昵称长度4-20个字符,支持中英文、数字、-、_', 'invalid') ]) email = models.EmailField('邮箱', default=None, unique=True, null=True, blank=True) password = models.CharField('密码', blank=True, null=True, max_length=128) is_password_set = models.BooleanField('是否设置密码', default=True) is_username_set = models.BooleanField('是否设置昵称', default=True) date_joined = models.DateTimeField('注册时间', default=timezone.now) is_staff = models.BooleanField('是否是职员', default=False) mobile = models.CharField('手机号', max_length=100, default=None, unique=True, null=True) province = models.CharField('省份', max_length=100, null=True, blank=True, db_index=True) city = models.CharField('城市', max_length=100, null=True, blank=True, db_index=True) district = models.CharField('地区', max_length=50, null=True, blank=True) street = models.CharField('详细地址', max_length=100, null=True, blank=True) GENDER = ( (0, '保密'), (1, '男'), (2, '女'), ) CAREER = ( ('5', '房地产'), ('10', '国有企业'), ('2', '教科文'), ('3', '金融'), ('4', '商贸'), ('9', '事业单位'), ('1', '政府部门'), ('6', '制造业'), ('7', '自由职业'), ('8', '其他'), ) gender = models.SmallIntegerField('性别', null=True, blank=True, choices=GENDER, default=0) description = models.TextField('简介', null=True, blank=True) birthday = models.DateField('生日', null=True, blank=True) career = models.CharField( '职业', choices=CAREER, max_length=20, null=True, blank=True) qq = models.CharField(max_length=20, default=None, null=True, blank=True) we_chat = models.CharField( '微信', max_length=200, default=None, null=True, blank=True) we_bo = models.CharField( '微博', max_length=200, default=None, null=True, blank=True) modified_at = models.DateTimeField('修改时间', auto_now = True) VERIFIED_STATUS = ( (-1, '未提交'), (0, '审核中'), (1, '已认证'), (2, '审核失败'), ) verified_status = models.SmallIntegerField('认证状态', choices=VERIFIED_STATUS, default=-1) verified_reason = models.CharField('认证说明', max_length=200, null=True, blank=True) is_system = models.BooleanField('是否系统用户', default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = '用户' verbose_name_plural = verbose_name app_label = 'accounts'
class addUserForm(ModelForm): email = forms.CharField( label="Email", help_text="Required", widget=forms.TextInput(attrs={ 'class': 'form_control', 'placeholder': 'i.e: [email protected]' })) username = forms.CharField( label="Login", help_text="Required", max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField( widget=forms.PasswordInput(), help_text="Required", validators=[ validators.MinLengthValidator( limit_value=8, message='La contraseña no puede tener menos de 8 caracteres') ]) is_trainer = forms.ModelChoiceField(label="Entrenador Asignado", required=False, queryset=User.objects.filter(grupo=3)) first_name = forms.CharField( label="Nombre", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control'}), help_text="Required", validators=[ validators.RegexValidator( regex="[a-zA-Z]", message="No se admiten caracteres numéricos en el nombre") ]) last_name = forms.CharField( label="Apellidos", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control'}), help_text="Required", validators=[ validators.RegexValidator( regex="[a-zA-Z]", message="No se admiten caracteres numéricos en el nombre") ]) active = forms.ChoiceField(label="¿Está activo?", choices=active_choices, required=True, help_text="Required") staff = forms.ChoiceField(label="¿Es personal?", choices=staff_choices, required=True, help_text="Required") is_superuser = forms.ChoiceField(label="¿Es superusuario?", choices=superuser_choices, required=True, help_text="Required") grupo = forms.ChoiceField(label="Grupo de Usuario", choices=group_choices, required=True, help_text="Required") def clean(self): super(addUserForm, self).clean() email = self.cleaned_data.get('email') is_valid = validate_email(email) if not is_valid: self._errors['email'] = self.error_class(['El email no es válido']) return self.cleaned_data def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = User fields = [ 'email', 'username', 'is_trainer', 'first_name', 'last_name', 'active', 'staff', 'is_superuser', 'password' ]
import logging from django.core.urlresolvers import reverse from django.core import validators from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) validate_mac = validators.RegexValidator(r'([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}', _("Invalid MAC Address format"), code="invalid_mac") class AddAllowedAddressPairForm(forms.SelfHandlingForm): ip = forms.IPField(label=_("IP Address or CIDR"), help_text=_("A single IP Address or CIDR"), version=forms.IPv4 | forms.IPv6, mask=True) mac = forms.CharField(label=_("MAC Address"), help_text=_("A valid MAC Address"), validators=[validate_mac], required=False) failure_url = 'horizon:network:networks2:ports:detail' def clean(self):
from django.core import validators as core_validators from django.utils.translation import gettext_lazy as _ business_id_re = core_validators._lazy_re_compile(r"^.{9}$") validate_business_id = core_validators.RegexValidator( business_id_re, _("Enter a valid business id."), "invalid")
class User(AbstractBaseUser, PermissionsMixin): class Meta: app_label = 'accounts' db_table = "auth_user" username = models.CharField( _('username'), max_length=75, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[ validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid') ]) full_name = models.CharField(_('full name'), max_length=254, blank=True, help_text="Full name of the user") email = models.EmailField(_('email address'), max_length=254, unique=True) title = models.CharField(max_length=100, blank=True, help_text="Title of the user") phone = models.CharField(max_length=25, blank=True, help_text="Phone number of the user") company = models.CharField(max_length=100, blank=True, help_text="Company of the user") website = models.URLField(max_length=100, blank=True, help_text="Website of the user") street_1 = models.CharField(max_length=100, blank=True, help_text="Street of the user") street_2 = models.CharField(max_length=100, blank=True, help_text="APT/Building of the user") city = models.CharField(max_length=100, blank=True, help_text="City of the user") state = models.CharField(max_length=4, blank=True, choices=US_STATES, help_text="State of the user") country = models.CharField(max_length=50, blank=True, help_text="Country of the user") zipcode = models.CharField(max_length=25, blank=True, help_text="Zipcode name of the user") is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) password_hash = models.CharField(max_length=50, null=True, help_text="Forgot password hash") objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def get_full_name(self): return self.full_name def get_short_name(self): return self.username
from django.core import validators name_validators = [ validators.RegexValidator( r"^[\w ’ʼʻʽˈ՚‘ʹ′‵Ꞌꞌ'–−-]+$", 'Merci de saisir uniquement lettres et tirets', ), validators.RegexValidator( r'^[^\d_]+$', 'Merci de saisir uniquement lettres et tirets', ), ] def name_clean(name): replaces = { "'": "’ʼʻʽˈ՚‘ʹ′‵Ꞌꞌ'", "-": "–−-", } for clean, dirties in replaces.items(): for dirty in dirties: name = name.replace(dirty, clean) return name
class User( LoggableMixin, UuidMixin, DescribableMixin, AbstractBaseUser, UserDetailsMixin, PermissionsMixin, ): username = models.CharField( _('username'), max_length=128, unique=True, help_text=_('Required. 128 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[ validators.RegexValidator(re.compile(r'^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid') ], ) # Civil number is nullable on purpose, otherwise # it wouldn't be possible to put a unique constraint on it civil_number = models.CharField( _('civil number'), max_length=50, unique=True, blank=True, null=True, default=None, ) email = models.EmailField(_('email address'), max_length=75, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.'), ) is_support = models.BooleanField( _('support status'), default=False, help_text=_('Designates whether the user is a global support user.'), ) date_joined = models.DateTimeField(_('date joined'), default=django_timezone.now) registration_method = models.CharField( _('registration method'), max_length=50, default='default', blank=True, help_text=_('Indicates what registration method were used.'), ) agreement_date = models.DateTimeField( _('agreement date'), blank=True, null=True, help_text=_('Indicates when the user has agreed with the policy.'), ) preferred_language = models.CharField(max_length=10, blank=True) competence = models.CharField(max_length=255, blank=True) token_lifetime = models.PositiveIntegerField( null=True, help_text=_('Token lifetime in seconds.'), validators=[validators.MinValueValidator(60)], ) details = BetterJSONField( blank=True, default=dict, help_text=_('Extra details from authentication backend.'), ) backend_id = models.CharField(max_length=255, blank=True) tracker = FieldTracker() objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_log_fields(self): return ( 'uuid', 'full_name', 'native_name', self.USERNAME_FIELD, 'is_staff', 'is_support', 'token_lifetime', ) def get_full_name(self): # This method is used in django-reversion as name of revision creator. return self.full_name def get_short_name(self): # This method is used in django-reversion as name of revision creator. return self.full_name def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email]) @classmethod def get_permitted_objects(cls, user): from waldur_core.structure.filters import filter_visible_users queryset = User.objects.all() if user.is_staff or user.is_support: return queryset else: return filter_visible_users(queryset, user) def clean(self): super(User, self).clean() # User email has to be unique or empty if (self.email and User.objects.filter(email=self.email).exclude( id=self.id).exists()): raise ValidationError({ 'email': _('User with email "%s" already exists.') % self.email }) @transaction.atomic def create_request_for_update_email(self, email): if User.objects.filter(email=email).exclude(id=self.id).exists(): raise ValidationError( {'email': _('User with email "%s" already exists.') % email}) ChangeEmailRequest.objects.filter(user=self).delete() change_request = ChangeEmailRequest.objects.create( user=self, email=email, ) return change_request def __str__(self): if self.full_name: return '%s (%s)' % (self.get_username(), self.full_name) return self.get_username()
class PersonaForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(PersonaForm, self).__init__(*args, **kwargs) lista_grupo_familiar = [('', 'Selecione...')] for gf in GrupoFamiliar.objects.filter(vivienda__user=user): lista_grupo_familiar.append( (gf.id, gf.apellido_familia + "-" + str(gf.id))) self.fields['grupo_familiar'].choices = lista_grupo_familiar grupo_familiar = forms.ChoiceField( label=_("Grupo Familiar:"), widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione El Grupo Familiar al cual pertenece la Persona"), })) nombre = forms.CharField( label=_("Nombres:"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique los Nombres de la Persona"), })) apellido = forms.CharField( label=_("Apellidos:"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique los Apellidos de la Persona"), })) tiene_cedula = forms.ChoiceField( label=_("¿Tiene Cédula?:"), choices=(('S', _('Si')), ) + (('N', _('No')), ), widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:60px;', 'title': _("Seleccione si tiene cédula"), 'onchange': "_tiene_cedula(this.value)", }), required=False) cedula = CedulaField( required=False, validators=[ validators.RegexValidator( r'^[VE][\d]{8}$', _("Introduzca un número de cédula válido. Solo se permiten números y una longitud de 8 carácteres. Se agrega un 0 si la longitud es de 7 carácteres." )), ]) telefono = TelefonoField(validators=[ validators.RegexValidator( r'^\+\d{3}-\d{3}-\d{7}$', _("Número telefónico inválido. Solo se permiten números y los símbolos: + -" )), ]) correo = forms.EmailField( label=_("Correo Electrónico:"), max_length=100, widget=forms.EmailInput( attrs={ 'class': 'form-control input-sm email-mask', 'placeholder': _("Correo de contacto"), 'data-toggle': 'tooltip', 'size': '30', 'data-rule-required': 'true', 'title': _("Indique el correo electrónico de contacto con la persona.") }), required=False, ) sexo = forms.ChoiceField( label=_("Sexo:"), choices=(('', _('Seleccione...')), ) + SEXO, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione el Sexo de la Persona"), })) fecha_nacimiento = forms.CharField( label=_("Fecha de Nacimieno:"), widget=forms.TextInput( attrs={ 'class': 'form-control input-sm datepicker', 'style': 'width:100%;', 'readonly': 'true', 'onchange': 'calcular_edad(this.value)', })) edad = forms.CharField(label=_("Edad:"), widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'readonly': 'true', 'title': _("Muestra la edad de la Persona"), }), required=False) parentesco = forms.ChoiceField( label=_("Parentesco:"), choices=(('', _('Seleccione...')), ) + PARENTESCO, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione el Parentesco"), })) jefe_familiar = forms.BooleanField( label=_("Jefe Familiar"), help_text= _("Para actualizar los datos de un Jefe Familiar es necesario quitar esta selección y guardar. Hecho los cambios se puede seleccionar de nuevo si el Jefe Familiar se mantiene o se elige otro." ), required=False) estado_civil = forms.ChoiceField( label=_("Estado Civil:"), choices=(('', _('Seleccione...')), ) + ESTADO_CIVIL, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione el Estado Civil de la Persona"), })) grado_instruccion = forms.ChoiceField( label=_("Grado de Instrucción:"), choices=(('', _('Seleccione...')), ) + GRADO_INSTRUCCION, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione el Grado de Instrucción de la Persona"), })) mision_educativa = forms.ChoiceField( label=_("Misión Educativa:"), choices=(('', _('Seleccione...')), ) + MISION_EDUCATIVA, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _( "Seleccione la Misión Educativa que tiene la Persona"), })) mision_social = forms.ChoiceField( label=_("Misión Social:"), choices=(('', _('Seleccione...')), ) + MISION_SOCIAL, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Seleccione la Misión Social que tiene la Persona"), })) profesion = forms.CharField( label=_("Profesión:"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique la Profesión de la Persona"), }), required=False) ocupacion = forms.CharField( label=_("Ocupación:"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique la Ocupación de la Persona"), }), required=False) ingreso = forms.ChoiceField( label=_("Tipo de Ingresos:"), choices=(('', _('Seleccione...')), ) + TIPO_INGRESO, widget=forms.Select( attrs={ 'class': 'form-control select2', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _( "Seleccione el Tipo de Ingreso que tiene la Persona"), })) pensionado = forms.BooleanField(label=_("¿Es Pensionado?"), required=False) jubilado = forms.BooleanField(label=_("¿Es Jubilado?"), required=False) deporte = forms.CharField( label=_("Deporte que Practica:"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique el Deporte que practica de la Persona"), }), required=False) enfermedad = forms.CharField( label=_("Enfermedad que Presenta:"), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique la Enfermedad que Presenta la Persona"), }), required=False) discapacidad = forms.CharField( label=_("Discapacidad que Presenta:"), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique la Discapacidad que Presenta la Persona"), }), required=False) ley_consejo_comunal = forms.BooleanField( label=_("¿Ha Leído la Ley de Consejos Comunales?"), required=False) curso = forms.CharField( label=_("¿Qué Cursos le Gustaría Hacer?"), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique los Cursos que le gustaría hacer"), }), required=False) organizacion_comunitaria = forms.CharField( label=('Organizaciones Comunitarias que conoce:'), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-md', 'data-rule-required': 'true', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _( "Indique las organizaciones comunitarias que conoce"), }), required=False, ) ocio = forms.CharField( label=_("¿Que hace Ud. en sus horas de ocio?"), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique lo que hace en sus horas de Ocio"), }), required=False) mejorar_comunicacion = forms.CharField( label=_( "¿Qué sugiere Ud. para mejorar la comunicación en la comunidad?"), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique alguna sugerencia para mejorar la comunicación en la comunidad" ), }), required=False) inseguridad = forms.CharField( label=_("¿Qué Inseguridad Presenta la Comunidad?"), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique la inseguridad que presenta la comunidad"), }), required=False) comentario = forms.CharField(label=_( "Algún comentario que desee hacer en relación a las necesidades y soluciones en la comunidad" ), max_length=500, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _( "Indique algún comentario"), }), required=False) observacion = forms.CharField( label=_("Observación:"), widget=forms.Textarea( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'style': 'width:250px;', 'title': _("Indique alguna observación que pueda tener la persona"), }), required=False) """def clean_cedula(self): cedula = self.cleaned_data['cedula'] if cedula == '': return cedula else: if Persona.objects.filter(cedula=cedula): raise forms.ValidationError(_("La Persona ya se encuentra registrada")) return cedula""" def clean(self): cleaned_data = super(PersonaForm, self).clean() grupo_familiar = self.cleaned_data['grupo_familiar'] jefe_familiar = self.cleaned_data['jefe_familiar'] c = 0 if jefe_familiar: for p in Persona.objects.filter(grupo_familiar=grupo_familiar): if p.jefe_familiar: c = c + 1 print(c) if c >= 1: msg = str( _("Solo puede haber un Jefe Familiar por Grupo Familiar.")) self.add_error('jefe_familiar', msg) class Meta: model = Persona exclude = ['grupo_familiar']
import unittest import uuid from . import app_settings from ..compat import is_authenticated, reverse from .adapter import get_adapter from .auth_backends import AuthenticationBackend from .utils import ( filter_users_by_username, url_str_to_user_pk, user_pk_to_url_str, user_username, ) test_username_validators = [ validators.RegexValidator(regex=r'^[a-c]+$', message='not abc', flags=0) ] @override_settings( ACCOUNT_DEFAULT_HTTP_PROTOCOL='https', ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.MANDATORY, ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME, ACCOUNT_SIGNUP_FORM_CLASS=None, ACCOUNT_EMAIL_SUBJECT_PREFIX=None, LOGIN_REDIRECT_URL='/accounts/profile/', ACCOUNT_ADAPTER='allauth.account.adapter.DefaultAccountAdapter', ACCOUNT_USERNAME_REQUIRED=True) class AccountTests(TestCase): def setUp(self): if 'allauth.socialaccount' in settings.INSTALLED_APPS:
class CustomUser(AbstractBaseUser, PermissionsMixin): """ A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional. """ username = models.CharField( _('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'), validators=[ validators.RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username. ' 'This value may contain only letters, numbers ' 'and @/./+/-/_ characters.'), 'invalid'), ], error_messages={ 'unique': _("A user with that username already exists."), }) email = models.EmailField(_('email address'), max_length=254) first_name = models.CharField(_('first name'), max_length=30, blank=False) last_name = models.CharField(_('last name'), max_length=30, blank=False) shot = models.FileField(upload_to='uploads/profile', null=True, blank=True) mobile_number = models.CharField( _('mobile number'), max_length=30, blank=False, help_text=_('Required. digits and +-() only.'), validators=[ validators.RegexValidator(r'^[0-9+()-]+$', _('Enter a valid mobile number.'), 'invalid') ]) # Admin is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the short name for the user." return self.first_name def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email])
MULTIPLE_PREREQUISITES_REGEX_AND = MULTIPLE_PREREQUISITES_REGEX.format( main_operator=AND_OPERATOR, element_regex=ELEMENT_REGEX.format(acronym_regex=ACRONYM_REGEX, secondary_operator=OR_OPERATOR)) PREREQUISITE_SYNTAX_REGEX = r'^(?i)({no_element_regex}|' \ r'{unique_element_regex}|' \ r'{multiple_elements_regex_and}|' \ r'{multiple_elements_regex_or})$'.format( no_element_regex=NO_PREREQUISITE_REGEX, unique_element_regex=UNIQUE_PREREQUISITE_REGEX, multiple_elements_regex_and=MULTIPLE_PREREQUISITES_REGEX_AND, multiple_elements_regex_or=MULTIPLE_PREREQUISITES_REGEX_OR ) mark_safe_lazy = lazy(mark_safe, str) prerequisite_syntax_validator = validators.RegexValidator( regex=PREREQUISITE_SYNTAX_REGEX, message=mark_safe_lazy(_("Prerequisites are invalid"))) class PrerequisiteAdmin(VersionAdmin, OsisModelAdmin): list_display = ('learning_unit_year', 'education_group_year') raw_id_fields = ('learning_unit_year', 'education_group_year') list_filter = ('education_group_year__academic_year', ) search_fields = [ 'learning_unit_year__acronym', 'education_group_year__acronym', 'education_group_year__partial_acronym' ] readonly_fields = ('prerequisite_string', ) class Prerequisite(models.Model):
def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 7) super().__init__(*args, **kwargs) self.validators.append(validators.RegexValidator(r'#[a-f\d]{6}'))
class MyUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username, password and email are required. Other fields are optional. """ username = models.CharField( _('username'), max_length=100, unique=True, help_text=_('Tələb olunur. 75 simvol və ya az. Hərflər, Rəqəmlər və ' '@/./+/-/_ simvollar.'), validators=[ validators.RegexValidator(r'^[\w.@+-]+$', _('Düzgün istifadəçi adı daxil edin.'), 'yanlışdır') ]) first_name = models.CharField(_('first name'), max_length=255, blank=True) last_name = models.CharField(_('last name'), max_length=255, blank=True) email = models.EmailField(_('email address'), max_length=255) profile_picture = models.ImageField( upload_to=get_user_profile_photo_file_name, null=True, blank=True) gender = models.IntegerField(choices=GENDER, verbose_name="cinsi", null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) """ Important non-field stuff """ objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = 'İstifadəçi' verbose_name_plural = 'İstifadəçilər' def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """ Returns the short name for the user. """ return self.first_name def get_avatar(self): if self.profile_picture: try: return "https://graph.facebook.com/%s/picture?type=large" % self.social_auth.get( provider='facebook').uid except: return "https://graph.facebook.com/%s/picture?type=large" % '100002461198950' else: return "https://graph.facebook.com/%s/picture?type=large" % '100002461198950'
__all__ = ("content_name_validator", "validator_token") from django.core import validators from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def content_name_validator(value): if not value.isprintable(): raise ValidationError( _("Contains control characters"), code="control_characters" ) if value: if value[0].isspace() or value[-1].isspace(): raise ValidationError( _("Contains hidden spaces"), code="hidden_spaces" ) validator_token = validators.RegexValidator( r'\A[-a-zA-Z0-9_]+\Z', _("Enter a valid token."), 'invalid_token' )
def __init__(self, *args, **kwargs): regex = kwargs.pop('regex', None) self.validator = validators.RegexValidator(regex=regex) super(RegexValue, self).__init__(*args, **kwargs)
class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( _('username'), max_length=255, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' '/./-/_ characters'), validators=[ validators.RegexValidator(re.compile('^[\w.-]+$'), _('Enter a valid username.'), 'invalid') ]) email = models.EmailField(_('email address'), max_length=255, blank=True, unique=True) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) full_name = models.CharField(_('full name'), max_length=256, blank=True) color = models.CharField(max_length=9, null=False, blank=True, default=generate_random_hex_color, verbose_name=_("color")) bio = models.TextField(null=False, blank=True, default="", verbose_name=_("biography")) photo = models.FileField(upload_to=get_user_file_path, max_length=500, null=True, blank=True, verbose_name=_("photo")) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) lang = models.CharField(max_length=20, null=True, blank=True, default="", verbose_name=_("default language")) timezone = models.CharField(max_length=20, null=True, blank=True, default="", verbose_name=_("default timezone")) colorize_tags = models.BooleanField(null=False, blank=True, default=False, verbose_name=_("colorize tags")) token = models.CharField(max_length=200, null=True, blank=True, default=None, verbose_name=_("token")) email_token = models.CharField(max_length=200, null=True, blank=True, default=None, verbose_name=_("email token")) new_email = models.EmailField(_('new email address'), null=True, blank=True) is_system = models.BooleanField(null=False, blank=False, default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() class Meta: verbose_name = "user" verbose_name_plural = "users" ordering = ["username"] permissions = (("view_user", "Can view user"), ) def __str__(self): return self.get_full_name() def get_short_name(self): "Returns the short name for the user." return self.username def get_full_name(self): return self.full_name or self.username or self.email def save(self, *args, **kwargs): get_token_for_user(self, "cancel_account") super().save(*args, **kwargs) def cancel(self): self.username = slugify_uniquely("deleted-user", User, slugfield="username") self.email = "{}@taiga.io".format(self.username) self.is_active = False self.full_name = "Deleted user" self.color = "" self.bio = "" self.lang = "" self.timezone = "" self.colorize_tags = True self.token = None self.set_unusable_password() self.save() self.auth_data.all().delete()
def value_to_string(self, obj): """Value to string.""" value = self.value_from_object(obj, dump=False) return self.get_db_prep_value(value, None) def value_from_object(self, obj, dump=True): """Value from obect.""" value = super(jsonfield.fields.JSONFieldBase, self).value_from_object(obj) if self.null and value is None: return None return self.dumps_for_display(value) if dump else value _ID_VALIDATOR = validators.RegexValidator( r"^[a-zA-Z]+[0-9a-zA-Z-]*$", "Only alphanumeric characters are allowed.") class Source(models.Model): """A ticket source. This will usually be a filter for a ticket system. """ PLUGINS_CHOICES = ((s, s) for s in settings.MLT_PLUGINS) id = models.CharField(primary_key=True, max_length=64, validators=[_ID_VALIDATOR]) name = models.CharField(max_length=64) description = models.TextField(max_length=1024, blank=True, null=True)
class Migration(migrations.Migration): dependencies = [ ('contenttypes', '__first__'), ] operations = [ migrations.CreateModel( name='Permission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=50, verbose_name='name')), ('content_type', models.ForeignKey(to='contenttypes.ContentType', to_field='id', on_delete=models.CASCADE)), ('codename', models.CharField(max_length=100, verbose_name='codename')), ], options={ 'ordering': ('content_type__app_label', 'content_type__model', 'codename'), 'unique_together': set([('content_type', 'codename')]), 'verbose_name': 'permission', 'verbose_name_plural': 'permissions', }, ), migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=80, verbose_name='name')), ('permissions', models.ManyToManyField(to='auth.Permission', verbose_name='permissions', blank=True)), ], options={ 'verbose_name': 'group', 'verbose_name_plural': 'groups', }, ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=timezone.now, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, max_length=30, verbose_name='username', validators=[validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username.', 'invalid')])), ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), ('email', models.EmailField(max_length=75, verbose_name='email address', blank=True)), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(to='auth.Group', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', related_name='user_set', related_query_name='user')), ('user_permissions', models.ManyToManyField(to='auth.Permission', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user')), ], options={ 'swappable': 'AUTH_USER_MODEL', 'verbose_name': 'user', 'verbose_name_plural': 'users', }, ), ]
class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) # mysql using utf8mb4 supports a max length of 191 name = models.CharField(max_length=30, help_text=('请输入你的姓名.'), validators=[ validators.RegexValidator( r'^[\w]+$', ('请输入合法的姓名 ' '输入英文或中文字符 .'), 'invalid'), ]) choice_sex = ((1, '男'), (2, '女')) gender = models.IntegerField(choices=choice_sex, blank=True, null=True) friend = models.ManyToManyField("self", blank=True, related_name='my_friend') date_of_register = models.DateField(auto_now_add=True) depart = models.ForeignKey(Depart, blank=True, null=True, default=None) orgniza = models.ForeignKey(Orgniza, blank=True, null=True, default=None) position = models.ForeignKey(Position, blank=True, null=True, default=None) univs_attend = models.ManyToManyField(Univs, blank=True, through='UserUnivsAttend', related_name='attend_students') univs_gra = models.ManyToManyField(Univs, blank=True, through='UserUnivsGra', related_name='gra_strudents') message_receiver = models.ManyToManyField("self", blank=True, symmetrical=False, through='UserMessages', related_name='message_sender') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): """Does the user have a specific permission?""" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): """Does the user have permissions to view the app `app_label`?""" # Simplest possible answer: Yes, always return True def get_change_password_url(self): return reverse('change_password', args=[self.id]) @property def is_staff(self): """Is the user a member of staff?""" # Simplest possible answer: All admins are staff return self.is_admin
class Team(models.Model): name = models.CharField( max_length=50, null=True, unique=True, help_text=( 'The name of your team. Must be unique and follow our naming ' 'guidelines.'), validators=[ validators.MinLengthValidator(3), validators.RegexValidator( regex=r'[\x00@#]', message='Name cannot contain @ or #', inverse_match=True, ), UsernameValidator(), ], ) slug = models.SlugField( max_length=50, unique=True, validators=[validators.MinLengthValidator(3)], help_text=( 'Forms part of the URL of your team page, e.g. "your-team" will ' 'give "racetime.gg/team/your-team". Slug must be unique, and can ' 'only use letters, numbers and hyphens. You cannot change this ' 'later.'), ) profile = models.TextField( null=True, blank=True, help_text=( 'Add some information to your team\'s public profile. It can ' 'include anything you like.'), ) formal = models.BooleanField(default=True, ) categories = models.ManyToManyField('Category', ) avatar = models.ImageField( null=True, blank=True, help_text='Recommended size: 100x100. No larger than 100kb.', ) created_at = models.DateTimeField( auto_now_add=True, editable=False, ) updated_at = models.DateTimeField( auto_now=True, editable=False, ) max_owners = models.PositiveIntegerField( default=5, validators=[ validators.MinValueValidator(5), validators.MaxValueValidator(100), ], ) max_members = models.PositiveIntegerField( default=100, validators=[ validators.MinValueValidator(100), validators.MaxValueValidator(1000), ], ) class Meta: ordering = ['name'] @cached_property def all_categories(self): """ Return an ordered QuerySet of active categories this team is involved with. """ return self.categories.filter(active=True).order_by('name') @cached_property def all_owners(self): """ Return an ordered QuerySet of active users who have ownership of this category. """ return self.all_members.filter(owner=True) @cached_property def all_members(self): """ Return an ordered QuerySet of active users who are members of this team. """ return self.teammember_set.filter( invite=False, user__active=True, ).order_by('user__name') @cached_property def invited_members(self): """ Return an ordered QuerySet of active users who have been invited to this team. """ return self.teammember_set.filter( invite=True, user__active=True, ).order_by('user__name') def api_dict_summary(self): """ Return a summary dict of this team's data. """ if self.formal: return { 'name': self.name, 'slug': self.slug, 'formal': True, 'url': self.get_absolute_url(), 'data_url': self.get_data_url(), 'avatar': self.avatar.url if self.avatar else None, } else: return { 'name': self.name, 'slug': self.slug, 'formal': False, } def dump_json_data(self): """ Return team data as a JSON string. """ value = json.dumps( { **self.api_dict_summary(), 'profile': self.profile, 'categories': [ category.api_dict_summary() for category in self.all_categories ], 'members': [{ 'owner': member.owner, **member.user.api_dict_summary(), } for member in self.all_members], }, cls=DjangoJSONEncoder) return value def can_manage(self, user): return user.is_authenticated and (user.is_staff or user in self.all_owners) def get_absolute_url(self): """ Returns the URL of this team's landing page. """ return reverse('team', args=(self.slug, )) def get_data_url(self): """ Returns the URL of this team's data endpoint. """ return reverse('team_data', args=(self.slug, )) def __str__(self): return self.name
class editFicha2(ModelForm): dni = ESIdentityCardNumberField(only_nif=True) phone = forms.CharField( label="Teléfono Móvil", validators=[ validators.RegexValidator( regex="^(\d{4})?(-)?\d{3}(-)?\d{3}(-)?\d{3}$", message="No es un número de teléfono válido") ], widget=forms.TextInput(attrs={'class': 'form-control'}), help_text="Required") photo = forms.ImageField(help_text="Required") date = forms.DateField( label="Fecha de Nacimiento", validators=[ validators.RegexValidator( regex="([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))", message="Formato de fecha inválido"), ], widget=forms.SelectDateWidget(attrs={ 'placeholder': 'AAAA-MM-DD', 'class': 'form-control' }, years=range(1940, year)), help_text="Required") country = forms.ChoiceField(label="País", choices=Country_choices, widget=forms.Select(attrs={ 'class': 'country_form', 'placeholder': 'País' }), help_text="Required") weight = forms.IntegerField( label="Peso (kg)", validators=[ validators.RegexValidator("[0-9]", message="Formato erróneo en el peso"), validators.MaxValueValidator(limit_value=250, message="Valor de peso no realista"), validators.MinValueValidator(limit_value=20, message="Valor de peso no realista"), ], widget=forms.TextInput(attrs={ 'class': 'form_control', 'placeholder': 'Peso' }), help_text="Required") height = forms.IntegerField( label="Altura (cm)", validators=[ validators.RegexValidator("[0-9]", message="Formato de altura no realista"), validators.MaxValueValidator( limit_value=250, message="Valor de altura no realista"), validators.MinValueValidator( limit_value=20, message="Valor de altura no realista"), ], widget=forms.NumberInput(attrs={ 'class': 'form_control', 'placeholder': 'Altura' }), help_text="Required") somatotipe = forms.ChoiceField( label="Somatotipo", choices=somatotipe_choices, widget=forms.Select(attrs={'class': 'form_control'}), help_text="Required") gender = forms.ChoiceField(label="Género", choices=gender_choices, help_text="Required") timing = forms.CharField(label="Horarios", widget=forms.Textarea, help_text="Required") meals = forms.CharField(label="Comidas", widget=forms.Textarea, help_text="Required") sports = forms.CharField(label="Deportes", widget=forms.Textarea, help_text="Required") comments = forms.CharField(label="Comentarios Adicionales", widget=forms.Textarea, help_text="Required") patologies = forms.CharField(label="Patologías", widget=forms.Textarea, help_text="Required") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Record fields = [ 'dni', 'phone', 'photo', 'date', 'country', 'weight', 'height', 'somatotipe', 'gender', 'timing', 'meals', 'patologies', 'sports', 'comments', 'plan' ]
class GaeAbstractBaseUser(AbstractBaseUser): """ Absract base class for creating a User model which works with the App Engine users API. """ username = models.CharField( # This stores the Google user_id, or custom username for non-Google-based users. # We allow it to be null so that Google-based users can be pre-created before they log in. _('User ID'), max_length=21, unique=True, null=True, default=None, validators=[ validators.RegexValidator(re.compile('^\d{21}$'), _('User Id should be 21 digits.'), 'invalid') ]) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) # The null-able-ness of the email is only to deal with when an email address moves between Google Accounts email = models.EmailField(_('email address'), unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = GaeUserManager() class Meta: abstract = True def get_absolute_url(self): return "/users/%s/" % urlquote(self.username) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the short name for the user." return self.first_name def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email]) def __str__(self): """ We have to override this as username is nullable. We either return the email address, or if there is a username, we return "email (username)". """ username = self.get_username() if username: return "{} ({})".format(six.text_type(self.email), six.text_type(username)) return six.text_type(self.email)
class PaymentForm(forms.Form): """Form to collect details required for payment billing.""" CC_MONTHS = ( ('1', '01 - January'), ('2', '02 - February'), ('3', '03 - March'), ('4', '04 - April'), ('5', '05 - May'), ('6', '06 - June'), ('7', '07 - July'), ('8', '08 - August'), ('9', '09 - September'), ('10', '10 - October'), ('11', '11 - November'), ('12', '12 - December'), ) CC_YEARS = assemble_cc_years() cardholder_name = forms.CharField( label='Cardholder name', max_length=255, min_length=1, ) card_number = forms.CharField(label='Card number', max_length=19, min_length=13, validators=[ validators.RegexValidator( r'^\d{13,19}$', message='Invalid credit card number', ) ]) card_expiry_month = forms.ChoiceField( choices=CC_MONTHS, label='Card expiry (month)', ) card_expiry_year = forms.ChoiceField( choices=CC_YEARS, label='Card expiry (year)', ) card_cvv = forms.CharField(label='Card CVV', max_length=4, min_length=3, validators=[ validators.RegexValidator( r'^\d{3,4}$', message='Invalid CVV2 number', ) ]) address_title = forms.CharField( label='Title', max_length=32, required=False, ) address_name = forms.CharField( label='Name', max_length=128, ) address_line_1 = forms.CharField( label='Line 1', max_length=256, ) address_line_2 = forms.CharField( label='Line 2', max_length=256, required=False, ) address_line_3 = forms.CharField( label='Line 3', max_length=256, required=False, ) address_city = forms.CharField( label='City', max_length=128, min_length=1, ) address_province = forms.CharField( label='Province/State', max_length=128, min_length=1, ) address_postcode = forms.CharField( label='Postcode', max_length=16, required=False, ) address_country = forms.CharField( label='Country', max_length=128, min_length=1, )
class ConfigureForm(forms.Form): """Form to configure the Dynamic DNS client.""" help_update_url = \ ugettext_lazy('The Variables <User>, <Pass>, <Ip>, ' '<Domain> may be used within the URL. For details ' 'see the update URL templates of the example providers.') help_services = \ ugettext_lazy('Please choose an update protocol according to your ' 'provider. If your provider does not support the GnuDIP ' 'protocol or your provider is not listed you may use ' 'the update URL of your provider.') help_server = \ ugettext_lazy('Please do not enter a URL here (like ' '"https://example.com/") but only the hostname of the ' 'GnuDIP server (like "example.com").') help_domain = format_lazy(ugettext_lazy( 'The public domain name you want to use to reach your ' '{box_name}.'), box_name=ugettext_lazy(cfg.box_name)) help_disable_ssl = \ ugettext_lazy('Use this option if your provider uses self signed ' 'certificates.') help_http_auth = \ ugettext_lazy('If this option is selected, your username and password ' 'will be used for HTTP basic authentication.') help_secret = \ ugettext_lazy('Leave this field empty if you want to keep your ' 'current password.') help_ip_url = format_lazy(ugettext_lazy( 'Optional Value. If your {box_name} is not connected ' 'directly to the Internet (i.e. connected to a NAT ' 'router) this URL is used to determine the real ' 'IP address. The URL should simply return the IP where ' 'the client comes from (example: ' 'http://myip.datasystems24.de).'), box_name=ugettext_lazy(cfg.box_name)) help_user = \ ugettext_lazy('The username that was used when the account was ' 'created.') provider_choices = (('GnuDIP', ugettext_lazy('GnuDIP')), ('noip', 'noip.com'), ('selfhost', 'selfhost.bz'), ('freedns', 'freedns.afraid.org'), ('other', ugettext_lazy('other update URL'))) enabled = forms.BooleanField(label=ugettext_lazy('Enable Dynamic DNS'), required=False) service_type = forms.ChoiceField(label=ugettext_lazy('Service Type'), help_text=help_services, choices=provider_choices) dynamicdns_server = TrimmedCharField( label=ugettext_lazy('GnuDIP Server Address'), required=False, help_text=help_server, validators=[ validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$', ugettext_lazy('Invalid server name')) ]) dynamicdns_update_url = TrimmedCharField(label=ugettext_lazy('Update URL'), required=False, help_text=help_update_url) disable_SSL_cert_check = forms.BooleanField( label=ugettext_lazy('Accept all SSL certificates'), help_text=help_disable_ssl, required=False) use_http_basic_auth = forms.BooleanField( label=ugettext_lazy('Use HTTP basic authentication'), help_text=help_http_auth, required=False) dynamicdns_domain = TrimmedCharField( label=ugettext_lazy('Domain Name'), help_text=help_domain, required=False, validators=[ validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$', ugettext_lazy('Invalid domain name')) ]) dynamicdns_user = TrimmedCharField(label=ugettext_lazy('Username'), required=False, help_text=help_user) dynamicdns_secret = TrimmedCharField(label=ugettext_lazy('Password'), widget=forms.PasswordInput(), required=False, help_text=help_secret) showpw = forms.BooleanField(label=ugettext_lazy('Show password'), required=False) dynamicdns_ipurl = TrimmedCharField( label=ugettext_lazy('URL to look up public IP'), required=False, help_text=help_ip_url, validators=[validators.URLValidator(schemes=['http', 'https', 'ftp'])]) def clean(self): cleaned_data = super(ConfigureForm, self).clean() dynamicdns_secret = cleaned_data.get('dynamicdns_secret') dynamicdns_update_url = cleaned_data.get('dynamicdns_update_url') dynamicdns_user = cleaned_data.get('dynamicdns_user') dynamicdns_domain = cleaned_data.get('dynamicdns_domain') dynamicdns_server = cleaned_data.get('dynamicdns_server') service_type = cleaned_data.get('service_type') old_dynamicdns_secret = self.initial['dynamicdns_secret'] # Clear the fields which are not in use if service_type == 'GnuDIP': dynamicdns_update_url = '' else: dynamicdns_server = '' if cleaned_data.get('enabled'): # Check if gnudip server or update URL is filled if not dynamicdns_update_url and not dynamicdns_server: raise forms.ValidationError( _('Please provide an update URL or a GnuDIP server ' 'address')) if dynamicdns_server and not dynamicdns_user: raise forms.ValidationError( _('Please provide a GnuDIP username')) if dynamicdns_server and not dynamicdns_domain: raise forms.ValidationError( _('Please provide a GnuDIP domain name')) # Check if a password was set before or a password is set now if dynamicdns_server and \ not dynamicdns_secret and not old_dynamicdns_secret: raise forms.ValidationError(_('Please provide a password'))
class ProfileForm(forms.ModelForm): """! Clase que contiene los campos del formulario de perfil del usuario @author William Páez (paez.william8 at gmail.com) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> """ ## Username para identificar al usuario, en este caso se usa la cédula username = IdentityCardField(validators=[ validators.RegexValidator( r'^[VE][\d]{8}$', _('Introduzca un número de cédula válido. Solo se permiten números y una longitud de 8 carácteres. Se agregan ceros (0) si la longitud es de 7 o menos caracteres.' )), ], help_text=_('V00000000 ó E00000000')) ## Nombres del usuario first_name = forms.CharField(label=_('Nombres:'), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'title': _('Indique los Nombres.'), })) ## Apellidos del usuario last_name = forms.CharField(label=_('Apellidos:'), max_length=100, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'title': _('Indique los Apellidos.'), })) ## Correo del usuario email = forms.EmailField( label=_('Correo Electrónico:'), max_length=100, widget=forms.EmailInput( attrs={ 'class': 'form-control input-sm email-mask', 'data-toggle': 'tooltip', 'title': _('Indique el correo electrónico de contacto.') })) ## Teléfono del usuario phone = forms.CharField( label=_('Teléfono:'), max_length=15, widget=forms.TextInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'title': _('Indique el número telefónico de contacto.'), 'data-mask': '+00-000-0000000' }), validators=[ validators.RegexValidator( r'^\+\d{2}-\d{3}-\d{7}$', _('Número telefónico inválido. Solo se permiten números y los símbolos: + -' )), ], help_text=_('+58-416-0000000')) ## Clave de acceso del usuario password = forms.CharField( label=_('Contraseña:'), max_length=128, widget=forms.PasswordInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'title': _('Indique una contraseña de aceso al sistema.') })) ## Confirmación de clave de acceso del usuario confirm_password = forms.CharField( label=_('Confirmar Contraseña:'), max_length=128, widget=forms.PasswordInput( attrs={ 'class': 'form-control input-sm', 'data-toggle': 'tooltip', 'title': _( 'Indique nuevamente la contraseña de aceso al sistema.') })) def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email): raise forms.ValidationError(_('El correo ya esta registrado.')) return email def clean_confirm_password(self): confirm_password = self.cleaned_data['confirm_password'] password = self.cleaned_data.get('password') if password != confirm_password: raise forms.ValidationError(_('La contraseña no es la misma.')) return confirm_password class Meta: """! Meta clase del formulario que establece algunas propiedades @author William Páez (paez.william8 at gmail.com) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> """ model = User exclude = ['profile', 'level', 'date_joined']
class KolibriAbstractBaseUser(AbstractBaseUser): """ Our custom user type, derived from ``AbstractBaseUser`` as described in the Django docs. Draws liberally from ``django.contrib.auth.AbstractUser``, except we exclude some fields we don't care about, like email. This model is an abstract model, and is inherited by both ``FacilityUser`` and ``DeviceOwner``. """ class Meta: abstract = True USERNAME_FIELD = "username" username = models.CharField( _('username'), max_length=30, help_text=_( 'Required. 30 characters or fewer. Letters and digits only'), validators=[ validators.RegexValidator( r'^\w+$', _('Enter a valid username. This value may contain only letters and numbers.' )), ], ) full_name = models.CharField(_('full name'), max_length=120, blank=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now, editable=False) def get_short_name(self): return self.full_name.split(' ', 1)[0] def is_member_of(self, coll): """ Determine whether this user is a member of the specified ``Collection``. :param coll: The ``Collection`` for which we are checking this user's membership. :return: ``True`` if this user is a member of the specified ``Collection``, otherwise False. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `is_member_of` method." ) def get_roles_for_user(self, user): """ Determine all the roles this user has in relation to the target user, and return a set containing the kinds of roles. :param user: The target user for which this user has the roles. :return: The kinds of roles this user has with respect to the target user. :rtype: set of ``kolibri.auth.constants.role_kinds.*`` strings """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `get_roles_for_user` method." ) def get_roles_for_collection(self, coll): """ Determine all the roles this user has in relation to the specified ``Collection``, and return a set containing the kinds of roles. :param coll: The target ``Collection`` for which this user has the roles. :return: The kinds of roles this user has with respect to the specified ``Collection``. :rtype: set of ``kolibri.auth.constants.role_kinds.*`` strings """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `get_roles_for_collection` method." ) def has_role_for_user(self, kinds, user): """ Determine whether this user has (at least one of) the specified role kind(s) in relation to the specified user. :param user: The user that is the target of the role (for which this user has the roles). :param kinds: The kind (or kinds) of role to check for, as a string or iterable. :type kinds: string from ``kolibri.auth.constants.role_kinds.*`` :return: ``True`` if this user has the specified role kind with respect to the target user, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `has_role_for_user` method." ) def has_role_for_collection(self, kinds, coll): """ Determine whether this user has (at least one of) the specified role kind(s) in relation to the specified ``Collection``. :param kinds: The kind (or kinds) of role to check for, as a string or iterable. :type kinds: string from kolibri.auth.constants.role_kinds.* :param coll: The target ``Collection`` for which this user has the roles. :return: ``True`` if this user has the specified role kind with respect to the target ``Collection``, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `has_role_for_collection` method." ) def can_create_instance(self, obj): """ Checks whether this user (self) has permission to create a particular model instance (obj). This method should be overridden by classes that inherit from ``KolibriAbstractBaseUser``. In general, unless an instance has already been initialized, this method should not be called directly; instead, it should be preferred to call ``can_create``. :param obj: An (unsaved) instance of a Django model, to check permissions for. :return: ``True`` if this user should have permission to create the object, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `can_create_instance` method." ) def can_create(self, Model, data): """ Checks whether this user (self) has permission to create an instance of Model with the specified attributes (data). This method defers to the ``can_create_instance`` method, and in most cases should not itself be overridden. :param Model: A subclass of ``django.db.models.Model`` :param data: A ``dict`` of data to be used in creating an instance of the Model :return: ``True`` if this user should have permission to create an instance of Model with the specified data, else ``False``. :rtype: bool """ try: instance = Model(**data) instance.clean_fields() instance.clean() except TypeError as e: logging.error( "TypeError while validating model before checking permissions: {}" .format(e.args)) return False # if the data provided does not fit the Model, don't continue checking except ValidationError as e: logging.error( "ValidationError while validating model before checking permissions: {}" .format(e.args)) return False # if the data does not validate, don't continue checking # now that we have an instance, defer to the permission-checking method that works with instances return self.can_create_instance(instance) def can_read(self, obj): """ Checks whether this user (self) has permission to read a particular model instance (obj). This method should be overridden by classes that inherit from ``KolibriAbstractBaseUser``. :param obj: An instance of a Django model, to check permissions for. :return: ``True`` if this user should have permission to read the object, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `can_read` method." ) def can_update(self, obj): """ Checks whether this user (self) has permission to update a particular model instance (obj). This method should be overridden by classes that inherit from KolibriAbstractBaseUser. :param obj: An instance of a Django model, to check permissions for. :return: ``True`` if this user should have permission to update the object, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `can_update` method." ) def can_delete(self, obj): """ Checks whether this user (self) has permission to delete a particular model instance (obj). This method should be overridden by classes that inherit from KolibriAbstractBaseUser. :param obj: An instance of a Django model, to check permissions for. :return: ``True`` if this user should have permission to delete the object, otherwise ``False``. :rtype: bool """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `can_delete` method." ) def get_roles_for(self, obj): """ Helper function that defers to ``get_roles_for_user`` or ``get_roles_for_collection`` based on the type of object passed in. """ if isinstance(obj, KolibriAbstractBaseUser): return self.get_roles_for_user(obj) elif isinstance(obj, Collection): return self.get_roles_for_collection(obj) else: raise ValueError( "The `obj` argument to `get_roles_for` must be either an instance of KolibriAbstractBaseUser or Collection." ) def has_role_for(self, kinds, obj): """ Helper function that defers to ``has_role_for_user`` or ``has_role_for_collection`` based on the type of object passed in. """ if isinstance(obj, KolibriAbstractBaseUser): return self.has_role_for_user(kinds, obj) elif isinstance(obj, Collection): return self.has_role_for_collection(kinds, obj) else: raise ValueError( "The `obj` argument to `has_role_for` must be either an instance of KolibriAbstractBaseUser or Collection." ) def filter_readable(self, queryset): """ Filters a queryset down to only the elements that this user should have permission to read. :param queryset: A ``QuerySet`` instance that the filtering should be applied to. :return: Filtered ``QuerySet`` including only elements that are readable by this user. """ raise NotImplementedError( "Subclasses of KolibriAbstractBaseUser must override the `can_delete` method." )
class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): username = models.CharField( _('username'), max_length=60, unique=True, help_text=_( 'Required. 60 characters or fewer. Letters, digits, spaces and ' '@/./+/-/_ only.'), validators=[ validators.RegexValidator(USERNAME_REGEX, USERNAME_INVALID_MESSAGE, 'invalid') ], error_messages={ 'unique': _('A user with that username already exists.') }) email = models.EmailField( _('Email address'), unique=True, error_messages={ 'unique': _('A user with that email address already exists.') }) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(editable=False, default=timezone.now) get_notifications = models.BooleanField( verbose_name=_('Send me email notifications'), default=True, help_text=_('Designates whether you want to receive notifications. ' 'Unselect if you do not want to receive notifications.')) get_newsletters = models.BooleanField( verbose_name=_('I would like to receive further information'), default=False, help_text=_('Projects you are following can send you ' 'additional information via email.')) bio = models.TextField( blank=True, max_length=255, verbose_name=_('Biography'), help_text=_('Tell us about yourself in 255 characters!')) twitter_handle = models.CharField( blank=True, max_length=15, verbose_name=_('Twitter handle'), ) facebook_handle = models.CharField( blank=True, max_length=50, verbose_name=_('Facebook name'), help_text=_('Your facebook name is the last part of the URL, ' 'when you access your profile.')) homepage = models.URLField( blank=True, max_length=50, verbose_name=_('Homepage'), ) _avatar = ConfiguredImageField( 'avatar', upload_to='users/images', blank=True, verbose_name=_('Avatar picture'), ) language = models.CharField( verbose_name=_('Your preferred language'), choices=settings.LANGUAGES, default=settings.DEFAULT_USER_LANGUAGE_CODE, max_length=4, help_text=_('Specify your preferred language for the user interface ' 'and the notifications of the platform.'), ) objects = auth_models.UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] @cached_property def organisations(self): return self.organisation_set.all() @cached_property def avatar(self): if self._avatar: return self._avatar @cached_property def avatar_fallback(self): number = self.pk % 5 return static('images/avatar-{0:02d}.svg'.format(number)) def get_short_name(self): return self.username def get_full_name(self): full_name = '%s <%s>' % (self.username, self.email) return full_name.strip() def get_absolute_url(self): return reverse('profile', args=[str(self.username)])
class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( 'Nome de usuário:', max_length = 30, unique = True, validators = [ validators.RegexValidator(re.compile('^[\w.@+-]+$'), 'Nome de usuário inválido!', 'invalid') ] ) email = models.EmailField( 'Email:', unique = True ) name = models.CharField( 'Nome completo:', max_length = 100, blank = True ) is_active = models.BooleanField( 'Status:', blank = True, default = True ) is_staff = models.BooleanField( 'Permissao:', blank = True, default = False ) date_joined = models.DateTimeField( 'Data:', auto_now_add = True ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.name or self.username def get_short_name(self): return self.username def get_full_name(self): return str(self) class Meta: verbose_name = 'Usuário' verbose_name_plural = 'Usuários'