class CopyrightSearchForm(Form): form_buttons = Submit(value='search files') c = RadioSelectField( name='fc', id='fc', choices=SEARCH_CHOICES, default='0', label=_('Having Copyright'), html_attrs={'_class': 'radio inline'}, ) ci = RadioSelectField( name='fci', id='fci', choices=SEARCH_CHOICES, default='0', label=_('Copyright Inhouse'), html_attrs={'_class': 'radio inline'}, ) cg = RadioSelectField( name='fcg', id='fcg', choices=SEARCH_CHOICES, default='0', label=_('Copyright GPL'), html_attrs={'_class': 'radio inline'}, ) co = RadioSelectField( name='fco', id='fco', choices=SEARCH_CHOICES, default='0', label=_('Copyright Other Opensource'), html_attrs={'_class': 'radio inline'}, )
def authenticate(username, password): """ ldap authenticate using username/password """ if not settings.LDAP.user_case_sensitive: username = username.lower() ldap_auth_ok, attr_dict = ldapauth_handler.login(username=username, password=password) if not ldap_auth_ok: from uliweb import request log.error("user '%s' fail to login for ldap, try login from '%s'" % (username, request.environ['REMOTE_ADDR'])) return False, { 'password': _('LDAP error:user does not exist or password is not correct!') } try: user = _sync_ldap_user(username, attr_dict) if user.deleted: return False, { 'username': _('User "%s" has been deleted!') % username } except UserNotFoundError as err: from uliweb import request log.error("user '%s' not found, try login from '%s'" % (username, request.environ['REMOTE_ADDR'])) return False, {'username': _('User "%s" does not existed!') % username} log.info("user '%s' login successfully" % (username)) return True, user
def view(self): id_ = request.values.get("id") if not id_: error(_('No permission id')) role = "ADMIN" tconfig = functions.get_apijson_table(role, "permissions") Permission = models.permission Role = models.role perm = Permission.get(id_) if not perm: error(_('Permission "%s" not found' % (id_))) roles = [i for i in perm.perm_roles.all()] init_roles = [i.id for i in roles] init_role_labels = [i.name for i in roles] return { "request_tag": "permission", "id_": id_, "tconfig_json": json_dumps(tconfig), "role": role, "init_roles": json_dumps(init_roles), "init_role_labels": json_dumps(init_role_labels), }
def edit(self, id): """ Edit the role """ from uliweb.utils.generic import EditView from uliweb.orm import get_model obj = self.model.get(int(id)) # def get_form_field(name, obj): # from uliweb.form import SelectField # # if name == 'users': # choices = [(x.id, x.username) for x in obj.users.all()] # return SelectField('用户', name=name, choices=choices, # multiple=True, html_attrs={'url':'/config/users/search'}, # datatype=int) fields = [ { 'name': 'name', 'verbose_name': _('Name') }, { 'name': 'description', 'verbose_name': _('Description') }, ] view = EditView(self.model, url_for(PermissionView.view, id=int(id)), obj=obj, fields=fields) return view.run()
def edit(self, id): """ Edit the role """ from uliweb.utils.generic import EditView from uliweb.orm import get_model obj = self.model.get(int(id)) fields = [ { 'name': 'name', 'verbose_name': _('Name') }, { 'name': 'description', 'verbose_name': _('Description') }, { 'name': 'reserve', 'verbose_name': _('Is Reserved') }, ] view = EditView(self.model, url_for(RoleView.view, id=int(id)), obj=obj, fields=fields) return view.run()
def add(self): """ Add new role """ from uliweb.utils.generic import AddView from functools import partial url = partial(url_for, RoleView.view) default_data = {'reverse': False} fields = [ { 'name': 'name', 'verbose_name': _('Name') }, { 'name': 'description', 'verbose_name': _('Description') }, ] view = AddView(self.model, url, default_data=default_data, fields=fields) return view.run()
def view(self, id): """ Role display """ from uliweb.utils.generic import DetailView fields = [ { 'name': 'name', 'verbose_name': _('Name') }, { 'name': 'description', 'verbose_name': _('Description') }, { 'name': 'reserve', 'verbose_name': _('Is Reserved') }, ] obj = self.model.get(int(id)) view = DetailView(self.model, obj=obj, fields=fields) return view.run()
def to_python(self, data): for format in self.formats: try: return datetime.datetime(*time.strptime(data, format)[:6]) except ValueError: continue raise Exception, _("The datetime is not a valid datetime format.")
def edit(self, id): """ Edit the role """ from uliweb.utils.generic import EditView from uliweb.orm import get_model obj = self.model.get(int(id)) # def get_form_field(name, obj): # from uliweb.form import SelectField # # if name == 'users': # choices = [(x.id, x.username) for x in obj.users.all()] # return SelectField('用户', name=name, choices=choices, # multiple=True, html_attrs={'url':'/config/users/search'}, # datatype=int) fields = [ {'name':'name', 'verbose_name':_('Name')}, {'name':'description', 'verbose_name':_('Description')}, ] view = EditView(self.model, url_for(PermissionView.view, id=int(id)), obj=obj, fields=fields) return view.run()
def login(): from uliweb.contrib.auth import authenticate, login from forms import LoginForm from uliweb.form import Submit, Tag LoginForm.form_buttons = [Submit(value=_('Login'), _class="button")] form = LoginForm() if request.method == 'GET': form.next.data = request.GET.get('next', '/') return {'form':form, 'msg':''} if request.method == 'POST': flag = form.validate(request.params) if flag: f, d = authenticate(username=form.username.data, password=form.password.data) if f: request.session.remember = form.rememberme.data login(form.username.data) next = request.POST.get('next', '/') return redirect(next) else: data = d msg = form.errors.get('_', '') or _('Login failed!') return {'form':form, 'msg':str(msg)}
class ChangeInfoForm(Form): form_buttons = Submit(value=_('Save'), _class="submit") form_title = _('Change Basic Information') email = StringField(label=_('Email:')) image = ImageField(label=_('Portrait:')) action = HiddenField(default='changeinfo')
class ChangePasswordForm2(Form): form_buttons = Button(value=_('Save'), _class="btn btn-primary", type="submit") username = StringField(label=_('Username:'******'Old Password:'******'Password:'******'Password again:'), required=True) def form_validate(self, all_data): from uliweb.orm import get_model error = {} User = get_model('user') user = User.get(User.c.username == data) if not user: raise ValidationError(_('Username is not existed.')) if not request.user.check_password(all_data.oldpassword): error['oldpassword'] = _('Password is not right.') if all_data.password != all_data.password1: error['password1'] = _( 'Passwords are not the same between two types.') return error
class UserGroup(Model): name = Field(str, max_length=128, verbose_name=_('Name'), index=True, nullable=True) parent = SelfReference(verbose_name=_('Parent Group'), collection_name='children', nullable=True, default=0) users = ManyToMany('user', verbose_name=_('Users'), collection_name='groups') deleted = Field(bool, verbose_name=_('Deleted')) created_time = Field(datetime.datetime, verbose_name=_('Created Datetime'), auto_now_add=True) number_of_children = Field(int, verbose_name=_('Number of Children')) number_of_people = Field(int, verbose_name=_('Number of People')) order = Field(int, verbose_name=_('Order'), default=9999) type = Field(CHAR, max_length=1, verbose_name=_('Group Type'), choices=get_var('AUTH/USER_GROUP_TYPE')) auth_type = Field(int, default=get_var('AUTH/AUTH_TYPE_DEFAULT'), verbose_name=_('Auth type')) def __unicode__(self): return self.name @classmethod def OnInit(cls): Index('usergroup_idx', cls.c.parent, cls.c.name)
def authenticate(username, password, auth_type=None): from uliweb import settings, request auth_type = auth_type or settings.AUTH.AUTH_DEFAULT_TYPE errors = {} if not isinstance(auth_type, (list, tuple)): auth_type = [auth_type] ip = request.environ['REMOTE_ADDR'] for t in auth_type: if t in settings.AUTH_CONFIG: func_path = settings.AUTH_CONFIG[t].get('authenticate') if func_path: func = import_attr(func_path) f, d = func(username, password) if f: if hasattr(d,"locked") and d.locked: log.error("'%s' fail to login, err: user '%s' is locked"%(ip, d)) return False, {'username': _('"{}" is locked!').format(username)} if hasattr(d,"deleted") and d.deleted: log.error("'%s' fail to login, err: user '%s' is deleted"%(ip, d)) return False, {'username': _('"{}" is deleted!').format(username)} log.info("'%s' login successfully as user '%s', auth_type: %s"%(ip, username, t)) return f, d else: log.error("'%s' fail to login, auth_type: %s, err: %s"%(ip, t, d)) errors = d else: log.error("auth_type %s not in config"%(t)) return False, errors
def _get_title(self, action, obj=None): name = getattr(self.model, '__verbose_name__', '') if action == 'add': return _("Add") + safe_unicode(name) elif action == 'edit': return _("Edit") + safe_unicode(name) elif action == 'view': return _("View") + safe_unicode(name)
class LoginForm(Form): form_buttons = Submit(value=_('Login'), _class="btn btn-primary") # form_title = _('Login') username = UnicodeField(label=_('Username'), required=True) password = PasswordField(label=_('Password'), required=True) rememberme = BooleanField(label=_('Remember Me')) next = HiddenField()
class ReleaseForm(Form): release = BooleanField(name='release_bool', id='release_bool', label=_('Release this package')) rnote = TextField(label=_('release note'), name='rnote', id='rnote', rows="6")
def form_validate(self, all_data): from uliweb import settings from uliweb.orm import get_model User = get_model('user') user = User.get(User.c.username==all_data['username']) if not user: return {'username': _('User "%s" is not existed!') % all_data['username']} if not user.check_password(all_data['password']): return {'password' : _('Password is not right.')}
def form_validate(self, all_data): from uliweb import request error = {} if not request.user.check_password(all_data.oldpassword): error['oldpassword'] = _('Password is not right.') if all_data.password != all_data.password1: error['password1'] = _('Passwords are not the same between two types.') return error
def form_validate(self, all_data): from uliweb import request error = {} if not request.user.check_password(all_data.oldpassword): error['oldpassword'] = _('Password is not right.') if all_data.password != all_data.password1: error['password1'] = _( 'Passwords are not the same between two types.') return error
def f(data): import Image try: try: image = Image.open(data.file) if size: if image.size[0]>size[0] or image.size[1]>size[1]: return _("The image file size exceeds the limit.") except Exception, e: return _("The file is not a valid image.") finally: data.file.seek(0)
def f(data): import Image try: try: image = Image.open(data.file) if size: if image.size[0] > size[0] or image.size[1] > size[1]: return _("The image file size exceeds the limit.") except Exception, e: return _("The file is not a valid image.") finally: data.file.seek(0)
def _check_permission(self, perm, acl=None, user=None, page=None, err_msg=_("You have no right to access the page."), raise_exception=True): from uliweb.orm import Model if not user: user = request.user #superuser can do everything if user and user.is_superuser: return True if not user: err_msg = _("You are not logged in. ") + err_msg if isinstance(acl, Model): acl = acl.acl else: acl = acl if page: pagename = page.name else: pagename = '' result, _perms = self._find_permissions(perm, acl, user, check_default=False, pagename=pagename) while _perms: if page: parent = page.get_parent() if parent: _result, _perms = self._find_permissions(_perms, parent.acl, user, check_default=False, pagename=page.name) result.update(_result) page = parent if not _perms: break else: _result, _perms = self._find_permissions(_perms, None, user) result.update(_result) break else: _result, _perms = self._find_permissions(_perms, None, user) result.update(_result) break if user: log.debug('check permission perm=%s, user=%s, result=%r', perm, user.username, result) else: log.debug('check permission perm=%s, result=%r', perm, result) if not result.get(perm, False): if raise_exception: error(err_msg) else: return False return True
def default_authenticate(username, password): User = get_model("user") if isinstance(username, (str, unicode)): user = User.get(User.c.username == username) else: user = username if user: if user.check_password(password): return True, user else: return False, {"password": _("Password isn't correct!")} else: return False, {"username": _('"{}" is not existed!').format(username)}
class CheckLoginForm(Form): ''' form for use verification code ''' form_buttons = Submit(value=_('Login'), _class="btn btn-primary") username = UnicodeField(label=_('Username'), required=True) password = PasswordField(label=_('Password'), required=True) verification_code = VerificationCodeInputField( label=_('Verification Code'), required=True) verification_img = VerificationCodeField() rememberme = BooleanField(label=_('Remember Me')) next = HiddenField()
def default_authenticate(username, password): User = get_model('user') if isinstance(username, (str, unicode)): user = User.get(User.c.username==username) else: user = username if user: if user.check_password(password): return True, user else: return False, {'password': _("Password isn't correct!")} else: return False, {'username': _('Username is not existed!')}
def default_authenticate(username, password): User = get_model('user') if isinstance(username, (str, unicode)): user = User.get(User.c.username == username) else: user = username if user: if user.check_password(password): return True, user else: return False, {'password': _("Password isn't correct!")} else: return False, {'username': _('Username is not existed!')}
def validate_username(self, data): from uliweb.orm import get_model if any((x in data for x in '<>& ')): return _("Username can't include illegal characters, such as '<>&' and blank.") if not r_username.match(data): return _("Username can only include letter, number and '._/'.") User = get_model('user') user = User.get((User.c.username == data) & (User.c.id != self.object.id)) if user: return _('Username is already existed.')
def action(value, obj): from uliweb.core.html import Tag actions = [ Tag('a', '<i class="fa fa-eye"></i>', title=_('查看'), href=url_for(self.__class__.view, sheet_id=obj.id), _class="btn btn-xs btn-flat btn-primary"), Tag('a', '<i class="fa fa-remove"></i>', title=_('删除'), href=url_for(self.__class__.delete, sheet_id=obj.id), _class="btn btn-xs btn-flat btn-danger action-delete"), ] return ' '.join(map(str, actions))
def default_authenticate(username, password): User = get_model('user') if isinstance(username, string_types): user = User.get(User.c.username==username) else: user = username if user: if user.check_password(password): return True, user else: return False, {'password': _("Username or password isn't correct!")} else: return False, {'password': _("Username or password isn't correct!")}
def authenticate(username, password): from ldap_login import ldapauth_handler if not settings.LDAP.user_case_sensitive: username = username.lower() ldap_auth_ok, ldap_dict = ldapauth_handler.login(**{'username':username,'password':password}) if not ldap_auth_ok: return False,{'password' : _('LDAP error:user does not exist or password is not correct!')} User = get_model('user') user = User.get(User.c.username==username) if not user: if settings.LDAP.user_auto_create: user = User(username=username, password="") user.set_password("") user.save() else: return False,{'username': _('User "%s" does not existed!') % username} class cresult: pass cresult.changed = False #update user info def update_user_with_ldap_attr(setting_attrname,user_attrname): attrname = settings.LDAP.auth.get(setting_attrname,None) if attrname: attr = ldap_dict.get(attrname,None) if attr: if type(attr)==type([]): attr = attr[0] setattr(user,user_attrname,attr) cresult.changed = True update_user_with_ldap_attr('aliasname_attribute','nickname') update_user_with_ldap_attr('email_attribute','email') #sync groups if settings.LDAP.sync_user_groups: attrname = settings.LDAP.auth.get("memberof_attribute",None) if attrname: memberof = ldap_dict.get(attrname,None) if memberof: gnames = [] for i in memberof: try: gname = i.split(",")[0].split("=")[1] gnames.append(gname) except IndexError,e: logging.error("error when handle memberOf( %s ): %s"%(i,e)) update_user_groups(user,gnames)
class UserGroup(Model): name = Field(str, max_length=30, verbose_name=_('Name'), index=True, nullable=True) parent = SelfReference(verbose_name=_('Parent Group'), collection_name='children', nullable=True, default=0) users = ManyToMany('user', verbose_name=_('Users'), collection_name='groups') deleted = Field(bool, verbose_name=_('Deleted')) created_time = Field(datetime.datetime, verbose_name=_('Created Datetime'), auto_now_add=True) number_of_children = Field(int, verbose_name=_('Number of Children')) number_of_people = Field(int, verbose_name=_('Number of People')) order = Field(int, verbose_name=_('Order'), default=9999) def __unicode__(self): return self.name @classmethod def OnInit(cls): Index('usergroup_idx', cls.c.parent, cls.c.name, unique=True)
def view(self): from uliweb.utils.generic import DetailView group_id = int(request.values.get("id")) fields = [ {'name':'name', 'verbose_name':_('GroupName')}, {'name':'auth_type', 'verbose_name':_('AuthType')}, {'name':'created_time', 'verbose_name':_('CreateTime')}, {'name':'order', 'verbose_name':_('Order')}, {'name':'deleted', 'verbose_name':_('Deleted')}, ] obj = self.UserGroupMd.get(group_id) view = DetailView(self.UserGroupMd, obj=obj, fields=fields) response.template = 'UserGroup/view.html' return view.run()
def validate_username(self, data): from uliweb.orm import get_model if any((x in data for x in '<>& ')): return _( "Username can't include illegal characters, such as '<>&' and blank." ) if not r_username.match(data): return _("Username can only include letter, number and '._/'.") User = get_model('user') user = User.get(User.c.username == data) if user: return _('The username is already existed!')
def __get_choices_keys(choices): if callable(choices): choices = choices() if isinstance(choices, dict): keys = set(choices.keys()) elif isinstance(choices, (list, tuple)): keys = set([]) for v in choices: if isinstance(v, (list, tuple)): keys.add(v[0]) else: keys.add(v) else: raise Exception, _('Choices need a dict, tuple or list data.') return keys
def view(self, id): """ Role display """ from uliweb.utils.generic import DetailView fields = [ {'name':'name', 'verbose_name':_('Name')}, {'name':'description', 'verbose_name':_('Description')}, ] obj = self.model.get(int(id)) view = DetailView(self.model, obj=obj, fields=fields) return view.run()
def get_buttons(self): b = Buf() if self._buttons is None: b << [Button(value=_("Submit"), _class="btn btn-primary", name="submit", type="submit")] else: b << self._buttons return str(b)
def login(): from uliweb.contrib.auth import login form = functions.get_form('auth.LoginForm')() if request.user: next = request.values.get('next') if next: return redirect(next) next = request.values.get('next') if not next: next = add_prefix('/') if request.method == 'GET': form.next.data = next return {'next': next} if request.method == 'POST': flag = form.validate(request.values) if flag: f, d = functions.authenticate(username=form.username.data, password=form.password.data) if f: request.session.remember = form.rememberme.data login(form.username.data) next = unquote(next) return redirect(next) else: form.errors.update(d) if request.is_xhr: return json({'success': False, '_': 'Login Failed', 'errors': form.errors}) else: msg = form.errors.get('_', '') or _('Login failed!') return {'form': form, 'msg': str(msg)}
def login(self): from uliweb.contrib.auth import login form = functions.get_form('auth.LoginForm')() if request.user: next = request.GET.get('next','/admin') if next: return redirect(next) if request.method == 'GET': form.next.data = request.GET.get('next', request.referrer or '/') return {'form':form, 'msg':''} if request.method == 'POST': flag = form.validate(request.params) if flag: f, d = functions.authenticate(username=form.username.data, password=form.password.data) if f: request.session.remember = form.rememberme.data login(form.username.data) next = urllib.unquote(request.POST.get('next', '/admin')) return redirect(next) else: form.errors.update(d) msg = form.errors.get('_', '') or _('Login failed!') return {'msg':str(msg)}
def get_buttons(self): b = Buf() if self._buttons is None: b << [Submit(value=_('Submit'), _class="button", name="submit")] else: b << self._buttons return str(b)
def generic_add(model=None, get_url=get_url, layout='layout.html', template=None, title=None, view=None, data=None): from uliweb.utils.generic import AddView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) get_url = partial(get_url, action='view') view = AddView(model, get_url) result = view.run() if isinstance(result, dict): template = template or 'generic_add.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("Add") + safe_unicode(name) elif callable(title): title = title('add') data = data or {} result['get_url'] = get_url result['title'] = title result.update(data) return render_template(template, layout, result) else: return result
def IS_URL(data): """ Validate if the data is a valid url """ b = r_url.match(data) if not b: return _('The input value is not a valid url')
def form_validate(self, data): from uliweb.utils.common import import_attr, log from uliweb.orm import Model errors = {} if data['basemodel']: try: m = functions.get_model(data['basemodel']) if not (isinstance(m, type) and issubclass(m, Model)): errors['basemodel'] = _("Object is not a subclass of Model") except Exception as e: log.exception(e) errors['basemodel'] = _("Model can't be imported") return errors
def get_file_record(self, fileid): from uliweb import error obj = self.model.get(self.model.c.slug==fileid) if not obj: error(_('File %s is not found!') % fileid) return obj
def validate_username(self, data): from uliweb.orm import get_model User = get_model('user') user = User.get(User.c.username==data) if user: return _('User "%s" is already existed!') % data
def validate_username(self, data): from uliweb.orm import get_model User = get_model('user') user = User.get(User.c.username == data) if user: return _('The username is already existed! Please change another one.')
def add(self): """ Add new role """ from uliweb.utils.generic import AddView default_data = {'reverse':False} fields = [ {'name':'name', 'verbose_name':_('Name')}, {'name':'description', 'verbose_name':_('Description')}, ] view = AddView(self.model, url_for(self.__class__.view, _format=True), default_data=default_data, fields=fields) return view.run()
def validate_username(self, data, all_data=None): from uliweb.orm import get_model User = get_model('user') user = User.get(User.c.username == data) if user: return _('User "%s" is already existed!') % data
def login(): from uliweb.contrib.auth import login form = functions.get_form('auth.LoginForm')() if request.user: next = request.values.get('next') if next: return redirect(next) next = request.values.get('next') if not next: next = request.referrer if not next or (next and next.endswith('/login')): next = add_prefix('/') if request.method == 'GET': form.next.data = next return {} if request.method == 'POST': flag = form.validate(request.params) if flag: f, d = functions.authenticate(username=form.username.data, password=form.password.data) if f: request.session.remember = form.rememberme.data login(form.username.data) next = urllib.unquote(next) return redirect(next) else: form.errors.update(d) if request.is_xhr: return json({'success':False, 'errors':form.errors}) else: msg = form.errors.get('_', '') or _('Login failed!') return {'form':form, 'msg':str(msg)}
def form_validate(self, all_data): from uliweb.orm import get_model error = {} User = get_model('user') user = User.get(User.c.username == data) if not user: raise ValidationError, _('Username is not existed.') if not request.user.check_password(all_data.oldpassword): error['oldpassword'] = _('Password is not right.') if all_data.password != all_data.password1: error['password1'] = _('Passwords are not the same between two types.') return error
def __init__(self, action=None, method=None, buttons=None, validators=None, html_attrs=None, data=None, errors=None, idtype='name', title='', vars=None, layout=None, id=None, _class='', **kwargs): self.form_action = action or self.form_action self.form_method = method or self.form_method self.form_title = title or self.form_title self.form_class = _class or self.form_class self.form_id = id or self.form_id self.kwargs = kwargs buttons = buttons or self.form_buttons or [ str( Button(value=_('Submit'), _class="btn btn-primary", name="submit", type="submit")) ] if buttons: if isinstance(buttons, (tuple, list)): self._buttons = list(buttons) else: self._buttons = [buttons] self.validators = validators or [] self.html_attrs = html_attrs or {} if '_class' in self.html_attrs: self.html_attrs['class'] = self.html_attrs.pop('_class') self.idtype = idtype self.layout = layout or self.layout self.vars = vars for name, obj in self.fields_list: obj.idtype = self.idtype if self.form_class: self.html_attrs[ 'class'] = self.form_class # + ' ' + DEFAULT_FORM_CLASS if 'class' not in self.html_attrs: self.html_attrs['class'] = '' if self.form_id: self.html_attrs['id'] = self.form_id self.form_class = self.html_attrs.get('class') self.form_id = self.html_attrs.get('id') self.bind(data or {}, errors or {}) self.__init_validators() self.ok = True
def register(): from uliweb.contrib.auth import create_user, login form = functions.get_form('auth.RegisterForm')() if request.method == 'GET': form.next.data = request.GET.get('next', add_prefix('/')) return {'form':form, 'msg':''} if request.method == 'POST': flag = form.validate(request.params) if flag: from uliweb import settings f, d = create_user(username=form.username.data, password=form.password.data, auth_type=settings.AUTH.AUTH_TYPE_DEFAULT) if f: #add auto login support 2012/03/23 login(d) next = urllib.unquote(request.POST.get('next', add_prefix('/'))) return redirect(next) else: form.errors.update(d) msg = form.errors.get('_', '') or _('Register failed!') return {'form':form, 'msg':str(msg)}
def generic_edit(model=None, id=None, obj=None, get_url=get_url, layout='layout.html', template=None, title=None, view=None, data=None): from uliweb.utils.generic import EditView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) if not obj: obj = Model.get(Model.c.id == int(id)) view = EditView(model, get_url('view', id=id), obj=obj) result = view.run() if isinstance(result, dict): template = template or 'generic_edit.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("View") + safe_unicode(name) + ('(#%d)' % id) elif callable(title): title = title('edit', obj) data = data or {} result['get_url'] = get_url result['title'] = title result['obj_id'] = id result.update(data) return render_template(template, layout, result) else: return result
class Validator(object): default_message = _('There is an error!') def __init__(self, args=None, message=None, extra=None, next=None, field=None): self.message = message or self.default_message self.extra = extra or {} self.args = args self.next = next self.result = None self.field = field self.init() def get_message(self): if isinstance(self.message, LazyString): message = unicode(self.message) else: message = self.message return message % self.extra def validate(self, data, all_data=None): return True def init(self): if self.field: self.extra['label'] = self.field.label def __call__(self, data, all_data=None): self.result = data if not self.validate(data, all_data): return self.get_message() if self.next: return self.next(self.result)
def __init__( self, action=None, method=None, buttons=None, validators=None, html_attrs=None, data=None, errors=None, idtype="name", title="", vars=None, layout=None, id=None, _class="", **kwargs ): self.form_action = action or self.form_action or request_url() self.form_method = method or self.form_method self.form_title = title or self.form_title self.form_class = _class or self.form_class self.form_id = id or self.form_id self.kwargs = kwargs buttons = ( buttons or self.form_buttons or [str(Button(value=_("Submit"), _class="btn btn-primary", name="submit", type="submit"))] ) if buttons: if isinstance(buttons, (tuple, list)): self._buttons = list(buttons) else: self._buttons = [buttons] self.validators = validators or [] self.html_attrs = html_attrs or {} if "_class" in self.html_attrs: self.html_attrs["class"] = self.html_attrs.pop("_class") self.idtype = idtype self.layout = layout or self.layout self.vars = vars for name, obj in self.fields_list: obj.idtype = self.idtype if self.form_class: self.html_attrs["class"] = self.form_class # + ' ' + DEFAULT_FORM_CLASS if "class" not in self.html_attrs: self.html_attrs["class"] = "" if self.form_id: self.html_attrs["id"] = self.form_id self.form_class = self.html_attrs.get("class") self.form_id = self.html_attrs.get("id") self.bind(data or {}, errors or {}) self.__init_validators() self.ok = True