class TaggingAppDataForm(AppDataForm): public_tags = ModelMultipleChoiceField(Tag.objects.all()) admin_tags = ModelMultipleChoiceField(Tag.objects.all()) admin_fieldsets = [('Taggingzs!', { 'fields': [('tagging.public_tags', 'tagging.admin_tags')] })]
def __init__(self, *args, **kwargs): city_object = kwargs.pop('city_object', None) super(FilterForm, self).__init__(*args, **kwargs) self.fields['term_search'].initial = '30' if city_object: all_locations = Sublocality.objects.filter(city__id=city_object.id) big_sublocality = BigSublocality.objects.filter( city_id=city_object.id).order_by('id') all_metro = Metro.objects.filter(city__id=city_object.id) metro_lines = MetroLine.objects.filter(city__id=city_object.id) self.fields['province'] = ModelMultipleChoiceField( label=u'Областной центр', queryset=all_locations.filter(in_city=False), widget=CheckboxSelectMultiple(attrs={'form': 'search_query'})) self.fields['bigsubloc'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple(attrs={'form': 'search_query'}), queryset=big_sublocality) for i, item in enumerate(big_sublocality): self.fields[str(i) + 'subloc'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple( attrs={'form': 'search_query'}), queryset=all_locations.filter(big_sublocality=item.id)) # self.fields['sublocality'] = ModelMultipleChoiceField( # widget=CheckboxSelectMultiple(attrs={'form':'search_query'}), # queryset=all_locations) for i, item in enumerate(metro_lines): self.fields[str(i) + 'metro_line'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple( attrs={'form': 'search_query'}), queryset=all_metro.filter( line=item.id).order_by('sequence_number'))
def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': self.verbose_name, 'help_text': self.help_text, 'widget': FilteredSelectMultiple(self.verbose_name, False)} defaults.update(kwargs) return ModelMultipleChoiceField(**defaults)
class ProductForm(EntangledModelForm): name = fields.CharField() tenant = ModelChoiceField(queryset=get_user_model().objects.all(), empty_label=None) active = fields.BooleanField() color = fields.CharField() size = fields.ChoiceField(choices=[ ('s', "Small"), ('m', "Medium"), ('l', "Large"), ]) categories = ModelMultipleChoiceField(queryset=Category.objects.all(), required=False) class Meta: model = Product untangled_fields = ['name'] entangled_fields = { 'properties': ['tenant', 'active', 'color', 'size', 'categories'] } retangled_fields = { 'color': 'extra.variants.color', 'size': 'extra.variants.size', 'tenant': 'ownership.tenant', 'categories': 'extra.categories' }
class UserUpdateForm(UserChangeForm): """ Data entry form - fEMRUser """ password = None groups = ModelMultipleChoiceField( queryset=Group.objects.exclude(name="fEMR Admin").exclude( name="Manager"), required=True, ) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields["campaigns"].queryset = filter_campaigns_for_instances( user) class Meta: model = fEMRUser fields = [ "first_name", "last_name", "email", "username", "campaigns", "groups", ]
class fEMRAdminUserForm(UserCreationForm): """ Data entry form - fEMRUser """ groups = ModelMultipleChoiceField( queryset=Group.objects.all(), required=True, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() class Meta: model = fEMRUser fields = [ "first_name", "last_name", "email", "username", "password1", "password2", "groups", "campaigns", ]
class RulesForm(forms.ModelForm): boxes = ModelMultipleChoiceField(label="Связанные виджеты",required=False,queryset=Boxes.objects.all()) tips=ChoiceField(label="Подсказки", required=False,choices=[ ('','---Выберите подсказку---'), ('+.*НапишиТекст.*','Включить задачи с текстом'), ('+^((?!НапишиТекст).)*$','Включить задачи без текста'), ('-.*НапишиТекст.*','Исключить задачи с текстом'), ('-^((?!НапишиТекст).)*$','Исключить задачи без текста'), ('+.*{boxname}.*','Имя виджета в имени задачи'), ('+.*{boxname,1,5}.*','Первые 5 букв виджета в имени задачи'), ]) # Overriding __init__ here allows us to provide initial # data for 'toppings' field def __init__(self, *args, **kwargs): # Only in case we build the form from an instance # (otherwise, 'toppings' list should be empty) if kwargs.get('instance'): # We get the 'initial' keyword argument or initialize it # as a dict if it didn't exist. initial = kwargs.setdefault('initial', {}) # The widget for a ModelMultipleChoiceField expects # a list of primary key for the selected data. initial['boxes'] = [t.pk for t in kwargs['instance'].boxes_set.all()] forms.ModelForm.__init__(self, *args, **kwargs) # Overriding save allows us to process the value of 'toppings' field def save(self, commit=True): # Get the unsave Pizza instance instance = forms.ModelForm.save(self, False) # Prepare a 'save_m2m' method for the form, old_save_m2m = self.save_m2m def save_m2m(): old_save_m2m() # This is where we actually link the pizza with toppings instance.boxes_set.clear() for item in self.cleaned_data['boxes']: instance.boxes_set.add(item) self.save_m2m = save_m2m # Do we need to save all changes now? if commit: instance.save() self.save_m2m() return instance class Meta: model = Rules fields=('rule','tips','comment','boxes') # fields = ['name', 'manager'] # widgets = { # 'manager': forms.Select(), # } class Media: js=( 'cvUpdate/cvRulesFormHelper.js', )
class CouponsFrom(ModelForm): user = ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=CustomerUser.objects.all()) class Meta: model = Coupons fields = '__all__'
class EmailSelectForm(Form): """ Form for selecting email addresses """ SERVICETYPECHOICES = (('saml', _('SAML / Shibboleth')), ('ldap', _('LDAP')), ('oidc', _('OIDC'))) service_type = MultipleChoiceField(required=True, widget=CheckboxSelectMultiple, choices=SERVICETYPECHOICES) production_sp = BooleanField(required=False, help_text=_("Select production SPs.")) test_sp = BooleanField(required=False, help_text=_("Select test SPs")) individual_sp = ModelMultipleChoiceField( queryset=ServiceProvider.objects.filter( end_at=None, history=None).order_by('entity_id'), required=False, help_text=_("Select individual SPs")) admin_emails = BooleanField(required=False, help_text=_("Select admin emails")) technical_contacts = BooleanField(required=False, help_text=_("Select technical contacts")) support_contacts = BooleanField(required=False, help_text=_("Select support contacts")) administrative_contacts = BooleanField( required=False, help_text=_("Select administrative contacts")) template = ModelChoiceField( queryset=Template.objects.all(), required=False, help_text=_('Select template if you want to send email'))
def html_selector(model, id, default=0, placeholder="", attrs={}): # @ReservedAssignment ''' Returns an HTML string for a model selector. :param model: The model to provide a selector widget for :param id: The id of the widget :param default: The default selection supplied (widget's initial condition) :param placeholder: The text that forms the background of the empty widget :param attrs: Any extra attributes to provide the widget with ''' url = reverse_lazy('autocomplete_all', kwargs={ "model": model.__name__, "field_name": model.selector_field }) field = ModelMultipleChoiceField(model.objects.all()) widget = autocomplete.ModelSelect2Multiple(url=url, attrs={ **attrs, "class": "multi_selector", "id": id, "data-placeholder": placeholder, "data-theme": "bootstrap" }) widget.choices = ModelChoiceIterator(field) return widget.render(model.__name__, default)
class SelectMultipleEndpointsForm(forms.Form): endpoints = ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(SelectMultipleEndpointsForm, self).__init__(*args, **kwargs) self.fields['endpoints'].queryset = Endpoint.objects.filter(owner=user) self.fields['endpoints'].widget = CRUDWidgetWrapper( self.fields['endpoints'].widget, reverse_lazy('create_endpoint'), reverse_lazy('update_endpoint', args=['__fk__']), reverse_lazy('delete_endpoint', args=['__fk__']))
class triaProfessorsConsergesSelect2Form(forms.Form): professors_conserges = ModelMultipleChoiceField( label="Tria professors o PAS", widget=ModelSelect2MultipleWidget( queryset=ProfessorConserge.objects.all(), search_fields=( 'last_name__icontains', 'first_name__icontains', ), attrs={'style': "'width': '100%'"}), queryset=ProfessorConserge.objects.all(), required=True)
class SelectMultipleClassNodesForm(forms.Form): nodes = ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): endpoints = kwargs.pop('endpoints') super().__init__(*args, **kwargs) self.fields['nodes'].queryset = Node.objects.filter( endpoint__in=endpoints, type="class") self.fields['nodes'].widget = CRUDWidgetWrapper( self.fields['nodes'].widget, reverse_lazy('create_node'), reverse_lazy('update_node', args=['__fk__']), reverse_lazy('delete_node', args=['__fk__']))
class ProductForm(EntangledModelForm): name = fields.CharField() active = fields.BooleanField() tenant = ModelChoiceField(queryset=get_user_model().objects.all(), empty_label=None) description = fields.CharField(required=False, widget=widgets.Textarea) categories = ModelMultipleChoiceField(queryset=Category.objects.all(), required=False) field_order = ['active', 'name', 'tenant', 'description', 'categories'] class Meta: model = Product untangled_fields = ['name'] entangled_fields = { 'properties': ['active', 'tenant', 'description', 'categories'] }
def __render_filters(filters, filter_widget_id, initial_filters): widget_name = regex_subs(r'^id_', '', filter_widget_id) filter_field = ModelMultipleChoiceField( widget=FilterCheckboxSelectMultiple, queryset=filters, required=False) # extracts the initial filters to be selected from the initial_filters # string, see DatasetConfigurationForm.__init__ if filters and initial_filters: initial_filter_ids = list(map(int, initial_filters.split(','))) else: initial_filter_ids = None filter_html = filter_field.widget.render(name=widget_name, value=initial_filter_ids, attrs={'id': filter_widget_id}) return filter_html
def __render_filters(filters, filter_widget_id, parametrised = False): widget_name = regex_subs(r'^id_', '', filter_widget_id) if parametrised: filter_field = ParamFilterChoiceField(widget=ParamFilterSelectMultiple, queryset=filters, required=False) else: filter_field = ModelMultipleChoiceField(widget=FilterCheckboxSelectMultiple, queryset=filters, required=False) preselected = None if filters: # pre-select the first filter preselected = filters[0].id filter_html = filter_field.widget.render( name=widget_name, value=preselected, attrs={'id': filter_widget_id}) return filter_html
def __init__(self, user, *args, **kwargs): super(PasswordForm, self).__init__(*args, **kwargs) remove_message = unicode( _('Hold down "Control", or "Command" on a Mac, to select more than one.' )) for field in self.fields: if remove_message in self.fields[field].help_text: self.fields[field].help_text = self.fields[ field].help_text.replace(remove_message, '').strip() # restrict the choice of users to share passwords with to a # user's PasswordContacts self.fields['shares'] = ModelMultipleChoiceField( queryset=PasswordContact.objects.filter(from_user=user) \ .order_by('to_user__first_name'), widget=widgets.CheckboxSelectMultiple())
class ExamReportForm(ModelForm): exam = ModelChoiceField(queryset=Exam.objects.all(), required=False, label='Select an exam (Default - all exams)') label = 'Trainees whose exams to generate a report for' trainee = ModelMultipleChoiceField( widget=TraineeSelect2MultipleInput, queryset=Trainee.objects.all(), required=False, label=label ) def __init__(self, *args, **kwargs): super(ExamReportForm, self).__init__(*args, **kwargs) self.fields['trainee'].widget.attrs = {'id': 'id_trainees'} class Meta: model = Session fields = ('exam', 'trainee',)
class AuthorEditPrefsForm(Form): checkbox_attrs = { 'btn_attrs': {'type': 'button', 'class': 'btn'}, 'data_attrs': {'class': 'hidden'}, 'btn_container_attrs': {'class': 'btn-group buttons-visible', 'data-toggle': 'buttons-checkbox'}, 'data_container_attrs': {'class': 'buttons-data'}, } radio_attrs = { 'btn_attrs': {'type': 'button', 'class': 'btn'}, 'data_attrs': {'class': 'hidden'}, 'btn_container_attrs': {'class': 'btn-group buttons-visible', 'data-toggle': 'buttons-radio'}, 'data_container_attrs': {'class': 'buttons-data'}, } excluded_categories = ModelMultipleChoiceField( queryset=Category.objects.all(), required=False, widget=StoriesButtons(attrs=checkbox_attrs), ) detail_view = ChoiceField( choices=[(0, 'Кратко'), (1, 'Подробно')], required=True, widget=StoriesRadioButtons(attrs=radio_attrs), ) nsfw = ChoiceField( choices=[(0, 'Показать'), (1, 'Скрыть')], required=True, widget=StoriesRadioButtons(attrs=radio_attrs), ) def __init__(self, *args, **kwargs): self.author = kwargs.pop('author', None) super(AuthorEditPrefsForm, self).__init__(*args, **kwargs) if self.author: self.fields['excluded_categories'].initial = self.author.excluded_categories self.fields['detail_view'].initial = self.author.detail_view self.fields['nsfw'].initial = self.author.nsfw def save(self): author = self.author excluded_categories = self.cleaned_data['excluded_categories'] author.excluded_categories = obj_to_int_list(excluded_categories) author.detail_view = bool(int(self.cleaned_data['detail_view'])) author.nsfw = bool(int(self.cleaned_data['nsfw'])) author.save(update_fields=['excluded_categories', 'detail_view', 'nsfw'])
def __init__(self, *args, **kwargs): # Формируем список возможных значений queryset = Terms.objects.filter(vocabulary=self.admin_field.vocabulary) if self.admin_field.lang_depended: queryset = queryset.filter(language=self.language) # Определяем язык language = self.admin_field.lang_depended and self.language or '' # Обращаемся к обработчику по-умолчанию super().__init__(*args, **kwargs) old_widget = self.fields['terms'].widget if self.admin_field.multiple: # Если поле множественного выбора widget = SelectMultiple(old_widget.widget.attrs, queryset) widget_wrapped = SCMSRelatedFieldWidgetWrapper( widget, old_widget.rel, old_widget.admin_site, self.admin_field.vocabulary, language) self.fields['terms'] = ModelMultipleChoiceField( queryset, required=False, widget=widget_wrapped) else: # Если поле одиночного выбора widget = Select(old_widget.widget.attrs, queryset) widget_wrapped = SCMSRelatedFieldWidgetWrapper( widget, old_widget.rel, old_widget.admin_site, self.admin_field.vocabulary, language) self.fields['terms'] = ModelChoiceField(queryset, required=False, widget=widget_wrapped) try: # Определяем значение по умолчанию -- первое в списке значений initial = instance.terms.get_queryset()[0].id except: initial = None self.initial['terms'] = initial self.fields['terms'].initial = initial pass
class ReviewForm(forms.Form): # Hack to restore behavior from pre Django 1.10 times. # Django 1.10 enabled `required` rendering for required widgets. That # wasn't the case before, this should be fixed properly but simplifies # the actual Django 1.11 deployment for now. # See https://github.com/mozilla/addons-server/issues/8912 for proper fix. use_required_attribute = False comments = forms.CharField(required=True, widget=forms.Textarea(), label=_(u'Comments:')) canned_response = NonValidatingChoiceField(required=False) action = forms.ChoiceField(required=True, widget=forms.RadioSelect()) versions = ModelMultipleChoiceField( widget=forms.SelectMultiple( attrs={ 'class': 'data-toggle', 'data-value': ( 'reject_multiple_versions|confirm_multiple_versions|') }), required=False, queryset=Version.objects.none()) # queryset is set later in __init__. operating_systems = forms.CharField(required=False, label=_(u'Operating systems:')) applications = forms.CharField(required=False, label=_(u'Applications:')) info_request = forms.BooleanField( required=False, label=_(u'Require developer to respond in less than…')) info_request_deadline = forms.IntegerField(required=False, widget=NumberInput, initial=7, label=_(u'days'), min_value=1, max_value=99) def is_valid(self): # Some actions do not require comments. action = self.helper.actions.get(self.data.get('action')) if action: if not action.get('comments', True): self.fields['comments'].required = False if action.get('versions', False): self.fields['versions'].required = True result = super(ReviewForm, self).is_valid() if result: self.helper.set_data(self.cleaned_data) return result def __init__(self, *args, **kw): self.helper = kw.pop('helper') super(ReviewForm, self).__init__(*args, **kw) # Info request deadline needs to be readonly unless we're an admin. user = self.helper.handler.user deadline_widget_attributes = {} info_request_deadline = self.fields['info_request_deadline'] if not acl.action_allowed_user(user, amo.permissions.REVIEWS_ADMIN): info_request_deadline.min_value = info_request_deadline.initial info_request_deadline.max_value = info_request_deadline.initial deadline_widget_attributes['readonly'] = 'readonly' deadline_widget_attributes.update({ 'min': info_request_deadline.min_value, 'max': info_request_deadline.max_value, }) info_request_deadline.widget.attrs.update(deadline_widget_attributes) # With the helper, we now have the add-on and can set queryset on the # versions field correctly. Small optimization: we only need to do this # if the reject_multiple_versions/confirm_multiple_versions actions are # available, otherwise we don't really care about this field. if ('reject_multiple_versions' in self.helper.actions or 'confirm_multiple_versions' in self.helper.actions): if self.helper.version: channel = self.helper.version.channel else: channel = amo.RELEASE_CHANNEL_LISTED self.fields['versions'].queryset = ( self.helper.addon.versions.distinct().filter( channel=channel, files__status__in=( amo.STATUS_APPROVED, amo.STATUS_AWAITING_REVIEW)).order_by('created')) # For the canned responses, we're starting with an empty one, which # will be hidden via CSS. canned_choices = [[ '', [('', ugettext('Choose a canned response...'))] ]] canned_type = (amo.CANNED_RESPONSE_TYPE_THEME if self.helper.addon.type == amo.ADDON_STATICTHEME else amo.CANNED_RESPONSE_TYPE_ADDON) responses = CannedResponse.objects.filter(type=canned_type) # Loop through the actions (public, etc). for k, action in self.helper.actions.items(): action_choices = [[c.response, c.name] for c in responses if c.sort_group and k in c.sort_group.split(',')] # Add the group of responses to the canned_choices array. if action_choices: canned_choices.append([action['label'], action_choices]) # Now, add everything not in a group. for r in responses: if not r.sort_group: canned_choices.append([r.response, r.name]) self.fields['canned_response'].choices = canned_choices self.fields['action'].choices = [ (k, v['label']) for k, v in self.helper.actions.items() ] @property def unreviewed_files(self): return (self.helper.version.unreviewed_files if self.helper.version else [])
class ReviewForm(happyforms.Form): comments = forms.CharField(required=True, widget=forms.Textarea(), label=_(u'Comments:')) canned_response = NonValidatingChoiceField(required=False) action = forms.ChoiceField(required=True, widget=forms.RadioSelect()) versions = ModelMultipleChoiceField( widget=forms.SelectMultiple(attrs={ 'class': 'data-toggle', 'data-value': 'reject_multiple_versions|' }), required=False, queryset=Version.objects.none()) # queryset is set later in __init__. operating_systems = forms.CharField(required=False, label=_(u'Operating systems:')) applications = forms.CharField(required=False, label=_(u'Applications:')) info_request = forms.BooleanField(required=False, label=_(u'Is more info requested?')) def is_valid(self): # Some actions do not require comments. action = self.helper.actions.get(self.data.get('action')) if action: if not action.get('comments', True): self.fields['comments'].required = False if action.get('versions', False): self.fields['versions'].required = True result = super(ReviewForm, self).is_valid() if result: self.helper.set_data(self.cleaned_data) return result def __init__(self, *args, **kw): self.helper = kw.pop('helper') self.type = kw.pop('type', amo.CANNED_RESPONSE_ADDON) super(ReviewForm, self).__init__(*args, **kw) # With the helper, we now have the add-on and can set queryset on the # versions field correctly. Small optimization: we only need to do this # if the reject_multiple_versions action is available, otherwise we # don't really care about this field. if 'reject_multiple_versions' in self.helper.actions: self.fields['versions'].queryset = ( self.helper.addon.versions.distinct().filter( channel=amo.RELEASE_CHANNEL_LISTED, files__status=amo.STATUS_PUBLIC).order_by('created')) # For the canned responses, we're starting with an empty one, which # will be hidden via CSS. canned_choices = [[ '', [('', ugettext('Choose a canned response...'))] ]] responses = CannedResponse.objects.filter(type=self.type) # Loop through the actions (public, etc). for k, action in self.helper.actions.iteritems(): action_choices = [[c.response, c.name] for c in responses if c.sort_group and k in c.sort_group.split(',')] # Add the group of responses to the canned_choices array. if action_choices: canned_choices.append([action['label'], action_choices]) # Now, add everything not in a group. for r in responses: if not r.sort_group: canned_choices.append([r.response, r.name]) self.fields['canned_response'].choices = canned_choices self.fields['action'].choices = [ (k, v['label']) for k, v in self.helper.actions.items() ] @property def unreviewed_files(self): return (self.helper.version.unreviewed_files if self.helper.version else [])
class PlacementForm(modelforms.ModelForm): """PlacementForm from ella.core.newman_admin without djangomarkup dependency (and default Django fields).""" # create the field here to pass validation #listings = fields.ListingCustomField(Category.objects.all(), label=_('Category'), cache_choices=True, required=False) listings = ModelMultipleChoiceField(Category.objects.all(), label=_('Category'), cache_choices=True, required=False) class Meta: model = Placement def __init__(self, *args, **kwargs): initial = [] # args[data] -> instance if 'initial' in kwargs: initial = [ c.pk for c in Category.objects.distinct().filter( listing__placement=kwargs['initial']['id']) ] elif 'instance' in kwargs: initial = [list(kwargs['instance'].listing_set.all())] #self.base_fields['listings'] = fields.ListingCustomField( # Category.objects.all(), label=_('Category'), cache_choices=True, required=False, initial=initial) self.base_fields['listings'] = self.base_fields['listings'].__class__( Category.objects.all(), label=_('Category'), cache_choices=True, required=False, initial=initial) super(PlacementForm, self).__init__(*args, **kwargs) def get_publish_date(self, pub_from): " Tries to save publish_from field specified either by POST parameter or by Placement (self.instance). " if pub_from: dt_field = DateTimeField() return dt_field.clean(pub_from) return self.instance.publish_from def save(self, commit=True): cleaned_list_cats = self.cleaned_data.pop('listings') list_cats = [] # Order of items should be preserved (in cleaned_data is order not preserved) for pk in self.data.getlist(self.get_part_id('')): list_cats.append(Category.objects.get(pk=int(pk))) publish_from_fields = self.data.getlist( self.get_part_id('publish_from')) instance = self.instance def save_them(): if not list_cats: return listings = dict([ (l.category, l) for l in Listing.objects.filter(placement=instance.pk) ]) forloop_counter = 0 # used for counting delete checkboxes for c, pub in zip(list_cats, publish_from_fields): forloop_counter += 1 delete_listing = self.data.get( self.get_part_id('%d-DELETE' % forloop_counter), 'off') if delete_listing == 'on': # skip following for-cycle body, so the listing will be deleted continue publish_from = self.get_publish_date(pub) if not c in listings: # create listing l = Listing(placement=instance, category=c, publish_from=publish_from) l.save() else: del listings[c] lst = Listing.objects.filter(placement=instance, category=c) if not lst: continue l = lst[0] # if publish_from differs, modify Listing object if l.publish_from != publish_from: l.publish_from = publish_from l.save() for l in listings.values(): l.delete() if commit: save_them() else: save_m2m = getattr(self, 'save_m2m', None) def save_all(): if save_m2m: save_m2m() save_them() self.save_m2m = save_all instance.category = self.cleaned_data['category'] instance.publish_from = self.cleaned_data['publish_from'] instance.publish_to = self.cleaned_data['publish_to'] instance.slug = self.cleaned_data['slug'] instance.static = self.cleaned_data['static'] if not commit: return instance if self.instance.pk is None: fail_message = 'created' else: fail_message = 'changed' return save_instance(self, instance, self._meta.fields, fail_message, commit, exclude=self._meta.exclude) def get_part_id(self, suffix): id_part = self.data.get('placement_listing_widget') if not suffix: return id_part return '%s-%s' % (id_part, suffix) def listings_clean(self, placement_publish_from, data): # get listing category, publish_from and publish_to pub_from = data.getlist(self.get_part_id('publish_from')) listings = self.cleaned_data['listings'] if pub_from and len(pub_from) != len(listings): raise ValidationError(_('Duplicate listings')) for lst, pub in zip(listings, pub_from): if not pub: #raise ValidationError(_('This field is required')) continue dt_field = DateTimeField() publish_from = dt_field.clean(pub) if publish_from < placement_publish_from: raise ValidationError( _('No listing can start sooner than main listing')) def clean(self): # no data - nothing to validate if not self.is_valid( ) or not self.cleaned_data or not self.instance or not self.cleaned_data[ 'publishable']: return self.cleaned_data obj = self.instance cat = None if obj.pk: cat = getattr(obj, 'category', None) obj_slug = getattr(obj, 'slug', obj.pk) # if Placement has no slug, slug from Publishable object should be considered in following checks: if not obj_slug: obj_slug = self.cleaned_data['publishable'].slug main = None d = self.cleaned_data # empty form if not d: return self.cleaned_data #if cat and cat == cat and cat: # should be equiv. if cat:... if cat: main = d if d['publish_to'] and d['publish_from'] > d['publish_to']: raise ValidationError( _('Publish to must be later than publish from.')) d['slug'] = obj_slug # try and find conflicting placement qset = Placement.objects.filter( category=d['category'], slug=d['slug'], #publishable=obj, static=d['static']) if d['static']: # allow placements that do not overlap q = Q(publish_to__lt=d['publish_from']) if d['publish_to']: q |= Q(publish_from__gt=d['publish_to']) qset = qset.exclude(q) # check for same date in URL if not d['static']: qset = qset.filter( publish_from__year=d['publish_from'].year, publish_from__month=d['publish_from'].month, publish_from__day=d['publish_from'].day, ) # exclude current object from search if d['id']: qset = qset.exclude(pk=d['id'].pk) if qset: plac = qset[0] # raise forms.ValidationError( raise ValidationError( _('''There is already a Placement object published in category %(category)s with the same URL referring to %(target)s. Please change the slug or publish date.''') % { 'category': plac.category, 'target': plac.publishable, }) if cat and not main: # raise forms.ValidationError(_('If object has a category, it must have a main placement.')) raise ( _('If object has a category, it must have a main placement.')) self.listings_clean(d['publish_from'], self.data) return self.cleaned_data
class ContatoForm(ModelForm): class Meta: model = Contato fields = [ 'nome', 'nome_social', 'apelido', 'data_nascimento', 'estado_civil', 'sexo', 'identidade_genero', 'nivel_instrucao', 'naturalidade', 'tem_filhos', 'quantos_filhos', 'profissao', 'pronome_tratamento', 'tipo_autoridade', 'nome_pai', 'nome_mae', 'numero_sus', 'cpf', 'titulo_eleitor', 'rg', 'rg_orgao_expedidor', 'rg_data_expedicao', 'ativo', 'observacoes', 'cargo', 'grupodecontatos_set' ] grupodecontatos_set = ModelMultipleChoiceField( queryset=GrupoDeContatos.objects.all(), required=False, label='', widget=FilteredSelectMultiple('grupodecontatos_set', False), ) def __init__(self, *args, **kwargs): instance = None super(ContatoForm, self).__init__(*args, **kwargs) if isinstance(self.instance, Contato): instance = self.instance if 'tipo_autoridade' in self.fields: self.fields['tipo_autoridade'].widget.attrs.update( {'onchange': 'atualizaPronomes(event)'}) self.fields['pronome_tratamento'].widget = forms.RadioSelect() self.fields['pronome_tratamento'].queryset = \ PronomeTratamento.objects.order_by( 'prefixo_nome_singular_m', 'nome_por_extenso') if 'tipo_autoridade' in self.fields and\ instance and instance.tipo_autoridade: pronomes_choice = instance.tipo_autoridade.pronomes.order_by( 'prefixo_nome_singular_m', 'nome_por_extenso') else: pronomes_choice = self.fields['pronome_tratamento'].queryset self.fields['pronome_tratamento'].choices = [ (p.pk, '%s, %s - %s - %s - %s - %s - %s - %s' % (p.prefixo_nome_singular_m, p.prefixo_nome_singular_f, p.nome_por_extenso, p.abreviatura_singular_m, p.abreviatura_plural_m, p.vocativo_direto_singular_m, p.vocativo_indireto_singular_m, p.enderecamento_singular_m)) for p in pronomes_choice ] self.fields[ 'grupodecontatos_set'].widget = forms.CheckboxSelectMultiple() self.fields['grupodecontatos_set'].inline_class = True self.fields['grupodecontatos_set'].queryset = \ GrupoDeContatos.objects.filter(workspace=self.initial['workspace']) if self.instance and self.instance.pk: self.fields['grupodecontatos_set'].initial = list( self.instance.grupodecontatos_set.all()) def clean(self): pronome = self.cleaned_data['pronome_tratamento'] if 'tipo_autoridade' in self.cleaned_data: tipo_autoridade = self.cleaned_data['tipo_autoridade'] if tipo_autoridade and not pronome: self._errors['pronome_tratamento'] = [ _('Tendo sido selecionado um tipo de autoridade, \ o campo pronome de tratamento se torna obrigatório.') ]
class FilterForm(forms.Form): def __init__(self, *args, **kwargs): city_object = kwargs.pop('city_object', None) super(FilterForm, self).__init__(*args, **kwargs) self.fields['term_search'].initial = '30' if city_object: all_locations = Sublocality.objects.filter(city__id=city_object.id) big_sublocality = BigSublocality.objects.filter( city_id=city_object.id).order_by('id') all_metro = Metro.objects.filter(city__id=city_object.id) metro_lines = MetroLine.objects.filter(city__id=city_object.id) self.fields['province'] = ModelMultipleChoiceField( label=u'Областной центр', queryset=all_locations.filter(in_city=False), widget=CheckboxSelectMultiple(attrs={'form': 'search_query'})) self.fields['bigsubloc'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple(attrs={'form': 'search_query'}), queryset=big_sublocality) for i, item in enumerate(big_sublocality): self.fields[str(i) + 'subloc'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple( attrs={'form': 'search_query'}), queryset=all_locations.filter(big_sublocality=item.id)) # self.fields['sublocality'] = ModelMultipleChoiceField( # widget=CheckboxSelectMultiple(attrs={'form':'search_query'}), # queryset=all_locations) for i, item in enumerate(metro_lines): self.fields[str(i) + 'metro_line'] = ModelMultipleChoiceField( widget=CheckboxSelectMultiple( attrs={'form': 'search_query'}), queryset=all_metro.filter( line=item.id).order_by('sequence_number')) term_search = forms.ChoiceField( choices=TERM_LIST, widget=Select(attrs={'form': 'search_query'})) rooms_num = forms.MultipleChoiceField( required=False, widget=CheckboxSelectMultiple(attrs={'form': 'search_query'}), choices=CHECKBOX_CHOICES, label=u'Число комнат') min_price = forms.DecimalField( label=u'от', required=False, widget=forms.NumberInput(attrs={ 'step': '100', 'form': 'search_query' })) max_price = forms.DecimalField( label=u'до', required=False, widget=forms.NumberInput(attrs={'form': 'search_query'})) query = forms.CharField(widget=forms.TextInput( attrs={'form': 'search_query'})) currency = forms.ChoiceField(choices=CURRENCY_CHOICES, widget=forms.Select(attrs={ 'form': 'search_query', })) sort_obj = forms.ChoiceField(choices=SELECT_OBJ, widget=forms.Select(attrs={ 'form': 'search_query', })) sort_level = forms.ChoiceField(choices=SELECT_LEVEL, widget=forms.Select(attrs={ 'form': 'search_query', })) object_type = ModelMultipleChoiceField( queryset=ObjectType.objects.all(), widget=CheckboxSelectMultiple(attrs={'form': 'search_query'})) object_all = forms.ChoiceField(choices=OBJ_ALL, widget=forms.Select(attrs={ 'form': 'search_query', })) action = forms.ChoiceField(choices=ACT, widget=forms.Select(attrs={ 'form': 'search_query', })) woagent = forms.BooleanField(widget=forms.CheckboxInput( attrs={'form': 'search_query'})) prozvon = forms.BooleanField(widget=forms.CheckboxInput( attrs={'form': 'search_query'})) city = ModelChoiceField( queryset=City.objects.all(), label=u'Город', required=True, help_text=u'', empty_label=None, widget=forms.Select(attrs={'form': 'search_query'})) rent_term = forms.DecimalField( widget=Select(choices=TERM_CHOICES, attrs={'form': 'search_query'})) text_filter = forms.CharField(widget=forms.TextInput( attrs={ 'form': 'search_query', 'placeholder': u'Поиск по слову' })) hide_show_notes = forms.DecimalField(widget=Select( choices=SHOW_NOTE_CHOICES, attrs={'form': 'search_query'}), ) pro_color = forms.MultipleChoiceField( choices=PRO_COLORS, widget=CheckboxSelectMultiple(attrs={'form': 'search_query'})) pro_comment = forms.BooleanField(widget=forms.CheckboxInput( attrs={'form': 'search_query'})) new_building = forms.BooleanField(widget=forms.CheckboxInput( attrs={'form': 'search_query'})) house_type = forms.MultipleChoiceField( required=False, choices=HOUSE_TYPE, widget=forms.CheckboxSelectMultiple(attrs={ 'form': 'search_query', 'class': 'hohouse' }))
class SearchForm(forms.Form): instruments = ModelMultipleChoiceField(queryset=Instrument.objects.all(), required=False)
class DatasetConfigurationForm(forms.ModelForm): class Meta: model = DatasetConfiguration fields = [ 'dataset', 'version', 'variable', 'filters', 'parametrised_filters', ] dataset = DatasetChoiceField(queryset=Dataset.objects.none(), required=True) filter_dataset = forms.BooleanField(initial=True, required=False, label='Filter dataset') # if you change this field, be sure to adapt validator.views.validation.__render_filters filters = ModelMultipleChoiceField(widget=FilterCheckboxSelectMultiple, queryset=DataFilter.objects.filter(parameterised=False), required=False) # see https://stackoverflow.com/questions/2216974/django-modelform-for-many-to-many-fields/2264722#2264722 # and https://docs.djangoproject.com/en/2.1/ref/forms/fields/#django.forms.ModelMultipleChoiceField # if you change this, be sure to adapt _save_m2m and validator.views.validation.__render_filters parametrised_filters = ParamFilterChoiceField(widget=ParamFilterSelectMultiple, queryset=DataFilter.objects.filter(parameterised=True), required=False) ## if you want to create a dataset config form for reference datasets, pass in parameter is_reference=True def __init__(self, *args, is_reference=False, **kwargs): super(DatasetConfigurationForm, self).__init__(*args, **kwargs) if is_reference: # self.fields["dataset"].queryset = Dataset.objects.all() # temporarily SMOS, SMAP and ASCAT are removed from the reference list self.fields["dataset"].queryset = Dataset.objects.exclude(short_name__in=NOT_AS_REFERENCE) else: self.fields["dataset"].queryset = Dataset.objects.filter(is_only_reference=is_reference) for key in ["dataset", "version", "variable"]: self.fields[key].initial = self.get_initial_for_field( self.fields[key], key ) # This translates the initial filter list to a string of filter ids # separated by an underscore. This string is passed to the ajax call # `ajax_change_dataset` in validate.html, and then further passed to # `ajax_get_dataset_options` in validation.py. if "filters" in self.initial: self.initial_filters = ",".join(map( lambda x: str(getattr(x, "id")), list(self.initial["filters"]) )) else: self.initial_filters = "" if "parametrised_filters" in self.initial: self.initial_paramfilters = ",".join(map( lambda x: str(getattr(x, "id")), list(self.initial["parametrised_filters"]) )) if "paramfilter_params" in self.initial: self.initial_paramfilter_params = ";".join( self.initial["paramfilter_params"] ) else: self.initial_paramfilter_params = "" else: self.initial_paramfilters = "" self.initial_paramfilter_params = "" # do the same for version and variable if "version" in self.initial: self.initial_version = str(self.initial["version"].id) else: self.initial_version = "" if "variable" in self.initial: self.initial_variable = str(self.initial["variable"].id) else: self.initial_variable = "" def _save_m2m(self): # treat the parametrised filters separately, remove them now, save after calling super param_filters = None if('parametrised_filters' in self.cleaned_data and self.cleaned_data['parametrised_filters']): param_filters = self.cleaned_data['parametrised_filters'] self.cleaned_data['parametrised_filters'] = [] super(DatasetConfigurationForm, self)._save_m2m() # apparently, the unsaved ParametrisedFilter objects need to have save called on them explicitly, so do that # https://stackoverflow.com/questions/31862599/how-to-save-a-manytomany-field-with-a-through-relationship/31863016#31863016 if param_filters: for pf in param_filters: pf.dataset_config = self.instance pf.save() def clean(self): cleaned_data = super(DatasetConfigurationForm, self).clean() # this shouldn't be necessary because the values of disabled checkboxes in HTML forms # don't get submitted, but let's err on the side of caution... if not cleaned_data['filter_dataset']: cleaned_data['filters'] = DataFilter.objects.none() cleaned_data['parametrised_filters'] = [] return cleaned_data
class DocumentoForm(ModelForm): parlamentares = ModelMultipleChoiceField( queryset=Parlamentar.objects.filter(ativo=True), required=False, label=Parlamentar._meta.verbose_name_plural, widget=forms.SelectMultiple(attrs={'size': '10'}) ) public_date = forms.DateTimeField( widget=forms.HiddenInput(), required=False,) tipo = forms.ChoiceField(choices=Documento.tipo_parte_doc['documentos']) capa = forms.TypedChoiceField(label=_('Capa de sua Classe'), choices=YES_NO_CHOICES, coerce=lambda x: x == 'True') materias = ModelMultipleChoiceField( queryset=MateriaLegislativa.objects.order_by( '-data_apresentacao'), required=False, label=MateriaLegislativa._meta.verbose_name_plural, widget=forms.SelectMultiple(attrs={'size': '10'}) ) class Meta: model = Documento fields = ['titulo', 'template_doc', 'descricao', 'visibilidade', 'parlamentares', 'public_date', 'tipo', 'listar', 'capa', 'materias' ] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.layout = SaplFormLayout( to_row([ ('titulo', 7), ('visibilidade', 3), ('listar', 2) ]), to_row([ ('tipo', 4), ('template_doc', 4), ('capa', 4), ]), to_row([ ('descricao', 8), ('parlamentares', 4) ]), to_row([ ('materias', 12), ]), ) super(DocumentoForm, self).__init__(*args, **kwargs) self.fields['parlamentares'].choices = [ ('0', '--------------')] + list( self.fields['parlamentares'].choices) self.fields['materias'].choices = [ ('0', '--------------')] + [(m.id, str(m) + ' - ' + m.ementa) for m in self.fields['materias'].queryset[:200]] self.fields['capa'].initial = self.instance == self.instance.classe.capa def save(self, commit=True): inst = self.instance if inst.visibilidade != Documento.STATUS_PUBLIC: inst.public_date = None inst.public_end_date = None else: if not inst.public_date: inst.public_date = timezone.now() inst = super().save(commit) if not inst.childs.exists(): container = Documento() container.titulo = '' container.descricao = '' container.classe = inst.classe container.tipo = Documento.TPD_CONTAINER_SIMPLES container.owner = inst.owner container.parent = inst container.ordem = 1 container.visibilidade = inst.visibilidade container.save() classe = inst.classe classe.capa = inst if self.cleaned_data['capa'] else None classe.save() return inst
def __init__(self, *args, **kwargs): self.questions=kwargs.pop('questions') ModelMultipleChoiceField.__init__(self, *args, **kwargs)