def test_tag_d_validation(self): t = TagField() self.assertEqual(t.clean('foo'), 'foo') self.assertEqual(t.clean('foo bar baz'), 'foo bar baz') self.assertEqual(t.clean('foo,bar,baz'), 'foo,bar,baz') self.assertEqual(t.clean('foo, bar, baz'), 'foo, bar, baz') self.assertEqual(t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar'), 'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar') self.assertRaises(forms.ValidationError, t.clean, 'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar')
def testFormFields(self): from django.forms import ValidationError t = TagField() self.assertEqual(u'foo', t.clean('foo')) self.assertEqual(u'foo bar baz', t.clean('foo bar baz')) self.assertEqual(u'foo,bar,baz', t.clean('foo,bar,baz')) self.assertEqual(u'foo, bar, baz', t.clean('foo, bar, baz')) self.assertEqual(u'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar', t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar')) self.assertRaises(ValidationError, t.clean, 'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar')
class TipForm(ModelForm): id = IntegerField(required=False, widget=HiddenInput()) tags = TagField(max_length=50, label='Tags', required=False, widget=AutoCompleteTagInput()) class Meta: model = Tip exclude = ['author', 'slug_title', 'pub_date', 'hits', 'approved'] def __init__(self, *args, **kwargs): super(TipForm, self).__init__(*args, **kwargs) if self.instance.id: self.initial['tags'] = ' '.join([item.name for item in Tag.objects.get_for_object(self.instance)]) def save(self, *args, **kwargs): self.instance.approved = settings.APPROVE_NEW_TIPS_AUTOMATICALY super(TipForm, self).save(*args, **kwargs) from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [mail_tuple[1] for mail_tuple in settings.ADMINS] subject = '[TIP] %s' % self.instance.slug_title message = "Author: %s \nE-mail: %s\n\n%s\n\n%s" % (self.instance.author, self.instance.author.email, self.instance.title, self.instance.body) mail = EmailMessage(subject, message, from_email, recipient_list) try: mail.send() except: pass
class PostAdminModelForm(forms.ModelForm): tags = TagField(widget=CloudTagInput(), required=False) date_published = forms.DateTimeField(widget=widgets.AdminSplitDateTime) def save(self, force_insert=False, force_update=False, commit=True): m = super(PostAdminModelForm, self).save(commit=False) m.content = m.content m.save() return m class Meta: model = Post class Media: css = { 'all': ( 'jquery.autocomplete.css', 'admin/rte/rte.css', ) } js = ( 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'js/urlify.js', 'jquery.bgiframe.min.js', 'js/RelatedObjectLookups.js', 'js/calendar.js', 'js/DateTimeShortcuts.js', )
class EntryAdminForm(forms.ModelForm): """ Form for Entry's Admin. """ categories = MPTTModelMultipleChoiceField( label=_('Categories'), required=False, queryset=Category.objects.all(), widget=MPTTFilteredSelectMultiple(_('categories'), False, attrs={'rows': '10'})) tags = TagField(label=_('Tags'), required=False, widget=TagAutoComplete()) def __init__(self, *args, **kwargs): super(EntryAdminForm, self).__init__(*args, **kwargs) rel = ManyToManyRel(Category, 'id') self.fields['categories'].widget = RelatedFieldWidgetWrapper( self.fields['categories'].widget, rel, self.admin_site) self.fields['sites'].initial = [Site.objects.get_current()] class Meta: """ EntryAdminForm's Meta. """ model = Entry fields = forms.ALL_FIELDS
class CmsForm(PermalinkForm): class Meta: model = CommonCms title = forms.CharField(max_length=512, help_text=_('Title in 512 characters')) image = files_widget.forms.FilesFormField(required=False, fields=(forms.CharField(required=False), forms.CharField(required=False), forms.CharField(required=False), ), widget=files_widget.forms.widgets.ImageWidget()) permalink = forms.CharField() summary = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 5, 'maxlength': 240})) description = forms.CharField(required=False, widget=CKEditorWidget()) topics = forms.ModelMultipleChoiceField(queryset=Topic.objects.filter(level=0), widget=forms.CheckboxSelectMultiple(attrs={'id': 'id_topics'})) tags = TagField(required=False, widget=TagAutocompleteTagIt(max_tags=False), help_text='') in_the_news = forms.ModelMultipleChoiceField( required=False, queryset=Party.objects.all(), widget=autocomplete_light.MultipleChoiceWidget(CmsHasPartyAutocomplete, attrs={'placeholder': _('Type to search organizations or people by name.'), 'class': 'form-control'} ) ) is_promoted = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'id': 'id_is_promoted'}) )
class AskForm(forms.ModelForm): tags = TagField(widget=TagAutocomplete()) notify = forms.BooleanField(required=False) class Meta: model = Question exclude = ['date_created', 'views', 'user', 'last_answer_date']
class BookmarkInstanceEditForm(forms.ModelForm): description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceEditForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['description', 'note', 'tags', 'redirect'] def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False class Meta: model = BookmarkInstance #fields = ('description', 'note', 'redirect') def clean(self): # The Bookmark Instance doesn't have a url field, as we can't change it. return self.cleaned_data
class ProductForm(forms.ModelForm): name = forms.CharField(max_length=50, required=True) description = forms.CharField(widget=forms.Textarea(attrs={}), required=True) tags = TagField(required=False, help_text="Add tags that help describe this product. Separeate each tag with a comma.") prod_type = forms.ModelChoiceField(label='Product Type', queryset=Product_Type.objects.all(), required=True) prod_manager = forms.CharField(max_length=30, label="Product Manager", required=False) tech_contact = forms.CharField(max_length=30, label="Technical Contact", required=False) manager = forms.CharField(max_length=30, label="Team Manager", required=False) authorized_users = forms.ModelMultipleChoiceField( queryset=None, required=False, label="Authorized Users") def __init__(self, *args, **kwargs): non_staff = User.objects.exclude(is_staff=True) \ .exclude(is_active=False) super(ProductForm, self).__init__(*args, **kwargs) self.fields['authorized_users'].queryset = non_staff class Meta: model = Product fields = ['name', 'description', 'tags', 'prod_manager', 'tech_contact', 'manager', 'prod_type', 'authorized_users']
class LancamentoForm(ModelForm): """ Form para cadastro de lancamentos. """ tags = TagField(max_length=50, label='Tags', required=False, widget=AutoCompleteTagInput()) vencimento = DateField(('%d/%m/%Y', ), label='Vencimento', widget=DateTimeInput(format='%d/%m/%Y')) tipo = ChoiceField(choices=Lancamento.TIPO_CHOICES) valor = PositiveDecimalField() class Meta: model = Lancamento fields = [ 'desc', 'vencimento', 'valor', 'tipo', 'forma_pagamento', 'credor', 'caixa', 'tags', 'pago' ] def __init__(self, *args, **kwargs): super(LancamentoForm, self).__init__(*args, **kwargs) if self.instance.id: self.initial['tags'] = ' '.join([ item.name for item in Tag.objects.get_for_object(self.instance) ]) #() def as_ext(self): # Converte os campos para o formato ExtJS return mark_safe(simplejson.dumps(self, cls=ExtJSONEncoder))
class ImportScanForm(forms.Form): SCAN_TYPE_CHOICES = (("Burp Scan", "Burp Scan"), ("Nessus Scan", "Nessus Scan"), ("Nexpose Scan", "Nexpose Scan"), ("AppSpider Scan", "AppSpider Scan"), ("Veracode Scan", "Veracode Scan"), ("Checkmarx Scan", "Checkmarx Scan"), ("ZAP Scan", "ZAP Scan")) scan_date = forms.DateTimeField( required=True, label="Scan Completion Date", help_text="Scan completion date will be used on all findings.", initial=datetime.now().strftime("%m/%d/%Y"), widget=forms.TextInput(attrs={'class': 'datepicker'})) minimum_severity = forms.ChoiceField(help_text='Minimum severity level to be imported', required=True, choices=SEVERITY_CHOICES[0:4]) active = forms.BooleanField(help_text="Select if these findings are currently active.", required=False) verified = forms.BooleanField(help_text="Select if these findings have been verified.", required=False) scan_type = forms.ChoiceField(required=True, choices=SCAN_TYPE_CHOICES) tags = TagField(required=False, help_text="Add tags to help describe this test. Separate tags with a comma.") file = forms.FileField(widget=forms.widgets.FileInput( attrs={"accept": ".xml, .csv, .nessus"}), label="Choose report file", required=True) # date can only be today or in the past, not the future def clean_scan_date(self): date = self.cleaned_data['scan_date'] if date.date() > datetime.today().date(): raise forms.ValidationError("The date cannot be in the future!") return date
class PagesPortletForm(forms.ModelForm): """Add/edit form of the pages portlet. """ tags = TagField(widget=AutoCompleteTagInput(), required=False) class Meta: model = PagesPortlet
class RandomPortletForm(forms.ModelForm): """Add/Edit form for the random portlet. """ tags = TagField(widget=AutoCompleteTagInput(), required=False) class Meta: model = RandomPortlet
class RepositoryForm(forms.ModelForm): """Base class for item types Data, Task and Method. @cvar tags: an input field with its contents autocompleted @type tags: tagging.forms.TagField """ tags = TagField(widget=AutoCompleteTagInput(), required=False) keep_private = BooleanField( widget=forms.CheckboxInput(attrs=attrs_checkbox), required=False) def clean_name(self): """Cleans field name.""" if re.match('^\d+$', self.cleaned_data['name']): raise ValidationError( _('Names consisting of only numerical values are not allowed.') ) return self.cleaned_data['name'] def clean_tags(self): """Cleans field tags. We want to avoid tags like 'foo, bar baz', i.e. we want foo, bar, baz to be tags, so split based on spaces and then comma """ tags = self.cleaned_data['tags'] return ','.join([y for x in tags.split() for y in x.split(',') if y])
class TaskForm(forms.ModelForm): def __init__(self, user, group, *args, **kwargs): self.user = user self.group = group super(TaskForm, self).__init__(*args, **kwargs) if group: assignee_queryset = group.member_queryset() else: assignee_queryset = self.fields["assignee"].queryset self.fields["assignee"].queryset = assignee_queryset.order_by("username") self.fields['summary'].widget.attrs["size"] = 65 def save(self, commit=True): return super(TaskForm, self).save(commit) tags = TagField(required=False, widget=TagAutoCompleteInput(app_label='tasks', model='task')) class Meta: model = Task fields = ('summary', 'detail', 'assignee', 'tags', 'markup') def clean(self): self.check_group_membership() return self.cleaned_data def check_group_membership(self): group = self.group if group and not self.group.user_is_member(self.user): raise forms.ValidationError("You must be a member to create tasks")
class UpdateForm(forms.ModelForm): tags = TagField(required=False, help_text=_( 'Enter space separated list of single word tags ' \ 'or comma separated list of tags containing spaces. ' \ 'Use doublequotes to enter name containing comma.' ), widget=forms.TextInput(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.initial['tags'] = self.instance.tags_edit_string() def save(self, commit=True): scl = super(UpdateForm, self).save(commit) scl.tags = self.cleaned_data['tags'] scl.add_auto_tags() return scl class Meta: model = SoftwareCollection fields = ['title', 'description', 'instructions', 'issue_tracker', 'upstream_url', 'policy', 'auto_sync',] widgets = { 'title': forms.TextInput( attrs={'class': 'form-control'}), 'description': forms.Textarea( attrs={'class': 'form-control', 'rows': '4'}), 'instructions': forms.Textarea( attrs={'class': 'form-control', 'rows': '4'}), 'upstream_url': forms.TextInput( attrs={'class': 'form-control'}), 'policy': forms.RadioSelect(choices=POLICY_CHOICES_TEXT, renderer=RadioSelectTableRenderer), 'issue_tracker': forms.TextInput( attrs={'class': 'form-control'}), 'auto_sync': forms.CheckboxInput(attrs={'class': 'form-control-static'}), }
class BlogEntryForm(forms.ModelForm): """The add/edit form of the Blog content object """ tags = TagField(widget=AutoCompleteTagInput(), required=False) class Meta: model = BlogEntry fields = ("title", "display_title", "slug", "description", "text", "tags")
class IssueForm(forms.Form): title = forms.CharField( label=_('your issue title'), widget=forms.Textarea(attrs={'id': 'title'}), max_length=200, ) body = forms.CharField( label=_('arguments'), widget=forms.Textarea(attrs={'id': 'arguments'}), max_length=2000, ) url = forms.URLField( label=_('external source of information'), widget=forms.TextInput(attrs={'size': '80'}), ) source_type = forms.ChoiceField( label=_("source type"), choices=source_types, ) options = [ (1, votes[1]), (-1, votes[-1]), ] direction = forms.TypedChoiceField(label=_("your vote"), choices=options, coerce=int) # is_draft = forms.BooleanField(label=_("publish"), initial=True, required=False) tags = TagField(label=_("tags"), required=True, widget=forms.TextInput(attrs={'size': '80'}))
class NewsForm(forms.ModelForm): class Meta: model = News title = forms.CharField(widget=forms.Textarea(attrs={'rows': 3}), max_length=500) if news_settings.NEWS_TAGGING: tags = TagField(required=False)
class ArticleForm(forms.ModelForm): tags = TagField(widget=TagAutocomplete()) class Meta: model = Article fields = ('category', 'title', 'image', 'image_url', 'card_text', 'content', 'tags', 'author') widgets = {'author': forms.HiddenInput}
class TForm(forms.ModelForm): test = TagField( widget=autocomplete.TaggingSelect2('select2_tagging'), required=False, ) class Meta: model = TModel exclude = ['for_inline']
class CoreDataForm(forms.ModelForm): """Core data form for pages. """ tags = TagField(widget=AutoCompleteTagInput(), required=False) class Meta: model = Page fields = ("title", "display_title", "slug", "description", "text", "tags")
class RecipeForm(forms.ModelForm): description = forms.CharField(widget=MarkItUpWidget()) ingredients = forms.CharField(widget=MarkItUpWidget()) directions = forms.CharField(widget=MarkItUpWidget()) tags = TagField(widget=AutoCompleteTagInput()) captcha = ReCaptchaField(label="Please let us know you are a real person") class Meta: model = Recipe exclude = ('approved', 'slug')
class TagsCreateOneForm(TagsBaseForm): """ For adding a non existing tag """ tag = TagField() def save(self): owner = globals.user tagged_object = self.get_related_object() tagged_object.private_tags.add(self.cleaned_data['tag'], owner=owner)
class AudioForm(forms.ModelForm): tags_aud = TagField(widget=TagAutocomplete(), required=False) class Meta: model = Audios exclude = ( 'content_type', 'object_id', 'content_object', )
class FotoForm(forms.ModelForm): tags_img = TagField(widget=TagAutocomplete(), required=False, label="Tags") class Meta: model = Imagen exclude = ( 'content_type', 'object_id', 'content_object', )
def test_tag_d_validation(self): t = TagField() self.assertEquals(t.clean('foo'), u'foo') self.assertEquals(t.clean('foo bar baz'), u'foo bar baz') self.assertEquals(t.clean('foo,bar,baz'), u'foo,bar,baz') self.assertEquals(t.clean('foo, bar, baz'), u'foo, bar, baz') self.assertEquals(t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar'), u'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar') try: t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar') except forms.ValidationError, ve: self.assertEquals(str(ve), "[u'Each tag may be no more than 50 characters long.']")
class SectionAdminModelForm(ModelForm): # It uses the same tags than articles. (TODO: explain better this comment) tags = TagField(widget=TagAutocompleteTagIt({ 'app': 'core', 'model': 'article' }), required=False) class Meta: model = Section fields = "__all__"
class ZornaFileAddForm(ModelForm): file = forms.CharField(label=_( u'File'), widget=forms.FileInput(attrs={'size': '80'})) description = forms.CharField(label=_( u'Description'), widget=forms.TextInput(attrs={'size': '80'})) tags = TagField(required=False, widget=forms.TextInput( attrs={'class': 'zorna-tags'})) class Meta: model = ZornaFile fields = ('file', 'description', 'tags')
class PopupPlaneForm(ModelForm): tags = TagField(widget=forms.Textarea, required=False) class Meta: model = Plane ## add these functions to the class this way so we don't have to duplicate ## code when adding them to the mass entry form as well... clean_tailnumber = clean_tailnumber clean_type = clean_type clean_fuel_burn = clean_fuel_burn clean = clean
class TestForm(forms.ModelForm): test_type = forms.ModelChoiceField(queryset=Test_Type.objects.all()) environment = forms.ModelChoiceField( queryset=Development_Environment.objects.all()) target_start = forms.DateTimeField(widget=forms.TextInput( attrs={'class': 'datepicker'})) target_end = forms.DateTimeField(widget=forms.TextInput( attrs={'class': 'datepicker'})) tags = TagField(required=False, help_text="Add tags to help describe Test. Separate tags with commas.") class Meta: model = Test fields = ['test_type', 'target_start', 'target_end', 'environment', 'percent_complete', 'tags']
class ArticleAdminModelForm(ModelForm): body = CharField(widget=MarkdownWidget()) headline = CharField(label=u'Título', widget=TextInput(attrs={'style': 'width:600px'})) slug = CharField( label='Slug', widget=TextInput(attrs={ 'style': 'width:600px', 'readonly': 'readonly' }), help_text=u'Se genera automáticamente en base al título.', ) tags = TagField(widget=TagAutocompleteTagIt(max_tags=False), required=False) def clean_tags(self): """ This is a hack to bypass the bug that: 1 tag with spaces is considered as many tags by the lib. This doesn't ocurr with 2 tags or more. With double quotes, the tag with spaces is correctly interpreted. """ tags = self.cleaned_data.get('tags') if tags and ',' not in tags: # there is just 1 tag tags = tags.strip('"') tags = '"' + tags + '"' return tags def clean(self): cleaned_data = super(ArticleAdminModelForm, self).clean() date_value = (self.cleaned_data.get('date_published') if self.cleaned_data.get('is_published') else self.cleaned_data.get('date_created')) or date.today() targets = Article.objects.filter( Q(is_published=True) & Q(date_published__year=date_value.year) & Q(date_published__month=date_value.month) | Q(is_published=False) & Q(date_created__year=date_value.year) & Q(date_created__month=date_value.month), slug=slugify( cleanhtml(ldmarkup(smart_quotes( cleaned_data.get('headline'))))), ) if self.instance.id: targets = targets.exclude(id=self.instance.id) if targets: raise ValidationError( u'Ya existe un artículo en ese mes con el mismo título.') class Meta: model = Article fields = "__all__"
def test_tag_d_validation(self): t = TagField(required=False) self.assertEqual(t.clean(""), "") self.assertEqual(t.clean("foo"), "foo") self.assertEqual(t.clean("foo bar baz"), "foo bar baz") self.assertEqual(t.clean("foo,bar,baz"), "foo,bar,baz") self.assertEqual(t.clean("foo, bar, baz"), "foo, bar, baz") self.assertEqual( t.clean("foo qwertyuiopasdfghjklzxcvbnm" "qwertyuiopasdfghjklzxcvb bar"), "foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar", ) self.assertRaises(forms.ValidationError, t.clean, "foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar")
def test_tag_d_validation(self): t = TagField() self.assertEqual(t.clean('foo'), 'foo') self.assertEqual(t.clean('foo bar baz'), 'foo bar baz') self.assertEqual(t.clean('foo,bar,baz'), 'foo,bar,baz') self.assertEqual(t.clean('foo, bar, baz'), 'foo, bar, baz') self.assertEqual(t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar'), 'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar') try: t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar') except forms.ValidationError as exc: self.assertEqual(str(exc), str([six.text_type('Each tag may be no more than 50 characters long.')])) except Exception as exc: raise exc else: raise self.failureException('a ValidationError exception was supposed to have been raised.')
def test_tag_d_validation(self): t = TagField() self.assertEqual(t.clean('foo'), u'foo') self.assertEqual(t.clean('foo bar baz'), u'foo bar baz') self.assertEqual(t.clean('foo,bar,baz'), u'foo,bar,baz') self.assertEqual(t.clean('foo, bar, baz'), u'foo, bar, baz') self.assertEqual(t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar'), u'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar') try: t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar') except forms.ValidationError as ve: self.assertEqual(ve.messages, ['Each tag may be no more than 50 characters long.']) except Exception as e: raise e else: raise self.failureException('a ValidationError exception was supposed to have been raised.')