def test_urlfield_7(self): f = URLField() self.assertEqual("http://example.com", f.clean("http://example.com")) self.assertEqual("http://example.com/test", f.clean("http://example.com/test")) self.assertEqual( "http://example.com?some_param=some_value", f.clean("http://example.com?some_param=some_value") )
def _extract_url(cls, text_url_field): ''' >>> url_text = 'http://www.google.com blabla' >>> FacebookAPI._extract_url(url_text) u'http://www.google.com/' >>> url_text = 'http://www.google.com/' >>> FacebookAPI._extract_url(url_text) u'http://www.google.com/' >>> url_text = 'google.com/' >>> FacebookAPI._extract_url(url_text) u'http://google.com/' >>> url_text = 'http://www.fahiolista.com/www.myspace.com/www.google.com' >>> FacebookAPI._extract_url(url_text) u'http://www.fahiolista.com/www.myspace.com/www.google.com' >>> url_text = u"""http://fernandaferrervazquez.blogspot.com/\r\nhttp://twitter.com/fferrervazquez\r\nhttp://comunidad.redfashion.es/profile/fernandaferrervazquez\r\nhttp://www.facebook.com/group.php?gid3D40257259997&ref3Dts\r\nhttp://fernandaferrervazquez.spaces.live.com/blog/cns!EDCBAC31EE9D9A0C!326.trak\r\nhttp://www.linkedin.com/myprofile?trk3Dhb_pro\r\nhttp://www.youtube.com/account#profile\r\nhttp://www.flickr.com/\r\n Mi galer\xeda\r\nhttp://www.flickr.com/photos/wwwfernandaferrervazquez-showroomrecoletacom/ \r\n\r\nhttp://www.facebook.com/pages/Buenos-Aires-Argentina/Fernanda-F-Showroom-Recoleta/200218353804?ref3Dts\r\nhttp://fernandaferrervazquez.wordpress.com/wp-admin/""" >>> FacebookAPI._extract_url(url_text) u'http://fernandaferrervazquez.blogspot.com/a' ''' import re text_url_field = text_url_field.encode('utf8') seperation = re.compile('[ ,;\n\r]+') parts = seperation.split(text_url_field) for part in parts: from django.forms import URLField url_check = URLField(verify_exists=False) try: clean_url = url_check.clean(part) return clean_url except ValidationError, e: continue
def get_url_informations(url): """Get informations about a url""" error_invalid = False, {"error": _(u"Invalid URL")} error_exist = False, {"error": _(u"This URL has already been submitted")} error_connect = False, {"error": _(u"Failed at opening the URL")} # Check url is valid try: url_field = URLField() clean_url = url_field.clean(url) except: return error_invalid # Check url exist if exist_url(clean_url): return error_exist # Get informations req = requests.get(clean_url) if 200 == req.status_code: final_url = req.url soup = BeautifulSoup(req.text) title = soup.title.string description = soup.findAll("meta", attrs={"name": re.compile("^description$", re.I)})[0].get("content") else: return error_connect # Check final url exist if different from clean url if final_url != clean_url: if exist_url(final_url): return error_exist return True, {"url": final_url, "title": title, "description": description}
def _extract_url(cls, text_url_field): ''' >>> url_text = 'http://www.google.com blabla' >>> FacebookAPI._extract_url(url_text) u'http://www.google.com/' >>> url_text = 'http://www.google.com/' >>> FacebookAPI._extract_url(url_text) u'http://www.google.com/' >>> url_text = 'google.com/' >>> FacebookAPI._extract_url(url_text) u'http://google.com/' >>> url_text = 'http://www.fahiolista.com/www.myspace.com/www.google.com' >>> FacebookAPI._extract_url(url_text) u'http://www.fahiolista.com/www.myspace.com/www.google.com' ''' import re text_url_field = str(text_url_field) seperation = re.compile('[ |,|;]+') parts = seperation.split(text_url_field) for part in parts: from django.forms import URLField url_check = URLField(verify_exists=False) try: clean_url = url_check.clean(part) return clean_url except ValidationError, e: continue
def test_urlfield_7(self): f = URLField() self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com/test', f.clean('http://example.com/test')) self.assertEqual( 'http://example.com?some_param=some_value', f.clean('http://example.com?some_param=some_value') )
def test_urlfield_10(self): """URLField correctly validates IPv6 (#18779).""" f = URLField() urls = ( 'http://[12:34::3a53]/', 'http://[a34:9238::]:8080/', ) for url in urls: self.assertEqual(url, f.clean(url))
def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://%s' % ("X" * 200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://%s' % ("X" * 60,))
def test_urlfield_9(self): f = URLField() urls = ( 'http://עברית.idn.icann.org/', 'http://sãopaulo.com/', 'http://sãopaulo.com.br/', 'http://пример.испытание/', 'http://مثال.إختبار/', 'http://例子.测试/', 'http://例子.測試/', 'http://उदाहरण.परीक्षा/', 'http://例え.テスト/', 'http://مثال.آزمایشی/', 'http://실례.테스트/', 'http://العربية.idn.icann.org/', ) for url in urls: # Valid IDN self.assertEqual(url, f.clean(url))
def get_url_informations(url): """Get informations about a url""" error_invalid = False, {'error': _(u'Invalid URL')} error_exist = False, {'error': _(u'This URL has already been submitted')} error_connect = False, {'error': _(u'Failed at opening the URL')} # Check url is valid try: url_field = URLField() clean_url = url_field.clean(url) except: return error_invalid # Check url exist if exist_url(clean_url): return error_exist # Get informations req = requests.get(clean_url) if req.status_code == 200: final_url = req.url soup = BeautifulSoup(req.text) title = soup.title.string description = soup.findAll('meta', attrs={'name': re.compile("^description$", re.I)})[0].get('content') else: return error_connect # Check final url exist if different from clean url if final_url != clean_url: if exist_url(final_url): return error_exist return True, { 'url': final_url, 'title': title, 'description': description, }
def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertWidgetRendersTo(f, '<input id="id_f" type="url" name="f" maxlength="20" />') with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'"): f.clean('http://f.com') self.assertEqual('http://example.com', f.clean('http://example.com')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'"): f.clean('http://abcdefghijklmnopqrstuvwxyz.com')
class URLInputField(BaseResponseForm): answer = URLField(widget=TextInput(attrs={'class': 'text'}))
def test_urlfield_2(self): f = URLField(required=False) self.assertEqual("", f.clean("")) self.assertEqual("", f.clean(None)) self.assertEqual("http://example.com", f.clean("http://example.com")) self.assertEqual("http://www.example.com", f.clean("http://www.example.com")) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("foo") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://example") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://example.") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://.com")
class ShortenForm(Form): url = URLField(required=True) length = IntegerField(max_value=255, required=False)
def test_urlfield_not_string(self): f = URLField(required=False) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean(23)
def test_urlfield_6(self): f = URLField(required=False) self.assertEqual('http://example.com', f.clean('example.com')) self.assertEqual('', f.clean('')) self.assertEqual('https://example.com', f.clean('https://example.com'))
class SavedSearchForm(BaseUserForm): def __init__(self, *args, **kwargs): super(SavedSearchForm, self).__init__(*args, **kwargs) choices = make_choices(self.user) self.fields["email"] = ChoiceField(widget=Select(), choices=choices, initial=choices[0][0]) initial = kwargs.get("instance") # TODO: Rework text_only overrides when this is promoted to SavedSearch text_only_kwargs = { 'widget': HiddenInput(), 'initial': initial.text_only if initial else False, 'required': False } self.fields["text_only"] = BooleanField(**text_only_kwargs) autofocus_input(self, 'url') feed = URLField(widget=HiddenInput()) notes = CharField(label=_("Notes and Comments"), widget=Textarea(attrs={'placeholder': 'Comments'}), required=False) # day_of_week and day_of_month are not required in the database. # These clean functions ensure that it is required only when # the correct frequency is selected def clean_day_of_week(self): if self.cleaned_data.get('frequency', None) == 'W': if not self.cleaned_data['day_of_week']: raise ValidationError(_("This field is required.")) return self.cleaned_data['day_of_week'] def clean_day_of_month(self): if self.cleaned_data.get('frequency', None) == 'M': if not self.cleaned_data['day_of_month']: raise ValidationError(_("This field is required.")) return self.cleaned_data['day_of_month'] def clean_text_only(self): if self.cleaned_data.get('text_only', None) is None: self.cleaned_data['text_only'] = self.instance.text_only return self.cleaned_data['text_only'] def clean(self): cleaned_data = self.cleaned_data url = cleaned_data.get('url') feed = validate_dotjobs_url(url, self.user)[1] if feed: cleaned_data['feed'] = feed self._errors.pop('feed', None) else: error_msg = "That URL does not contain feed information" self._errors.setdefault('url', []).append(error_msg) self.cleaned_data['feed'] = feed return cleaned_data def clean_url(self): rss_url = validate_dotjobs_url(self.cleaned_data['url'], self.user)[1] if not rss_url: raise ValidationError(_('This URL is not valid.')) # Check if form is editing existing instance and if duplicates exist if not self.instance.pk and SavedSearch.objects.filter( user=self.user, url=self.cleaned_data['url']): raise ValidationError(_('URL must be unique.')) return self.cleaned_data['url'] def save(self, commit=True): self.instance.feed = self.cleaned_data['feed'] return super(SavedSearchForm, self).save(commit) class Meta: model = SavedSearch widgets = { 'notes': Textarea(attrs={ 'rows': 5, 'cols': 24 }), 'sort_by': RadioSelect(renderer=HorizontalRadioRenderer) } exclude = ['custom_message', 'last_action_time']
def _clean_url(url): url_field = URLField() return url_field.clean(url.strip())
def test_urlfield_strip_on_none_value(self): f = URLField(required=False, empty_value=None) self.assertIsNone(f.clean(None))
import short_url from django.conf import settings from django.forms import URLField from rest_framework import serializers from url_minion.models import ShortUrl url_field = URLField() def url_validator(url): return url_field.clean(url) class ShortUrlSerializer(serializers.ModelSerializer): url = serializers.CharField(validators=[url_validator]) def to_representation(self, instance): return {'shortened_url': f'{settings.APP_URL}/{instance.index}'} def create(self, validated_data): instance = super().create(validated_data) instance.index = short_url.encode_url(instance.id) instance.save() return instance class Meta: model = ShortUrl fields = ('url',)
def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo( f, '<input type="url" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual('http://localhost', f.clean('http://localhost')) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com.', f.clean('http://example.com.')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) self.assertEqual('http://valid-with-hyphens.com', f.clean('valid-with-hyphens.com')) self.assertEqual('http://subdomain.domain.com', f.clean('subdomain.domain.com')) self.assertEqual('http://200.8.9.10', f.clean('http://200.8.9.10')) self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('com.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://invalid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://-invalid.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.alid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com')) self.assertEqual( 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) self.assertEqual( 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean( 'www.example.com/s/http://code.djangoproject.com/ticket/13804') ) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('[a') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://[a')
class IntegrationScaffoldingForm(Form): name = CharField(max_length=80, label=_('Integration name'), widget=TextInput()) author_homepage = URLField(label=_('Author\'s homepage'), required=False) issue_tracker = URLField(label=_('Issue tracker URL'), required=False, help_text=_('Bug reports and feature requests')) categories = MultipleChoiceField(widget=HiddenInput(), disabled=True, required=True, label=_('Categories'), choices=lazy(get_categories, list), help_text=_('Hold down Ctrl and click to ' 'select multiple entries')) summary = CharField( max_length=256, label=_('Summary'), help_text= _('Short description of your app that will be rendered as short teaser' )) screenshot = URLField(max_length=256, label=_('Screenshot URL'), required=False, help_text=_('URL for integration screenshot')) screenshot_thumbnail = URLField(max_length=256, label=_('Screenshot ' 'thumbnail URL'), required=False, help_text=_('URL for integration ' 'screenshot in ' 'smaller dimensions. ' 'Must be used in combination ' 'with a larger screenshot.')) description = CharField(widget=Textarea, label=_('Description'), help_text=_('Full description of what your' ' integration ' 'does. Can contain Markdown.')) def _create_discourse_category(self, app_id: str) -> None: url = '%s/categories?api_key=%s&api_username=%s' % ( settings.DISCOURSE_URL.rstrip('/'), settings.DISCOURSE_TOKEN, settings.DISCOURSE_USER) data = { 'name': app_id.replace('_', '-'), 'color': '3c3945', 'text_color': 'ffffff' } if settings.DISCOURSE_PARENT_CATEGORY_ID: data['parent_category_id'] = settings.DISCOURSE_PARENT_CATEGORY_ID # ignore requests errors because there can be many issues and we do not # want to abort app registration just because the forum is down or # leak sensitive data like tokens or users try: requests.post(url, data=data) except requests.HTTPError: pass def save(self, user, app_id, action): if app_id is None: app_id = slugify(self.cleaned_data['name']).replace('-', '_')[:80] try: app = App.objects.get(id=app_id) if app.can_update(user) or user.is_superuser: if action == "reject" and user.is_superuser: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() app.delete() elif action == "approve" and user.is_superuser: app.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) app.save() return app_id else: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self. cleaned_data['screenshot_thumbnail'], ordering=1, app=app) screenshot.save() app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() return app_id except App.DoesNotExist: app = App.objects.create(id=app_id, owner=user, certificate=uuid.uuid1().urn) app.set_current_language('en') app.categories.set(self.cleaned_data['categories']) app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() p = App.objects.get(id=app_id) p.is_integration = True if user.is_superuser: p.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) else: send_mail( "New integration submitted", "Please review the " "integration to make " "sure it fits the " "guidelines.", settings.NEXTCLOUD_FROM_EMAIL, settings.NEXTCLOUD_INTEGRATIONS_APPROVAL_EMAILS) p.save() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self.cleaned_data['screenshot_thumbnail'], ordering=1, app=p) screenshot.save() if not p.is_integration or p.approved or user.is_superuser: return app_id
class IntegrationScaffoldingForm(Form): name = CharField(max_length=80, label=_('Integration name'), widget=TextInput()) author_homepage = URLField(label=_('Author\'s homepage'), required=False) issue_tracker = URLField(label=_('Issue tracker URL'), required=False, help_text=_('Bug reports and feature requests')) categories = MultipleChoiceField(widget=HiddenInput(), disabled=True, required=True, label=_('Categories'), choices=lazy(get_categories, list), help_text=_('Hold down Ctrl and click to ' 'select multiple entries')) summary = CharField( max_length=256, label=_('Summary'), help_text= _('Short description of your app that will be rendered as short teaser' )) screenshot = URLField(max_length=256, label=_('Screenshot URL'), required=False, help_text=_('URL for integration screenshot')) screenshot_thumbnail = URLField(max_length=256, label=_('Screenshot ' 'thumbnail URL'), required=False, help_text=_('URL for integration ' 'screenshot in ' 'smaller dimensions. ' 'Must be used in combination ' 'with a larger screenshot.')) description = CharField(widget=Textarea, label=_('Description'), help_text=_('Full description of what your' ' integration ' 'does. Can contain Markdown.')) def save(self, user, app_id, action): if app_id is None: app_id = self.cleaned_data['name'].lower().replace(" ", "_") try: app = App.objects.get(id=app_id) if app.can_update(user) or user.is_superuser: if action == "reject" and user.is_superuser: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() app.delete() elif action == "approve" and user.is_superuser: app.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) app.save() return app_id else: '''Not optimal but works''' Screenshot.objects.filter(app=app).delete() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self. cleaned_data['screenshot_thumbnail'], ordering=1, app=app) screenshot.save() app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() return app_id except App.DoesNotExist: app = App.objects.create(id=app_id, owner=user, certificate=uuid.uuid1().urn) app.set_current_language('en') app.categories.set(self.cleaned_data['categories']) app.description = self.cleaned_data['description'] app.name = self.cleaned_data['name'] app.summary = self.cleaned_data['summary'] app.website = self.cleaned_data['author_homepage'] app.issue_tracker = self.cleaned_data['issue_tracker'] app.save() p = App.objects.get(id=app_id) p.is_integration = True if user.is_superuser: p.approved = True if settings.DISCOURSE_TOKEN: self._create_discourse_category(app_id) else: send_mail( "New integration submitted", "Please review the " "integration to make " "sure it fits the " "guidelines.", settings.NEXTCLOUD_FROM_EMAIL, settings.NEXTCLOUD_INTEGRATIONS_APPROVAL_EMAILS) p.save() if self.data['screenshot']: screenshot = Screenshot.objects.create( url=self.cleaned_data['screenshot'], small_thumbnail=self.cleaned_data['screenshot_thumbnail'], ordering=1, app=p) screenshot.save() if not p.is_integration or p.approved or user.is_superuser: return app_id
class ServerForm(Form): url = URLField(required=True, help_text="https://your-server.com:4040") username = CharField(required=True) password = CharField(required=False, widget=PasswordInput(), help_text="Leave blank if not being changed.")
def test_urlfield_6(self): f = URLField(required=False) self.assertEqual("http://example.com", f.clean("example.com")) self.assertEqual("", f.clean("")) self.assertEqual("https://example.com", f.clean("https://example.com"))
def test_urlfield_2(self): f = URLField(required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://.com')
def test_urlfield_unable_to_set_strip_kwarg(self): msg = "__init__() got multiple values for keyword argument 'strip'" with self.assertRaisesMessage(TypeError, msg): URLField(strip=False)
class URLForm(ModelForm): def clean_target(self): """ Prevent redirect loop links """ # get the entered target link target = self.cleaned_data.get('target') return target # Custom target URL field target = URLField(required=True, label='Long URL (Required)', max_length=1000, widget=URLInput( attrs={ 'placeholder': 'https://yoursite.com/', 'class': 'urlinput form-control', })) # short -------------------------------------------------------------------- def unique_short(value): """ Check to make sure the short url has not been used """ try: # if we're able to get a URL with the same short url URL.objects.get(short__iexact=value) except URL.DoesNotExist as ex: return # then raise a ValidationError raise ValidationError('Short URL already exists.') # Custom short-url field with validators. short = SlugField( required=False, label='Short URL (Optional)', widget=TextInput(attrs={ 'class': 'urlinput form-control', }), validators=[unique_short], max_length=20, min_length=3, ) # expires ------------------------------------------------------------------ # Define some string date standards DAY = '1 Day' WEEK = '1 Week' MONTH = '1 Month' # CUSTOM = 'Custom Date' NEVER = 'Never' # Define a tuple of string date standards to be used as our date choices EXPIRATION_CHOICES = ( (DAY, DAY), (WEEK, WEEK), (MONTH, MONTH), (NEVER, NEVER), # (CUSTOM, CUSTOM), ) # Add preset expiration choices. expires = ChoiceField( required=True, label='Expiration (Required)', choices=EXPIRATION_CHOICES, initial=NEVER, widget=RadioSelect(attrs={'class': 'radios'}), ) def valid_date(value): """ Check if the selected date is a valid date """ # a valid date is one that is greater than today if value > timezone.now(): return # raise a ValidationError if the date is invalid else: raise ValidationError('Date must be after today.') def __init__(self, *args, **kwargs): """ On initialization of the form, crispy forms renders this layout """ # Grab that host info self.host = kwargs.pop('host', None) super(URLForm, self).__init__(*args, **kwargs) self.target_title = 'Paste the URL you would like to shorten:' self.short_title = 'Create a custom Go address:' self.expires_title = 'Set when you would like your Go address to expire:' self.action = '/newLink' class Meta: """ Metadata about this ModelForm """ # what model this form is for model = URL # what attributes are included fields = ['target']
def test_urlfield_clean_not_required(self): f = URLField(required=False) self.assertEqual(f.clean(None), "") self.assertEqual(f.clean(""), "")
def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual('http://localhost', f.clean('http://localhost')) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com.', f.clean('http://example.com.')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) self.assertEqual('http://valid-with-hyphens.com', f.clean('valid-with-hyphens.com')) self.assertEqual('http://subdomain.domain.com', f.clean('subdomain.domain.com')) self.assertEqual('http://200.8.9.10', f.clean('http://200.8.9.10')) self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('com.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://invalid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://-invalid.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.alid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com')) self.assertEqual( 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah') ) self.assertEqual( 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804') ) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('[a') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://[a')
def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual("http://localhost", f.clean("http://localhost")) self.assertEqual("http://example.com", f.clean("http://example.com")) self.assertEqual("http://example.com.", f.clean("http://example.com.")) self.assertEqual("http://www.example.com", f.clean("http://www.example.com")) self.assertEqual("http://www.example.com:8000/test", f.clean("http://www.example.com:8000/test")) self.assertEqual("http://valid-with-hyphens.com", f.clean("valid-with-hyphens.com")) self.assertEqual("http://subdomain.domain.com", f.clean("subdomain.domain.com")) self.assertEqual("http://200.8.9.10", f.clean("http://200.8.9.10")) self.assertEqual("http://200.8.9.10:8000/test", f.clean("http://200.8.9.10:8000/test")) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("foo") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://example") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://example.") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("com.") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean(".") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://.com") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://invalid-.com") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://-invalid.com") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://inv-.alid-.com") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://inv-.-alid.com") self.assertEqual("http://valid-----hyphens.com", f.clean("http://valid-----hyphens.com")) self.assertEqual( "http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah", f.clean("http://some.idn.xyzäöüßabc.domain.com:123/blah"), ) self.assertEqual( "http://www.example.com/s/http://code.djangoproject.com/ticket/13804", f.clean("www.example.com/s/http://code.djangoproject.com/ticket/13804"), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("[a") with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean("http://[a")
def test_urlfield_widget(self): f = URLField() self.assertWidgetRendersTo( f, '<input type="url" name="f" id="id_f" required>')
class PageForm(Form): title = CharField(max_length=256) description = CharField(max_length=1024) href = URLField(max_length=2084) id = CharField()
class ImportProjectsForm(Form): use = BooleanField(label='Import') name = CharField(max_length=50) url = URLField() tags = CharField(max_length=50, required=False) category = ChoiceField(choices=categories)
def test_urlfield_normalization(self): f = URLField() self.assertEqual(f.clean('http://example.com/ '), 'http://example.com/')
class S3DirectUploadForm(Form): images = URLField(widget=S3DirectWidget(dest='arquivos_cirurgia'))