def test_strip_before_checking_empty(self): """ A whitespace-only value, ' ', is stripped to an empty string and then converted to the empty value, None. """ f = CharField(required=False, empty_value=None) self.assertIsNone(f.clean(' '))
def __init__(self, grouping=IBAN_GROUPING, *args, **kwargs): kwargs.setdefault('max_length', IBAN_MAX_LENGTH) kwargs.setdefault('min_length', IBAN_MIN_LENGTH) self.grouping = grouping self.default_validators = [IBANValidator()] CharField.__init__(self, *args, **kwargs)
def make_quiz_form(quiz, select_to_radio=False): """ Generates a form on the fly based on the Quiz questions """ form_fields = OrderedDict() for question in quiz.get_questions(): AnswerModel = question.get_answer_class() model_fields = fields_for_model(AnswerModel, exclude=['userprofile', 'review']) if AnswerModel == MultipleChoiceAnswer or AnswerModel == RatingAnswer: if select_to_radio or (quiz.question_widget == quiz.RADIO_WIDGET) or (question.widget == question.RADIO_WIDGET): model_fields = fields_for_model( AnswerModel, exclude=['userprofile', 'review'], formfield_callback=multiplechoice_to_radio) # Begin Diry hack # for when radio select has for some reason not been set by fields_for_model # this happens for RatingAnswer objects # first we check if choices exist to avoid none choice fields if hasattr(model_fields['answer'], '_choices'): # then we check if the widget is still Select if isinstance(model_fields['answer'].widget, Select): # we manually make it into a Radio Select field model_fields['answer'].widget = RadioSelect() # we remove the empty answer choice usually preset in Select Fields if not model_fields['answer']._choices[0][0]: model_fields['answer']._choices.pop(0) # End Diry hack answer_field = model_fields['answer'] answer_field.required = question.required # answer_field.question = question ?? should this be included answer_field.has_image_answers = question.has_image_answers answer_field.widget_to_use = question.widget other_field = None if question.image: thumb_size = getattr(settings, 'QUESTION_LABEL_THUMBS_SIZE', "500x400") thumb = get_thumbnail(question.image.file, thumb_size) answer_field.label = format_html( "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str(question.title)) if quiz.show_question_numbers: answer_field.label = format_html( "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str("{}. {}".format(question.order, question.title))) else: this_label = question.title if quiz.show_question_numbers: this_label = "{}. {}".format(question.order, this_label) if question.description: answer_field.label = format_html("<span class='question-text-latel'>{}</span><div class='question-description'>{}</div>", smart_str( this_label), mark_safe(smart_str(question.description).replace('\n', '<br />'))) else: answer_field.label = smart_str(this_label) if question._meta.model == MultipleChoiceQuestion: answer_field.queryset = MultipleChoiceOption.objects.filter(question=question) if answer_field.queryset.filter(other=True).exists(): other_field = CharField() other_field.widget.attrs['class'] = "other-field id_answer_{}".format(question.id) other_field.label = _("If you selected Other, please specify what you meant") other_field.required = False form_fields['answer_{}'.format(question.id)] = answer_field if other_field: form_fields['other_{}'.format(question.id)] = other_field return type('QuizForm', (BaseForm,), {'base_fields': form_fields})
def test_charfield_3(self): f = CharField(max_length=10, required=False) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) msg = "'Ensure this value has at most 10 characters (it has 11).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1234567890a') self.assertEqual(f.max_length, 10) self.assertIsNone(f.min_length)
def test_charfield_strip(self): """ Values have whitespace stripped but not if strip=False. """ f = CharField() self.assertEqual(f.clean(' 1'), '1') self.assertEqual(f.clean('1 '), '1') f = CharField(strip=False) self.assertEqual(f.clean(' 1'), ' 1') self.assertEqual(f.clean('1 '), '1 ')
def test_clean_non_string(self): """CharField.clean() calls str(value) before stripping it.""" class StringWrapper: def __init__(self, v): self.v = v def __str__(self): return self.v value = StringWrapper(' ') f1 = CharField(required=False, empty_value=None) self.assertIsNone(f1.clean(value)) f2 = CharField(strip=False) self.assertEqual(f2.clean(value), ' ')
def clean(self, value): cleaned_path = CharField.clean(self, value) if value.lower().startswith(S3_ROOT): cleaned_path = s3_normpath(cleaned_path) else: cleaned_path = normpath(cleaned_path) return cleaned_path
def clean(self, value): try: if "".join(value.split()) == "": value = "UNKNOWN" return CharField.clean(self,value.strip()) except: raise ValidationError( "You provided an invalid value for your subject's race" )
def test_charfield_1(self): f = CharField() self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length)
def test_charfield_5(self): f = CharField(min_length=10, required=True) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Ensure this value has at least 10 characters (it has 5).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertIsNone(f.max_length) self.assertEqual(f.min_length, 10)
def test_using_validators_on_other_fields(self): dict_validator = validators.DictionaryValidator(words=["nostromo"], threshold=0.8) length_validator = validators.LengthValidator(min_length=2) p = CharField(validators=[dict_validator, length_validator]) p.clean("aa") with self.assertRaises(ValidationError): p.clean("a") # too short with self.assertRaises(ValidationError): p.clean("nostrilomo") # too much like nostromo
def test_charfield_2(self): f = CharField(required=False) self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) self.assertEqual('', f.clean(None)) self.assertEqual('', f.clean('')) self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length)
def get_ordering_field(self): """ Fixed get_ordering_field to not depend on self.filters because we overwrite them when accessing self.qs. """ ordering_field = super(FilterSet, self).get_ordering_field() if self._meta.order_by is True: if getattr(self, "default_order", None): choices = [(",".join(self.default_order),) * 2] else: choices = [] for field in self._meta.model._meta.get_fields(): # pylint: disable=protected-access label = getattr(field, "verbose_name", field.name.capitalize()) choices += [ (field.name, label), ("-{}".format(field.name), "{} (descending)".format(label)) ] def validator_factory(queryset): def validate_order_by(value): ordered_queryset = queryset.order_by(*value.split(",")) compiler = ordered_queryset.query.get_compiler(using=ordered_queryset.db) try: compiler.get_order_by() except FieldError: raise ValidationError("'{}' is not a valid order".format(value)) return validate_order_by ordering_field = CharField( label=ordering_field.label, required=False, widget=Select, validators=[validator_factory(self.queryset)]) ordering_field.choices = choices ordering_field.widget.choices = choices return ordering_field
def test_charfield_widget_attrs(self): """ CharField.widget_attrs() always returns a dictionary (#15912). """ # Return an empty dictionary if max_length is None f = CharField() self.assertEqual(f.widget_attrs(TextInput()), {}) self.assertEqual(f.widget_attrs(Textarea()), {}) # Otherwise, return a maxlength attribute equal to max_length f = CharField(max_length=10) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'})
class TournamentConfigureForm(ModelForm): class Meta: model = Tournament fields = ('preset_rules', 'public_info') preset_rules = ChoiceField( choices=presets_for_form(), # Tuple with (Present_Index, Preset_Name) label=_("Format Configuration"), help_text=_( "Apply a standard set of settings to match a common debate format") ) public_info = ChoiceField( choices=public_presets_for_form( ), # Tuple with (Present_Index, Preset_Name) label=_("Public Configuration"), help_text=_( "Show non-sensitive information on the public-facing side of this site, " "like draws (once released) and the motions of previous rounds")) tournament_staff = CharField( label=TournamentStaff.verbose_name, required=False, help_text=TournamentStaff.help_text, initial=_( "<strong>Tabulation:</strong> [list tabulation staff here]<br />" "<strong>Organisation:</strong> [list organising committee members here]<br />" "<strong>Adjudication:</strong> [list chief adjudicators here]"), widget=SummernoteWidget(attrs={ 'height': 150, 'class': 'form-summernote' }), ) def save(self): presets = list(all_presets()) t = self.instance # Identify + apply selected preset selected_index = self.cleaned_data["preset_rules"] selected_preset = next(p for p in presets if p.name == selected_index) selected_preferences = get_preferences_data(selected_preset, t) for preference in selected_preferences: t.preferences[preference['key']] = preference['new_value'] # Apply public info presets do_public = self.cleaned_data["public_info"] public_preset = next((p for p in presets if p.name == do_public), False) if public_preset: public_preferences = get_preferences_data(public_preset, t) for preference in public_preferences: t.preferences[preference['key']] = preference['new_value'] # Apply the credits if self.cleaned_data['tournament_staff'] != self.fields[ 'tournament_staff'].initial: t.preferences[ "public_features__tournament_staff"] = self.cleaned_data[ "tournament_staff"] # Create break rounds (need to do so after we know teams-per-room) open_break = BreakCategory.objects.filter(tournament=t, is_general=True).first() # Check there aren't already break rounds (i.e. when importing demos) if open_break and not t.break_rounds().exists(): auto_make_break_rounds(open_break, t, False)
class AgendaItemForm(ModelForm): hour = CharField(widget=HiddenInput(), required=False) class Meta: model = AgendaItem fields = [ "helper", "helper_confirmed", "hour", "meeting", "meeting_confirmed", "room", ] def clean(self) -> Dict[str, Union[bool, Helper, Meeting, Room, str]]: cleaned_data = super().clean() start = self._get_hour(cleaned_data.get("hour")) proposal = cleaned_data["meeting"].proposal end = start + timedelta(minutes=proposal.duration_minutes) possible_conflicts = AgendaItem.objects.filter( Q(meeting__start_time__gt=start, meeting__start_time__lt=end) | Q(meeting__end_time__gt=start, meeting__end_time__lt=end) | Q(meeting__start_time__lte=start, meeting__end_time__gte=end) ).exclude(id=self.instance.pk) conflicted_item = possible_conflicts.filter(room=cleaned_data["room"]).last() if conflicted_item and conflicted_item != self.instance: raise ValidationError( _("There's already an agenda item in this time slot.") ) time_slots = cleaned_data["room"].festival.time_slots start_slots = time_slots.filter( start_time__lte=start, end_time__gt=start ).count() end_slots = time_slots.filter(start_time__lt=end, end_time__gte=end).count() if start_slots != 1 or end_slots != 1: raise ValidationError( _( f"Wrong time slots. Slots found: start: {start_slots}, " f"end: {end_slots} (both should be 1)" ) ) user_lookup = {} if proposal.speaker_user: user_lookup["meeting__proposal__speaker_user"] = proposal.speaker_user else: user_lookup["meeting__proposal__speaker_name"] = proposal.speaker_name users_meetings = possible_conflicts.filter(**user_lookup) if users_meetings.exists(): raise ValidationError(_("User already has a meeting at this hour")) if proposal.speaker_user and possible_conflicts.filter( helper__user=proposal.speaker_user ): raise ValidationError(_("User is on helper duty during this time")) return cleaned_data def _get_hour(self, cleaned_hour: Optional[str]) -> datetime: if self.instance and self.instance.pk: return cast(datetime, self.instance.meeting.start_time) if cleaned_hour: return strphour(cleaned_hour) raise ValidationError(_("Missing hour field value"))
def test_null_characters_prohibited(self): f = CharField() msg = 'Null characters are not allowed.' with self.assertRaisesMessage(ValidationError, msg): f.clean('\x00something')
class UserLoginForm(Form): login = CharField() password = CharField(widget=PasswordInput)
class ModelForm(Form): id = CharField( label="Model ID", max_length=80, required=True, )
class AddTagForm(Form): name = CharField(max_length=64, label=_('Name'))
class JSONForm(Form): name = CharField(max_length=2) json_field = JSONField()
class RuleForm(DefaultForm): id = CharField( label="SBML short rule", max_length=80, required=True, )
def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) if self.request is None: raise ValueError("'request' kwargs is required.") self.pod = kwargs.pop("pod", None) if self.pod is None: raise ValueError("'pod' kwargs is required.") super(ComposeMachineForm, self).__init__(*args, **kwargs) # Build the fields based on the pod and current pod hints. self.fields["cores"] = IntegerField(min_value=1, max_value=self.pod.hints.cores, required=False) self.initial["cores"] = 1 self.fields["memory"] = IntegerField(min_value=1024, max_value=self.pod.hints.memory, required=False) self.initial["memory"] = 1024 self.fields["architecture"] = ChoiceField( choices=[(arch, arch) for arch in self.pod.architectures], required=False, ) self.initial["architecture"] = self.pod.architectures[0] if self.pod.hints.cpu_speed > 0: self.fields["cpu_speed"] = IntegerField( min_value=300, max_value=self.pod.hints.cpu_speed, required=False, ) else: self.fields["cpu_speed"] = IntegerField(min_value=300, required=False) def duplicated_hostname(hostname): if Node.objects.filter(hostname=hostname).exists(): raise ValidationError( 'Node with hostname "%s" already exists' % hostname) self.fields["hostname"] = CharField( required=False, validators=[duplicated_hostname, validate_hostname]) self.initial["hostname"] = make_unique_hostname() self.fields["domain"] = ModelChoiceField(required=False, queryset=Domain.objects.all()) self.initial["domain"] = Domain.objects.get_default_domain() self.fields["zone"] = ModelChoiceField(required=False, queryset=Zone.objects.all()) self.initial["zone"] = Zone.objects.get_default_zone() self.fields["pool"] = ModelChoiceField( required=False, queryset=ResourcePool.objects.all()) self.initial["pool"] = self.pod.pool self.fields["storage"] = CharField(validators=[storage_validator], required=False) self.initial["storage"] = "root:8(local)" self.fields["interfaces"] = LabeledConstraintMapField( validators=[interfaces_validator], label="Interface constraints", required=False, ) self.initial["interfaces"] = None self.fields["skip_commissioning"] = BooleanField(required=False) self.initial["skip_commissioning"] = False self.allocated_ips = {}
class SomeForm(Form): username = CharField(max_length=10, label=gettext_lazy('username'))
class TextInputAnswer(BaseAnswerForm): answer = CharField()
class TextAreaAnswer(BaseAnswerForm): answer = CharField(widget=Textarea)
class SeedshipMQTTForm(Form): #validators = {[validators.DecimalValidator(20, 10)]} topic = CharField(widget=TextInput(attrs={"disabled": True})) message = CharField() retain = BooleanField(widget=HiddenInput()) qos = ChoiceField(widget=HiddenInput(attrs={"hidden": True}), choices=[("0", "0"), ("1", "1"), ("2", "2")])
class CreateForm(Form): q = CharField(label='Search', min_length=1, max_length=20)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["early_field"] = CharField(required=False)
class CreateForm(Form): title = CharField(label= 'Enter title',min_length=1, max_length=30) text = CharField(label='Enter text', max_length=1024)
def test_disabled_has_changed(self): f = MultiValueField(fields=(CharField(), CharField()), disabled=True) self.assertIs(f.has_changed(['x', 'x'], ['y', 'y']), False)
class EventForm(DefaultForm): id = CharField( label="SBML short Event", max_length=80, required=True, )
def to_python(self, value): value = CharField.to_python(self, value) if value is not None: return clean_iban(value)
class UserIdFilter(django_filters.Filter): field = CharField()
def clean(self, value): return normpath(CharField.clean(self, value))
class AForm(Form): name = CharField(max_length=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].required = True
class TaskForm(ModelForm): problem_category = ModelChoiceField(queryset=TaskCategory.objects.filter( stage=TaskCategory.Stage.INITIAL_ASSESSMENT), required=False, label="Problem category") resolution_category = ModelChoiceField( queryset=TaskCategory.objects.filter( stage=TaskCategory.Stage.COMPLETION), required=False, label="Resolution category") action = ChoiceField(choices=[('create', 'create'), ('update', 'update'), ('resolve', 'resolve')], label="Action") description = CharField(required=False, label="Description") class Meta: model = Task fields = [ 'tool', 'urgency', 'estimated_resolution_time', 'force_shutdown', 'safety_hazard' ] def __init__(self, user, *args, **kwargs): super(TaskForm, self).__init__(*args, **kwargs) self.user = user self.fields['tool'].required = False self.fields['urgency'].required = False def clean_description(self): return self.cleaned_data['description'].strip() def clean(self): if any(self.errors): return super(TaskForm, self).clean() action = self.cleaned_data['action'] if action == 'create': if not self.cleaned_data['description']: raise ValidationError('You must describe the problem.') if action == 'resolve': if self.instance.cancelled or self.instance.resolved: raise ValidationError( "This task can't be resolved because it is marked as 'cancelled' or 'resolved' already." ) def save(self, commit=True): instance = super(TaskForm, self).save(commit=False) action = self.cleaned_data['action'] description = self.cleaned_data['description'] instance.problem_category = self.cleaned_data['problem_category'] now = timezone.now() if action == 'create': instance.problem_description = description instance.urgency = Task.Urgency.HIGH if self.cleaned_data[ 'force_shutdown'] or self.cleaned_data[ 'safety_hazard'] else Task.Urgency.NORMAL instance.creator = self.user if action == 'update': instance.last_updated = timezone.now() instance.last_updated_by = self.user instance.cancelled = False instance.resolved = False if description: preface = f'On {format_datetime(now)} {self.user.get_full_name()} updated this task:\n' if instance.progress_description is None: instance.progress_description = preface + description else: instance.progress_description += '\n\n' + preface + description instance.progress_description = instance.progress_description.strip( ) if action == 'resolve': instance.cancelled = False instance.resolved = True instance.resolution_time = now instance.resolver = self.user if 'resolution_category' in self.cleaned_data: instance.resolution_category = self.cleaned_data[ 'resolution_category'] if 'description' in self.cleaned_data: if instance.resolution_description: preface = f'On {format_datetime(now)} {self.user.get_full_name()} updated the resolution information:\n' instance.resolution_description = ( instance.resolution_description + '\n\n' + preface + self.cleaned_data['description']).strip() else: instance.resolution_description = self.cleaned_data[ 'description'] return super(TaskForm, self).save(commit=True)
def test_charfield_widget_attrs(self): """ CharField.widget_attrs() always returns a dictionary (#15912). """ # Return an empty dictionary if max_length and min_length are both None. f = CharField() self.assertEqual(f.widget_attrs(TextInput()), {}) self.assertEqual(f.widget_attrs(Textarea()), {}) # Return a maxlength attribute equal to max_length. f = CharField(max_length=10) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'}) # Return a minlength attribute equal to min_length. f = CharField(min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'minlength': '5'}) # Return both maxlength and minlength when both max_length and # min_length are set. f = CharField(max_length=10, min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10', 'minlength': '5'})
class InviteUserForm(Form): additional_message = CharField(label=_('optional additional message'), max_length=300, required=False, widget=Textarea(attrs={'rows': 8, 'cols': 80}))
class NewUserForm(EmailUserCreationForm): access_area = CharField(widget=Select(choices=[]), required=False) class Meta: model = get_user_model() fields = ("email", "is_superuser", "access_level", "access_area")
class DRMMForm(QueryForm): name = "DRMM" nbins = IntegerField(required=True) nodes = IntegerField(required=True) histType = CharField(required=True) gateType = CharField(required=True)
class PinChangeForm(Form): pin = CharField(widget=PasswordInput(), required=False)
class QuestionForm(BetterModelForm): q = CharField(widget=Textarea(attrs={'rows': '1'}), label="Question") class Meta: model = Question
class ChangeDataForm(Form): first_name = CharField(max_length=100, label='First Name', widget=TextInput( attrs={'placeholder': 'First Name', 'class': '', 'style': ''})) last_name = CharField(max_length=100, label='Last Name', widget=TextInput( attrs={'placeholder': 'Last Name', 'class': '', 'style': ''}))
class JsonForm(Form): name = CharField() jfield = forms.JSONField(disabled=True)
class JsonForm(Form): name = CharField(max_length=2) jfield = forms.JSONField()
class QueryForm(forms.Form): """ We don't really need a form, but if we use one django will do all the grunt work of converting strings to numbers and booleans e.t.c """ FORM_CLASSES = {} target_index = CharField(required=True) dataparallel = CharField(required=True) batch = IntegerField(required=True) benchmark = CharField(required=True) collection = CharField(required=True) expid = CharField(required=True) fold = CharField(required=True) index = CharField(required=True) indexstops = BooleanField(required=False) itersize = IntegerField(required=True) lr = FloatField(required=True) maxdoclen = IntegerField(required=True) maxqlen = IntegerField(required=True) reranker = CharField(required=True) niters = IntegerField(required=True) predontrain = BooleanField(required=False) searcher = CharField(required=True) rundocsonly = BooleanField(required=False) sample = CharField(required=True) seed = IntegerField(required=True) softmaxloss = BooleanField(required=False) stemmer = CharField(required=True) query = CharField(required=True) gradacc = IntegerField(required=True) @classmethod def register(cls, formcls): name = formcls.name if name in cls.FORM_CLASSES and cls.FORM_CLASSES[name] != formcls: raise RuntimeError( f"encountered two Forms with the same name: {name}") cls.FORM_CLASSES[name] = formcls return formcls
def test_charfield_widget_attrs(self): """ CharField.widget_attrs() always returns a dictionary and includes minlength/maxlength if min_length/max_length are defined on the field and the widget is not hidden. """ # Return an empty dictionary if max_length and min_length are both None. f = CharField() self.assertEqual(f.widget_attrs(TextInput()), {}) self.assertEqual(f.widget_attrs(Textarea()), {}) # Return a maxlength attribute equal to max_length. f = CharField(max_length=10) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'}) # Return a minlength attribute equal to min_length. f = CharField(min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'minlength': '5'}) # Return both maxlength and minlength when both max_length and # min_length are set. f = CharField(max_length=10, min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(HiddenInput()), {})
class SongForm(ModelForm): cuex = CharField(widget=LinkWidget, required=False) scld = CharField(widget=LinkWidget, required=False) midi = CharField(widget=LinkWidget, required=False) playback_mp3 = CharField(widget=LinkWidget, required=False) recording_ogg = CharField(widget=LinkWidget, required=False) recording_mp3 = CharField(widget=LinkWidget, required=False) author_songs = CharField(widget=DirectLinkWidget, required=False) song_Embed_Description = CharField(widget=DirectLinkWidget, required=False) user_info = CharField(widget=DirectLinkWidget, required=False) song_counters = CharField(widget=DirectLinkWidget, required=False) def __init__(self, *args, **kwargs): super(SongForm, self).__init__(*args, **kwargs) self.set_initial_values() def set_initial_values(self): api_base_url = "https://my.scorecloud.com/api/2.0/song/" if self.instance.source_type == "recording": self.fields[ 'recording_ogg'].initial = api_base_url + self.instance.song_id + "/recording.ogg" self.fields[ 'recording_mp3'].initial = api_base_url + self.instance.song_id + "/recording.mp3" self.fields[ 'cuex'].initial = api_base_url + self.instance.song_id + "/cuex" self.fields[ 'scld'].initial = api_base_url + self.instance.song_id + "/song.scld" self.fields[ 'midi'].initial = api_base_url + self.instance.song_id + "/playback.midi" self.fields[ 'playback_mp3'].initial = api_base_url + self.instance.song_id + "/playback.mp3" self.fields['author_songs'].initial = get_song_author_link( self.instance.author) self.fields['song_Embed_Description'].initial = get_song_meta_link( self.instance) self.fields['user_info'].initial = get_user_info_link( self.instance.author) self.fields['song_counters'].initial = get_song_counters_link( self.instance) class Meta: model = Song fields = ( 'song_id', 'source_type', 'title', 'creation_date', 'is_active', 'is_shared', 'is_deleted', 'song_Embed_Description', 'is_unsorted', 'current_scld_id', 'meta', 'current_revision_id', 'last_update', 'permissions', 'is_public', 'popularity', 'maturity', )