def _check_fields_errors(self): if self.errors: if self.error_source and self.error_source in self.errors: field_error, self.errors[self.error_source] = self.errors[ self.error_source][0], [] raise forms.ValidationError(field_error) raise forms.ValidationError(_("Form contains errors."))
def clean(self): # need to make sure the seller uploaded pictures in the fileupload form if self.request.session['check_for_sell_piece_pics']: # set this value back to False, so calls from FormWizards will not need to check again # for this instance of the form self.request.session['check_for_sell_piece_pics'] = False # use self.prefix as current step, minor hack :) piece_pics = Picture.objects.filter( seller=self.request.user, type='p', piece__isnull=True, piece_step=int(self.prefix)) if not piece_pics: # throw an error to tell seller to upload pictures for outfit raise forms.ValidationError(_(u'Remember to upload one or more photos above!')) # make sure primary photo was selected if piece_pics.filter(is_primary=True).count() == 0: if piece_pics.count() == 1: # if there is only one photo, just mark this as primary for pic in piece_pics: pic.is_primary = True pic.save() else: raise forms.ValidationError(make_primary_error_message) return self.cleaned_data
def post_action_merge(self, ids): users = [] posts = [] for post in self.posts: if post.pk in ids: posts.append(post) if not post.user_id in users: users.append(post.user_id) if len(users) > 1: raise forms.ValidationError( _("You cannot merge replies made by different members!" )) if len(posts) < 2: raise forms.ValidationError( _("You have to select two or more posts you want to merge.")) new_post = posts[0] for post in posts[1:]: post.merge_with(new_post) post.delete() md, new_post.post_preparsed = post_markdown(new_post.post) new_post.sync_attachments() new_post.save(force_update=True) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) messages.success( self.request, _('Selected posts have been merged into one message.'), 'threads')
def clean(self): """ Verify password fields match and school is provided. If addschool is True, build a new School based on data in nested SchoolForm. If not, and no school was selected, auto-construct one. """ data = self.cleaned_data password = data.get('password') confirm = data.get('password_confirm') if password != confirm: raise forms.ValidationError("The passwords didn't match.") if data.get('addschool'): if self.addschool_form.is_valid(): data['school'] = self.addschool_form.save(commit=False) else: raise forms.ValidationError( "Could not add a school.") else: # reinstantiate unbound addschool_form to avoid spurious errors self.addschool_form = SchoolForm(prefix='addschool') if data.get('email') and not data.get('school'): data['school'] = model.School( name=(u"%f-%s" % (time.time(), data['email']))[:200], postcode="", auto=True, ) return data
def clean_poll_choices(self): self.clean_choices = [] self.new_choices = [] data = self.cleaned_data['poll_choices'] if self.poll: self.clean_poll_edited_choices() if data: for choice in data.splitlines(): choice = choice.strip() if not choice in self.clean_choices: if len(choice) < 2: raise forms.ValidationError( _("Poll choices should be at least two characters long." )) if len(choice) > 250: raise forms.ValidationError( _("Poll choices should be no longer than 250 characters." )) self.clean_choices.append(choice) self.new_choices.append(choice) if len(self.clean_choices) < 2: raise forms.ValidationError( _("Poll needs at least two choices.")) if len(self.clean_choices) > 10: raise forms.ValidationError( _("Poll cannot have more than 10 choices.")) return '\r\n'.join(self.clean_choices)
def clean_invite_users(self): self.users_list = [] usernames = [] slugs = [self.request.user.username_slug] for username in self.cleaned_data['invite_users'].split(','): username = username.strip() slug = slugify(username) if len(slug) >= 3 and not slug in slugs: slugs.append(slug) usernames.append(username) try: user = User.objects.get(username_slug=slug) if not user.acl().private_threads.can_participate(): raise forms.ValidationError( _('%(user)s cannot participate in private threads.' ) % {'user': user.username}) if (not self.request.acl.private_threads. can_invite_ignoring() and not user.allow_pd_invite(self.request.user)): raise forms.ValidationError( _('%(user)s restricts who can invite him to private threads.' ) % {'user': user.username}) self.users_list.append(user) except User.DoesNotExist: raise forms.ValidationError( _('User "%(username)s" could not be found.') % {'username': username}) if len(usernames) > 8: raise forms.ValidationError( _('You cannot invite more than 8 members at single time. Post thread and then invite additional members.' )) return ', '.join(usernames)
def clean_shapefile(self): try: z = zipfile.ZipFile(self.cleaned_data["shapefile"], 'r') except zipfile.BadZipfile: raise forms.ValidationError( "Uploaded file is not a valid zip file.") shapefile_path = None target_dir = tempfile.mkdtemp(suffix="-mlt-parcel-shapefile") try: for name in z.namelist(): if name.startswith(os.path.sep) or os.path.pardir in name: raise forms.ValidationError( "Zip file contains unsafe paths (absolute or with ..)." ) z.extract(name, target_dir) if name.endswith(".shp"): shapefile_path = os.path.join(target_dir, name) if shapefile_path is None: raise forms.ValidationError( "Unable to find a .shp file in uploaded zip file.") except forms.ValidationError: shutil.rmtree(target_dir) raise self.cleaned_data["target_dir"] = target_dir self.cleaned_data["shapefile_path"] = shapefile_path return self.cleaned_data["shapefile"]
def clean_new_forum(self): new_forum = self.cleaned_data['new_forum'] # Assert its forum and its not current forum if new_forum.type != 'forum': raise forms.ValidationError(_("This is not forum.")) if new_forum.pk == self.forum.pk: raise forms.ValidationError(_("New forum is same as current one.")) return new_forum
def clean_poll_max_choices(self): data = self.cleaned_data['poll_max_choices'] if data < 1: raise forms.ValidationError( _("Voters must be allowed to make at least one choice.")) if self.clean_choices and data > len(self.clean_choices): raise forms.ValidationError( _("Users cannot cast more votes than there are options.")) return data
def clean(self): data = super(StudentGradeReportWriterForm, self).clean() if not data.get('student') and not data.get('all_students'): raise forms.ValidationError( "You must either check \"all students\" or select a student") if not data.get('template') and not data.get('upload_template'): raise forms.ValidationError( "You must either select a template or upload one.") return data
def clean_geom(self): geom = self.cleaned_data['geom'] if geom is None: raise forms.ValidationError(_("Invalid snapped geometry.")) if not geom.simple: raise forms.ValidationError(_("Geometry is not simple.")) if not PathHelper.disjoint(geom, self.cleaned_data.get('pk') or -1): raise forms.ValidationError(_("Geometry overlaps another.")) return geom
def clean_ttl(self): try: ttl = int(self.cleaned_data['ttl']) except ValueError: raise forms.ValidationError(_('Please enter an integer value.')) if ttl > 365 or ttl < 2: raise forms.ValidationError( _('Please enter a value between 2 and 365.')) return ttl
def clean_geom(self): pk = self.instance.pk if self.instance and self.instance.pk else -1 geom = self.cleaned_data['geom'] if geom is None: raise forms.ValidationError(_("Invalid snapped geometry.")) if not geom.simple: raise forms.ValidationError(_("Geometry is not simple.")) if not PathHelper.disjoint(geom, pk): raise forms.ValidationError(_("Geometry overlaps another.")) return geom
def clean_contents(self): data = self.cleaned_data['contents'] if data: if data.type == 'category': raise forms.ValidationError( _("Categories cannot contain threads.")) if data.type == 'redirect': raise forms.ValidationError( _("Redirects cannot contain threads.")) return data
def clean(self): cleaned_data = super(SettingsForm, self).clean() if cleaned_data.get('alert_email') and cleaned_data.get('email') == '': raise forms.ValidationError(u'Введите email') if cleaned_data.get('alert_sms') and cleaned_data.get('phone') == '': raise forms.ValidationError(u'Введите номер телефона') return cleaned_data
def clean_file(self): file_obj = self.cleaned_data['file'] if len(file_obj.name.split('.')) == 1: raise forms.ValidationError(_("File type is not allowed!")) if file_obj.name.split('.')[-1].lower() not in settings.UPLOAD_ALLOWED_EXTS: raise forms.ValidationError(_("File type is not allowed!")) return file_obj
def clean_poll(self, data): try: if bool(data['poll_question']) != bool(self.clean_choices): if bool(data['poll_question']): raise forms.ValidationError( _("You have to define poll choices.")) else: raise forms.ValidationError( _("You have to define poll question.")) except KeyError: pass return data
def clean_poll_question(self): data = self.cleaned_data['poll_question'].strip() if data or self.poll: if len(data) < 3: raise forms.ValidationError( _("Poll quesiton should be at least three characters long." )) if len(data) > 255: raise forms.ValidationError( _("Poll quesiton should be no longer than 250 characters.") ) return data
def clean(self): pk = self.cleaned_data.get('redirected', None) status = self.cleaned_data.get('status', None) if status == "request_redirected": if pk is None: raise forms.ValidationError( _("Provide the redirected public body!")) try: self._redirected_public_body = PublicBody.objects.get(id=pk) except PublicBody.DoesNotExist: raise forms.ValidationError(_("Invalid value")) return self.cleaned_data
def clean(self): cleaned_data = super(NewNodeForm, self).clean() node_role = cleaned_data['role'] if node_role != 'category' and cleaned_data['parent'].special == 'root': raise forms.ValidationError( _("Only categories can use Root Category as their parent.")) if node_role == 'redirect' and not cleaned_data['redirect']: raise forms.ValidationError( _("You have to define redirection URL")) return cleaned_data
def clean(self): """Verify that products all match up.""" productversion = self.cleaned_data.get("productversion") suite = self.cleaned_data.get("suite") product = self.cleaned_data.get("product") if product and productversion and productversion.product != product: raise forms.ValidationError( "Must select a version of the correct product.") if product and suite and suite.product != product: raise forms.ValidationError( "Must select a suite for the correct product.") return self.cleaned_data
def clean_public_body(self): pb = self.cleaned_data['public_body'] try: pb_pk = int(pb) except ValueError: raise forms.ValidationError(_("Invalid value")) try: public_body = PublicBody.objects.get(pk=pb_pk) except PublicBody.DoesNotExist: raise forms.ValidationError(_("Invalid value")) self.public_body_object = public_body self.foi_law_object = public_body.default_law return pb
def clean_user_email(self): email = self.cleaned_data['user_email'] try: user = User.objects.get(email=email) except User.DoesNotExist: pass else: if user.is_active: raise forms.ValidationError(mark_safe( _('This email address already has an account. <a href="%s?simple" class="target-small">Please login using that email address.</a>') % reverse("account-login"))) else: raise forms.ValidationError( _('This email address is already registered, but not yet confirmed! Please click on the confirmation link in the mail we send you.')) return email
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise floppyforms.ValidationError( message % {'username': self.username_field.verbose_name}) elif not self.user_cache.is_active or not self.user_cache.is_staff: raise floppyforms.ValidationError( message % {'username': self.username_field.verbose_name}) return self.cleaned_data
def clean_options(self): data = self.cleaned_data['options'] try: if not data: raise forms.ValidationError(_("You have to make selection.")) if len(data) > self.poll.max_choices: raise forms.ValidationError( ungettext( "You cannot select more than one option.", "You cannot select more than %(limit)s options.", self.poll.max_choices) % {'limit': self.poll.max_choices}) except TypeError: pass return data
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') self.user = None if username and password: self.user = authenticate(username=username, password=password) if self.user is None: raise forms.ValidationError( _(u'The username and/or password is incorrect, please try again.' )) elif not self.user.is_active: raise forms.ValidationError(_(u'This user is inactive.')) return self.cleaned_data
def clean(self): """Can't create new tags without appropriate permissions.""" if (self.data.get("tag-newtag") and not (self.user and self.user.has_perm("tags.manage_tags"))): raise forms.ValidationError( "You do not have permission to create new tags.") return self.cleaned_data
def clean_date(self): date = self.cleaned_data['date'] now = timezone.now().date() if date > now: raise forms.ValidationError( _("Your reply date is in the future, that is not possible.")) return date
def clean_sender(self): pk = self.cleaned_data['sender'] try: self._public_body = PublicBody.objects.get(id=pk) except PublicBody.DoesNotExist: raise forms.ValidationError(_("Invalid value")) return pk
def post_action_soft(self, ids): deleted = [] for post in self.posts: if post.pk in ids and not post.deleted: if post.pk == self.thread.start_post_id: raise forms.ValidationError( _("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead." )) deleted.append(post.pk) if deleted: update_kwargs = { 'deleted': True, 'current_date': timezone.now(), 'delete_date': timezone.now(), 'edit_user': self.request.user, 'edit_user_name': self.request.user.username, 'edit_user_slug': self.request.user.username_slug, } self.thread.post_set.filter(id__in=deleted).update(**update_kwargs) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) messages.success(self.request, _('Selected posts have been hidden.'), 'threads') else: messages.info(self.request, _('No posts were hidden.'), 'threads')