我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用django.forms.URLField()。
def sanitise_url(url): if url.strip() == "": raise ValidationError("Empty URL entered.") # verify if this is a valid GitHub url url_form_field = URLField() try: url = url_form_field.clean(url) if "github" not in url: raise ValidationError('Invalid GitHub URL entered: %s' % (url)) # - if entered url has a tailing '/', remove it if url[-1] == '/': url = url[:-1] # - strip out '.git' if it exists in the URL if url.endswith('.git'): url = url[0:-4] return url except ValidationError: raise ValidationError('Invalid GitHub URL entered: %s' % (url))
def __init__(self, *args, **kwargs): self.page=kwargs.pop('page') super(QuestionForm, self).__init__(*args, **kwargs) for p in Question.objects.filter(page=self.page): if p.id ==2: self.fields['url_field'] = forms.URLField(initial="http://",required = True) self.fields['url_field'].label = p.question self.fields['url_field'].page = p.page else: self.fields['extra_field_{index}'.format(index=p.id)] = forms.CharField(widget=forms.Textarea,required = True) self.fields['extra_field_{index}'.format(index=p.id)].label = p.question self.fields['extra_field_{index}'.format(index=p.id)].page = p.page
def __init__(self, verbose_name=None, name=None, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 200) super(URLField, self).__init__(verbose_name, name, **kwargs)
def deconstruct(self): name, path, args, kwargs = super(URLField, self).deconstruct() if kwargs.get("max_length") == 200: del kwargs['max_length'] return name, path, args, kwargs
def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. defaults = { 'form_class': forms.URLField, } defaults.update(kwargs) return super(URLField, self).formfield(**defaults)
def _clean_url(url): url_field = URLField() return url_field.clean(url.strip())
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
def validate_url(url): protocols=[ 'http://', 'https://' ] flag=0 url_form_field = URLField() email_field = EmailField() try : email_field.clean(url) except ValidationError: if url!='': for protocol in protocols: n=len(protocol) if url[0:n]==protocol: flag=1 break if flag==0: flag1=1 for protocol in protocols: new_url = protocol+url try: new_url == url_form_field.clean(new_url) except ValidationError: flag1=0 else: url=new_url break if flag1==1: return True,url return False,url return True,url return False,url else: return False,url
def validate_url(url): url_form_field = URLField() try: url = url_form_field.clean(url) except ValidationError: return False return True
def test_should_url_convert_string(): assert_conversion(forms.URLField, graphene.String)
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a URL property. This defaults to a URLField instance. """ defaults = {'form_class': forms.URLField} defaults.update(kwargs) return super(LinkProperty, self).get_form_field(**defaults)
def to_python(self, value): # Call grandparent method (CharField) to get string value. value = super(forms.URLField, self).to_python(value) # If it's a PPA locator, return it, else run URL pythonator. match = re.search(URLOrPPAValidator.ppa_re, value) return value if match else super().to_python(value)
def formfield(self, **kwargs): defaults = { 'form_class': URLOrPPAFormField, } defaults.update(kwargs) return super(URLField, self).formfield(**defaults)
def deconstruct(self): name, path, args, kwargs = super(URLField, self).deconstruct() if kwargs.get("max_length", None) == 200: del kwargs['max_length'] return name, path, args, kwargs
def event(wf_module, **kwargs): #number of rows we want to retrieve from Enigma. If you leave this blank/let it use the default, #you get all of 0 rows, so it should have a value > 0. wf_module.set_busy(notify=False) try: num_rows = int(wf_module.get_param_string("num_rows")) except ValueError: wf_module.set_error("The number of rows specified must be an integer, but it's {}." .format(wf_module.get_param_string("num_rows"))) return None # We can get one of two _types_ of Enigma URLs here: # - any URL with the .com TLD indicates that the URL is publicly browsable, and so we'll extract # the name of the dataset, construct the URL, and make a call using our API key. # - any URL with the .io TLD indicates that the URL is probably already using the API, so we we can$ # simply send off the request to Enigma. url = wf_module.get_param_string('enigma_url') url_form_field = URLField() try: url = url_form_field.clean(url) except ValidationError: wf_module.set_error('Invalid URL entered: {}'.format((url))) return #let's break the url down to its components split_url = urlsplit(url) netloc = split_url.netloc # quick basic validation: ensure it's an Enigma URL$ if netloc.split(".")[1].lower() != 'enigma': wf_module.set_error("The URL entered, {}, is not an Enigma URL.".format(netloc)) return None # there's no point going any further for obvious reasons # quick basic validation: ensure the TLD is .com or .io. if netloc.split(".")[2].lower() not in ["com", "io"]: wf_module.set_error("The top-level domain specified has to be .com or .io, but " + " the top-level domain in the URL received is {}.".format(netloc.split(".")[2])) return None # there's no point going any further for obvious reasons # Can wrap this around a single try because only one or the other will be called. try: if netloc.endswith("io"): data = handle_dotio_url(wf_module, url, split_url, num_rows) else: # this has to be ".com" as we've already done the check above for dodgy URLs. # this returns the Pandas table. data = handle_dotcom_url(wf_module, url, split_url, num_rows) except Exception as ex: wf_module.set_error("Caught error whilst attempting to retrieve details from Enigma: {}".format(str(ex))) # If we have got this far, and not run into any issues, we should do some data versioning magic. if wf_module.status != wf_module.ERROR: wf_module.set_ready(notify=False) csv_data = data.to_csv(index=False) updated = wf_module.auto_update_data or event.get('type') == 'click' save_fetched_table_if_changed(wf_module, csv_data, auto_change_version=updated)