class TestForm(forms.Form): """A Test Form with a field that contains a RelatedRepositoryWidget.""" my_multiselect_field = forms.ModelMultipleChoiceField( queryset=Repository.objects.filter(visible=True).order_by('name'), label=('Repositories'), required=False, widget=RelatedRepositoryWidget())
class SingleValueTestForm(forms.Form): """A Test Form with a field that contains a RelatedRepositoryWidget. RelatedRepositoryWidget is defined as setting multivalued to False.""" my_select_field = forms.ModelMultipleChoiceField( queryset=Repository.objects.filter(visible=True).order_by('name'), label=('Repositories'), required=False, widget=RelatedRepositoryWidget(multivalued=False))
class LocalSiteTestForm(forms.Form): """A Test Form with a field that contains a RelatedRepositoryWidget. The RelatedRepositoryWidget is defined to have a local_site_name.""" my_multiselect_field = forms.ModelMultipleChoiceField( queryset=Repository.objects.filter(visible=True).order_by('name'), label=('Repositories'), required=False, widget=RelatedRepositoryWidget(local_site_name='supertest'))
class WebHookTargetForm(LocalSiteAwareModelFormMixin, forms.ModelForm): """A form for creating and updating WebHookTargets.""" url = CharField(label=_('URL'), validators=[URLValidator()], widget=forms.widgets.URLInput(attrs={'size': 100})) repositories = forms.ModelMultipleChoiceField( label=_('Repositories'), required=False, queryset=Repository.objects.filter(visible=True).order_by('name'), widget=RelatedRepositoryWidget()) def clean_extra_data(self): """Ensure that extra_data is a valid value. Returns: unicode: Either a non-zero length string of JSON-encoded extra data or None. """ return self.cleaned_data['extra_data'] or None def clean_events(self): events = self.cleaned_data['events'] if '*' in events: events = ['*'] return events def clean(self): """Validate the state of the entire form. Returns: The cleaned form data. """ super(WebHookTargetForm, self).clean() custom_content = self.cleaned_data.get('custom_content', '') self.cleaned_data['use_custom_content'] = len(custom_content) > 0 apply_to = self.cleaned_data.get('apply_to') if (apply_to != WebHookTarget.APPLY_TO_SELECTED_REPOS or 'repositories' not in self.cleaned_data): self.cleaned_data['repositories'] = Repository.objects.none() return self.cleaned_data class Meta: model = WebHookTarget widgets = { 'apply_to': forms.widgets.RadioSelect(), } error_messages = { 'repositories': { 'invalid_choice': _('A repository with ID %(value)s was not ' 'found.'), 'invalid_pk_value': _('"%(pk)s" is an invalid repository ID.'), }, } fields = '__all__'
def __init__(self, form_row, admin_field): """Initialize the field wrapper. Args: form_row (ChangeFormRow): The parent row containing the field. admin_field (django.contrib.admin.helpers.AdminField): The administration field wrapper containing state for this field. """ bound_field = admin_field.field has_field_first = False show_errors = False is_checkbox = getattr(admin_field, 'is_checkbox', False) is_readonly = getattr(admin_field, 'is_readonly', False) classes = ['rb-c-form-field'] if is_readonly: classes.append('-is-read-only') errors = [] else: form_field = bound_field.field errors = admin_field.errors() if form_field.required: classes.append('-is-required') if errors: classes.append('-has-errors') show_errors = True if isinstance(form_field, forms.ModelMultipleChoiceField): widget = form_field.widget model = form_field.queryset.model if type(widget) is forms.ModelMultipleChoiceField.widget: # This is a default widget for a model multi-choice field. # Let's see if we use a better default. if model is User: form_field.widget = RelatedUserWidget() elif model is Group: form_field.widget = RelatedGroupWidget() elif model is Repository: form_field.widget = RelatedRepositoryWidget() else: # We can at least use the filtered selector. form_field.widget = FilteredSelectMultiple( form_field.label, is_stacked=False) if type(widget) is not widget: # We've replaced the widget, so get rid of the old bound # help text while we're at it. bound_field.help_text = None if form_row.is_multi_line: classes.append('field-%s' % bound_field.name) elif is_checkbox: classes.append('-has-input-first') has_field_first = True self.admin_field = admin_field self.classes = ' '.join(classes) self.errors = errors self.field = bound_field self.has_field_first = has_field_first self.is_checkbox = is_checkbox self.is_first = admin_field.is_first self.is_readonly = is_readonly self.show_errors = show_errors
class DefaultReviewerForm(LocalSiteAwareModelFormMixin, forms.ModelForm): name = forms.CharField(label=_("Name"), max_length=64, widget=forms.TextInput(attrs={'size': '30'})) file_regex = forms.CharField( label=_("File regular expression"), max_length=256, widget=forms.TextInput(attrs={'size': '60'}), validators=[regex_validator], help_text=_('File paths are matched against this regular expression ' 'to determine if these reviewers should be added.')) people = forms.ModelMultipleChoiceField( queryset=User.objects.filter(is_active=True), label=_('Default users'), required=False, widget=RelatedUserWidget(), error_messages={ 'invalid_choice': _('A user with ID %(value)s was not found.'), 'invalid_pk_value': _('"%(pk)s" is an invalid user ID.'), }) repository = forms.ModelMultipleChoiceField( label=_('Repositories'), required=False, queryset=Repository.objects.filter(visible=True).order_by('name'), help_text=_('The list of repositories to specifically match this ' 'default reviewer for. If left empty, this will match ' 'all repositories.'), widget=RelatedRepositoryWidget(), error_messages={ 'invalid_choice': _('A repository with ID %(value)s was not ' 'found.'), 'invalid_pk_value': _('"%(pk)s" is an invalid repository ID.'), }) groups = forms.ModelMultipleChoiceField( label=_('Default groups'), required=False, queryset=Group.objects.filter(visible=True).order_by('name'), widget=RelatedGroupWidget()) def clean(self): try: validate_users(self, 'people') except ValidationError as e: self._errors['people'] = self.error_class(e.messages) try: validate_review_groups(self, 'groups') except ValidationError as e: self._errors['groups'] = self.error_class(e.messages) try: validate_repositories(self, 'repository') except ValidationError as e: self._errors['repository'] = self.error_class(e.messages) return super(DefaultReviewerForm, self).clean() class Meta: model = DefaultReviewer error_messages = { 'groups': { 'invalid_choice': _('A group with ID %(value)s was not ' 'found.'), 'invalid_pk_value': _('"%(pk)s" is an invalid group ID.'), }, } fields = '__all__'