class WriteItInstanceCreateFormPopitUrl(ModelForm, PopitParsingFormMixin): popit_url = URLField( label=_('Popolo URL'), help_text= _("Example: https://cdn.rawgit.com/everypolitician/everypolitician-data/1460373/data/Abkhazia/Assembly/ep-popolo-v1.0.json" ), required=True, ) class Meta: model = WriteItInstance fields = ('owner', 'name', 'popit_url') def relate_with_people(self): if self.cleaned_data['popit_url']: popit_url = self.cleaned_data['popit_url'] self.instance.load_persons_from_popolo_json(popit_url) def save(self, commit=True): instance = super(WriteItInstanceCreateFormPopitUrl, self)\ .save(commit=commit) if commit: self.relate_with_people() return instance
class UpstreamSettingsForm(HierarkeyForm): downstream_upstream_url = URLField( label=_("Upstream URL"), help_text=_("URL of your schedule.xml"), required=True, ) downstream_interval = IntegerField( min_value=5, label=_("Interval"), help_text=_("Checking interval in minutes.") ) downstream_checking_time = ChoiceField( choices=( ("event", _("Check only during event time")), ("always", _("From now until one day after the event ends")), ), label=_("Schedule check time"), widget=RadioSelect, ) downstream_discard_after = CharField( label=_("Discard version name after"), help_text=_( "Everything after the first occurence of the entered string " "in schedule version will be discarded. Leave empty if you " "want to keep the full schedule version" ), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.event = kwargs.get("obj")
class AccountForm(ModelForm): avatar_url = URLField(required=False) class Meta: model = Account fields = ['balance', 'free_access', 'no_logs', 'avatar'] def clean_avatar(self): cleaned_data = self.cleaned_data['avatar'] if cleaned_data not in [None, False]: if cleaned_data.size > 5242880: #8MB raise ValidationError("Bild zu groß (>8MB", 'FILE_TO_LARGE') return cleaned_data def clean(self): #run the standard clean method first cleaned_data = super(AccountForm, self).clean() if cleaned_data['avatar_url'] is not "": print(cleaned_data['avatar']) img_file = ContentFile( get(self.cleaned_data['avatar_url']).content) try: img = Image.open(img_file) avatar = cleaned_data['avatar'] avatar.save("downloaded_avatar", img_file, save=False) self.clean_avatar() except OSError: #linked url looks not like an image raise ValidationError('URL ist kein Bild', 'URL_NO_IMAGE') except AttributeError: raise ValidationError('Erst einmalig ein Bild uploaden', 'NO_PREV_IMAGE') return cleaned_data
class BootstrapYoutubeForm(ModelForm): url = URLField( label=_("YouTube URL"), widget=widgets.URLInput(attrs={'size': 50}), ) def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if instance: videoid = instance.glossary.get('videoid') if videoid: parts = ParseResult('https', 'youtu.be', videoid, '', '', '') initial = {'url': urlunparse(parts)} kwargs.update(initial=initial) super(BootstrapYoutubeForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(BootstrapYoutubeForm, self).clean() url = cleaned_data.pop('url', None) if url: parts = urlparse(url) match = re.search(r'([^/]+)$', parts.path) if match: cleaned_data['glossary']['videoid'] = match.group(0) return cleaned_data raise ValidationError(_("Please enter a valid YouTube URL"))
def test_urlfield_clean_invalid(self): f = URLField() tests = [ "foo", "com.", ".", "http://", "http://example", "http://example.", "http://.com", "http://invalid-.com", "http://-invalid.com", "http://inv-.alid-.com", "http://inv-.-alid.com", "[a", "http://[a", # Non-string. 23, # Hangs "forever" before fixing a catastrophic backtracking, # see #11198. "http://%s" % ("X" * 60, ), # A second example, to make sure the problem is really addressed, # even on domains that don't fail the domain label length check in # the regex. "http://%s" % ("X" * 200, ), # urlsplit() raises ValueError. "////]@N.AN", # Empty hostname. "#@A.bO", ] msg = "'Enter a valid URL.'" for value in tests: with self.subTest(value=value): with self.assertRaisesMessage(ValidationError, msg): f.clean(value)
def test_urlfield_clean_required(self): f = URLField() msg = "'This field is required.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(None) with self.assertRaisesMessage(ValidationError, msg): f.clean("")
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
class TaskForm(ModelForm): name = CharField(widget=HiddenInput(), required=False) id = IntegerField(widget=HiddenInput(), required=False) search_query = CharField( label='Поисковый запрос', help_text='*по этому запросу мы будем искать сайт в Яндексе') target_url = URLField( label='Целевой сайт', help_text=f'*на этом сайте мы будем проводить больше всего времени ' f'и выполнять целевые действия') competitor_sites = CharField( label="Сайты конкурентов (в столбик)", widget=Textarea(attrs={}), help_text='*эти сайты мы будем быстро покидать') city = CharField(label='Указать населённый пункт') delay = IntegerField(label='Задержка', help_text='Запускать не чаще, чем раз в n минут') launches_per_day = IntegerField( label='Количество запусков в день', help_text= 'Максимальное количество запусков в день (0 — без ограничений)') class Meta: model = Task fields = [ 'name', 'id', 'search_query', 'target_url', 'competitor_sites', 'city', 'delay', 'launches_per_day' ] widgets = { 'city': TextInput(attrs={'name': 'city'}), }
class PageForm(Form): title = CharField(max_length=256) description = CharField(max_length=1024) href = URLField(max_length=2084) date_published = DateField() id = CharField()
class ActEditDraftForm(ModelForm): required_css_class = 'required' error_css_class = 'error' act_duration = DurationFormField( required=False, help_text=act_help_texts['act_duration'] ) track_duration = DurationFormField( required=False, help_text=act_help_texts['track_duration'], label=act_bid_labels['track_duration'] ) track_artist = CharField(required=False) track_title = CharField(required=False) shows_preferences = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=act_shows_options, label=act_bid_labels['shows_preferences'], help_text=act_help_texts['shows_preferences'], required=False ) other_performance = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=act_other_perf_options, label=act_bid_labels['other_performance'], help_text=act_help_texts['other_performance'], required=False ) video_link = URLField( widget=URLInput(attrs={'placeholder': 'http://'}), help_text=act_help_texts['video_link'], label=act_bid_labels['video_link'], required=False ) b_conference = HiddenInput() class Meta: model = Act fields = [ 'performer', 'shows_preferences', 'other_performance', 'b_title', 'track_title', 'track_artist', 'track_duration', 'act_duration', 'video_link', 'video_choice', 'b_description', 'why_you', 'b_conference', 'act_duration', 'track_duration', 'track_artist', 'track_title'] labels = act_bid_labels help_texts = act_help_texts widgets = {'b_conference': HiddenInput()}