class MigrateTagsForm(forms.Form): old_tag = TreeNodeChoiceField( queryset=Tag.objects.all(), label=_("Old category"), help_text=_( "All questions associated to this category will be migrated to " "the new one."), ) new_tag = TreeNodeChoiceField( queryset=Tag.objects.all(), label=_("Target category"), help_text=_( "All questions will be moved to this category (if not already " "attached to it)."), ) delete_old_tag = forms.BooleanField( label=_("Delete the old category?"), help_text=_( "If checked, the old category will be deleted. Else, kept but " "without any question left attached."), required=False, initial=True, )
def test_treenodechoicefield(self): field = TreeNodeChoiceField(queryset=Genre.objects.all()) self.assertHTMLEqual( field.widget.render("test", None), '<select name="test">' '<option value="" selected>---------</option>' '<option value="1"> Action</option>' '<option value="2">--- Platformer</option>' '<option value="3">------ 2D Platformer</option>' '<option value="4">------ 3D Platformer</option>' '<option value="5">------ 4D Platformer</option>' '<option value="6">--- Shootemup</option>' '<option value="7">------ Vertical Scrolling Shootemup</option>' '<option value="8">------ Horizontal Scrolling Shootemup</option>' '<option value="9"> Role-playing Game</option>' '<option value="10">--- Action RPG</option>' '<option value="11">--- Tactical RPG</option>' "</select>", ) field = TreeNodeChoiceField( queryset=Genre.objects.all(), empty_label="None of the below" ) self.assertInHTML( '<option value="" selected>None of the below</option>', field.widget.render("test", None), )
class PageForm(forms.ModelForm): meta_description = forms.CharField(widget=forms.Textarea, required=False) meta_keywords = forms.CharField(widget=forms.Textarea, required=False) parent = TreeNodeChoiceField(queryset=Page.tree.all(), level_indicator=3 * unichr(160), empty_label='---------', required=False) redirect_page = TreeNodeChoiceField(label=_('Redirect page'), queryset=Page.objects.filter(redirect_page__isnull=True), level_indicator=3 * unichr(160), empty_label='---------', required=False) class Meta: model = Page exclude = [] def __init__(self, *args, **kwargs): super(PageForm, self).__init__(*args, **kwargs) if len(TEMPLATE_CHOICES) > 0: self.fields['template_name'] = forms.ChoiceField(choices=TEMPLATE_CHOICES, required=False, label=_('Template')) def clean_title(self): """ Strips extra whitespace """ return self.cleaned_data.get('title', '').strip() def clean_redirect_page(self): if self.cleaned_data['redirect_page']: try: if self.cleaned_data['url'] and is_quoted_url(self.cleaned_data['url']): raise forms.ValidationError(_('A named url can\'t be combined with a redirect page')) except KeyError: pass return self.cleaned_data['redirect_page']
class FilterDevicesForm(ModelForm): filter_d = TreeNodeChoiceField(queryset=devicestypes.objects.all(),level_indicator=u'+--', label="Тип") filter_p = TreeNodeChoiceField(queryset=placements.objects.all(),level_indicator=u'+--', label="Размещение") class Meta: model = devicestypes fields = ['filter_d','filter_p'] def __init__(self, *args, **kwargs): super(FilterDevicesForm, self).__init__(*args, **kwargs) self.fields['filter_d'].widget.attrs = {'class':'form-control input-sm'} self.fields['filter_p'].widget.attrs = {'class':'form-control input-sm'}
class SimpleTransactionForm(forms.ModelForm): """A simplified form for transferring an an amount from one account to another This only allows the creation of transactions with two legs. This also uses :meth:`Account.transfer_to()`. See Also: * :meth:`hordak.models.Account.transfer_to()`. """ from_account = TreeNodeChoiceField( queryset=Account.objects.all(), to_field_name="uuid" ) to_account = TreeNodeChoiceField( queryset=Account.objects.all(), to_field_name="uuid" ) amount = MoneyField( max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, ) class Meta: model = Transaction fields = ["amount", "from_account", "to_account", "date", "description"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Limit currency choices if setup default_currency = DEFAULT_CURRENCY amount_field, currency_field = self.fields["amount"].fields self.fields["amount"].widget.widgets[1].choices = currency_field.choices = [ (code, name) for code, name in currency_field.choices if code == default_currency or code in CURRENCIES ] self.fields["amount"].initial[1] = default_currency def save(self, commit=True): from_account = self.cleaned_data.get("from_account") to_account = self.cleaned_data.get("to_account") amount = self.cleaned_data.get("amount") return from_account.transfer_to( to_account=to_account, amount=amount, description=self.cleaned_data.get("description"), date=self.cleaned_data.get("date"), )
def abuse(request): dictionary = { 'tools': Tool.objects.filter(visible=True), 'area_widget': TreeNodeChoiceField(Area.objects.filter(requires_reservation=True).only('name'), empty_label=None).widget } try: form = ReservationAbuseForm(request.GET) if form.is_valid(): intermediate_results = defaultdict(float) reservations = Reservation.objects.filter(start__gt=form.cleaned_data['start'], start__lte=form.cleaned_data['end'], cancelled=True, cancellation_time__isnull=False) if form.cleaned_data['target']: item_type, item_id = form.get_target() dictionary['item_type'] = item_type.value dictionary['item_id'] = item_id if item_type == ReservationItemType.AREA: reservations = reservations.filter(area__in=Area.objects.get(pk=item_id).get_descendants(include_self=True)) elif item_type == ReservationItemType.TOOL: reservations = reservations.filter(tool__id=item_id) for r in reservations: cancellation_delta = (r.start - r.cancellation_time).total_seconds() if 0 < cancellation_delta < form.cleaned_data['cancellation_horizon']: penalty = ((form.cleaned_data['cancellation_horizon'] - cancellation_delta) / form.cleaned_data['cancellation_horizon']) * form.cleaned_data['cancellation_penalty'] intermediate_results[r.user.id] += penalty final_results = {} for user_id, score in intermediate_results.items(): user = User.objects.get(id=user_id) final_results[user] = int(score) sorted_results = sorted(final_results.items(), key=lambda x: x[1], reverse=True) dictionary['results'] = sorted_results else: form = ReservationAbuseForm() except ValidationError: form = ReservationAbuseForm() dictionary['form'] = form return render(request, 'abuse/abuse.html', dictionary)
class ProductAdminForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.tree.all(), empty_label="Choisissez une catégorie", level_indicator=u'--') class Meta: model = Product
class bookForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.objects.all()) author = forms.ModelMultipleChoiceField(queryset=Author.objects.all()) class Meta: model = Book fields = [ 'name', 'author', 'publisher', 'isbn', 'slug', 'sku', 'category', 'inStock', 'language', 'bookDescription', 'metaKeywords', 'metaDescription', 'thumbnailImage', 'preview', 'coverImage' ] labels = { 'name': _('Book Name'), 'author': _('Author'), 'publisher': _('Publisher'), 'isbn': _('ISBN'), 'slug': _('Slug'), 'sku': _('SKU'), 'category': _('Category'), 'inStock': _('InStock'), 'language': _('Language'), 'bookDescription': _('Book Description'), 'metaKeywords': _('Meta Keywords'), 'metaDescription': _('Meta Description'), 'createdAt': _('CreatedAt'), 'updatedAt': _('UpdatedAt'), 'thumbnailImage': _('thumbnailImage'), 'coverImage': _('coverImage'), 'preview': _('preview'), }
def formfield_for_foreignkey(self, db_field, request, **kwargs): if issubclass(db_field.rel.to, MPTTModel): required = db_field.formfield().required return TreeNodeChoiceField(queryset=db_field.rel.to.objects.all(), required=required) return super(SectionTreeAdminMixin, self)\ .formfield_for_foreignkey(db_field, request, **kwargs)
class LegForm(forms.ModelForm): """A form for representing a single transaction leg Attributes: account (TreeNodeChoiceField): Choose an account the leg will interact with description (forms.CharField): Optional description/notes for this leg amount (MoneyField): The amount for this leg. Positive values indicate money coming into the transaction, negative values indicate money leaving the transaction. See Also: This is a `ModelForm` for the :class:`Leg model <hordak.models.Leg>`. """ account = TreeNodeChoiceField(Account.objects.all(), to_field_name='uuid') description = forms.CharField(required=False) amount = MoneyField(required=True, decimal_places=2) class Meta: model = Leg fields = ('amount', 'account', 'description') def __init__(self, *args, **kwargs): self.statement_line = kwargs.pop('statement_line', None) super(LegForm, self).__init__(*args, **kwargs) def clean_amount(self): amount = self.cleaned_data['amount'] if amount.amount <= 0: raise ValidationError('Amount must be greater than zero') if self.statement_line and self.statement_line.amount < 0: amount *= -1 return amount
class AdvancedSearchForm(forms.Form): folder = TreeNodeChoiceField( queryset=None, required=False ) text = forms.CharField() tags = forms.CharField() def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: all_folders = Folder.objects.exclude( title=Folder.INBOX_NAME ) folder_choice_ids = [] for folder in all_folders: if user.has_perm(Access.PERM_READ, folder): folder_choice_ids.append(folder.id) self.fields['folder'].queryset = Folder.objects.filter( id__in=folder_choice_ids )
class GenericInlineMenuItemForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=MenuItem.objects.all(), required=False) class Meta: model = MenuItem fields = ('parent', 'label', 'slug', 'order', 'is_enabled')
class NewCommentForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Comment.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent'].widget.attrs.update({'class': 'd-none'}) self.fields['parent'].label = '' self.fields['parent'].required = False class Meta: model = Comment fields = ('post', 'parent', 'content') widgets = { 'content': forms.Textarea( attrs={ 'class': 'ml-3 mb-3 form-control border-0 comment-add rounded-0', 'rows': '1', 'placeholder': 'Add a public comment' }), } def save(self, *args, **kwargs): Comment.objects.rebuild() return super(NewCommentForm, self).save(*args, **kwargs)
class IdeaFilterForm(forms.Form): author = forms.ModelChoiceField( label=_("Author"), required=False, queryset=User.objects.all(), ) category = TreeNodeChoiceField( label=_("Category"), required=False, queryset=Category.objects.all(), level_indicator=mark_safe(" ")) rating = forms.ChoiceField(label=_("Rating"), required=False, choices=RATING_CHOICES) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) author_field = layout.Field("author") category_field = layout.Field("category") rating_field = layout.Field("rating") submit_button = layout.Submit("filter", _("Filter")) actions = bootstrap.FormActions(submit_button) main_fieldset = layout.Fieldset( _("Filter"), author_field, category_field, rating_field, actions, ) self.helper = helper.FormHelper() self.helper.form_method = "GET" self.helper.layout = layout.Layout(main_fieldset)
class ShopItemForm(forms.ModelForm): thumbnail = ImageField(widget=ImagePreviewWidget) sale = IntegerField( min_value=0, max_value=100, help_text="Item price reduction (sale) in percent", ) download = forms.FileField() try: category = TreeNodeChoiceField( queryset=CategoryTree.shop.get_parent_leaves("digital"), level_indicator="") except OperationalError or ProgrammingError: pass def _post_clean(self): if "download" in self.changed_data: dl = Download.objects.create( file=self.cleaned_data.get("download")) dl.save() else: dl = self.instance.download self.cleaned_data["download"] = dl super(ShopItemForm, self)._post_clean() class Meta: model = Item fields = "__all__"
class StoreForm(forms.ModelForm): area = TreeNodeChoiceField(queryset=Area.objects.all()) class Meta: model = Store exclude = ['created', 'edited'] widgets = {'description': CKEditorUploadingWidget(config_name='mcat')}
class NewCommentForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Comment.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent'].widget.attrs.update({'class': 'd-none'}) self.fields['parent'].label = '' self.fields['parent'].required = False class Meta: model = Comment model2 = Article fields = ('content', 'parent') widgets = { 'content': forms.Textarea( attrs={ 'class': 'form-control', 'style': 'width: 98%; margin: auto; padding: 5px; align-items: center;', 'rows': 10, }), } def save(self, *args, **kwargs): Comment.objects.rebuild() return super(NewCommentForm, self).save(*args, **kwargs)
class DocumentForm(AskForm): file_data = forms.FileField(required=False) thread_category = TreeNodeChoiceField(queryset=ThreadCategory.objects.none(), required=False) allow_external_access = forms.BooleanField(required=False) def clean(self): try: _file = self.cleaned_data["file_data"] except KeyError: raise forms.ValidationError(_("Selected file is empty. Please choose another one.")) file_name = _file.name if _file else None if file_name: # change length of file_name by Thread title max_length file_name = file_name[:Thread._meta.get_field_by_name("title")[0].max_length] self.cleaned_data.setdefault("title", file_name) if "title" in self.errors: del self.errors["title"] self.cleaned_data.setdefault("text", "") if "text" in self.errors: del self.errors["text"] return super(DocumentForm, self).clean() def __init__(self, *args, **kwargs): kwargs["allow_tags"] = False super(DocumentForm, self).__init__(*args, **kwargs) self.fields["thread_category"].queryset = self.node.thread_categories.all() self.fields["text"].required = False
def __init__(self, *args, **kwargs): super(CategoryMoveForm, self).__init__(*args, **kwargs) self.fields['position'] = TreeNodePositionField( choices=( (TreeNodePositionField.LEFT, _(u'predecessor')), (TreeNodePositionField.RIGHT, _(u'successor')), (TreeNodePositionField.FIRST_CHILD, _(u'first child')), (TreeNodePositionField.LAST_CHILD, _(u'latest child')), ), label=_(u'Position of this item is'), required=True, ) print self.instance.node self.fields['target'] = TreeNodeChoiceField( queryset=self._meta.model._tree_manager.filter( node=self.instance.node ).exclude( tree_id=self.instance.tree_id, lft__gte=self.instance.lft, rght__lte=self.instance.rght, ), label=u"of item", )
class CategoryForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Category.objects.all(), required=False) class Meta: model = Category exclude = ('slug', )
class TaskAdminForm(forms.ModelForm): """ Form for Task's Admin. """ parent = TreeNodeChoiceField(label=_('Parent task'), empty_label=_('No parent task'), level_indicator='|--', required=False, queryset=proj_models.Task.objects.all()) # def __init__(self, *args, **kwargs): # super(TaskAdminForm, self).__init__(*args, **kwargs) # self.fields['parent'].widget = RelatedFieldWidgetWrapper( # self.fields['parent'].widget, # proj_models.Task.parent.field.remote_field, # self.admin_site) def clean_parent(self): """ Check if task parent is not selfish. """ data = self.cleaned_data['parent'] if data == self.instance: raise forms.ValidationError( _('A task cannot be parent of itself.'), code='self_parenting') return data class Meta: """ TaskAdminForm's Meta. """ model = proj_models.Task fields = forms.ALL_FIELDS widgets = { 'description': MiniAdminTextarea, }
class CommentForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Comment.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # for visible in self.visible_fields(): # visible.field.widget.attrs['class'] = 'form-control' self.fields['parent'].widget.attrs.update({'class': 'd-none'}) self.fields['parent'].label = '' self.fields['parent'].required = False self.fields['text'].widget.attrs.update({'class': 'form-control'}) class Meta: model = Comment fields = ['text'] # widgets = { # 'name': forms.TextInput(attrs={'class': 'col-sm-12'}), # 'email': forms.TextInput(attrs={'class': 'col-sm-12'}), # 'content': forms.Textarea(attrs={'class': 'form-control'}), # } def save(self, *args, **kwargs): Comment.objects.rebuild() return super(CommentForm, self).save(*args, **kwargs)
class AbstractCostForm(forms.ModelForm): to_account = TreeNodeChoiceField(queryset=Account.objects.all(), to_field_name='uuid') class Meta: model = RecurringCost fields = [] def __init__(self, *args, **kwargs): kwargs.setdefault('initial', {}) instance = kwargs.get('instance') if instance: kwargs['initial'].update(to_account=instance.to_account.uuid) super(AbstractCostForm, self).__init__(*args, **kwargs) @transaction.atomic() def save(self, commit=True): creating = not bool(self.instance.pk) recurring_cost = super(AbstractCostForm, self).save(commit) if creating: # TODO: Make configurable housemate_accounts = Account.objects.get( name='Housemate Income').get_children() for housemate_account in housemate_accounts: RecurringCostSplit.objects.create( recurring_cost=recurring_cost, from_account=housemate_account, ) return recurring_cost
class CategoryForm(CategoryFormBase): parent = TreeNodeChoiceField( label="Parent category", queryset=Category.objects.all(), initial=Category.objects.get(name="Root"), empty_label=None, ) class Meta: fields = CategoryFormBase.Meta.fields + [ 'parent', ] fieldsets = (('Basic', { 'fields': ( 'parent', 'name', 'description', 'css_class', 'is_closed', 'require_threads_approval', 'require_replies_approval', 'require_edits_approval', 'prune_started_after', 'prune_replied_after', 'archive_pruned_in', ) }), )
def area_access(request): """ Presents a page that displays audit records for all areas. """ now = timezone.now().astimezone() today = now.strftime('%m/%d/%Y') yesterday = (now - timedelta(days=1)).strftime('%m/%d/%Y') area_id = '' dictionary = { 'today': reverse('area_access') + '?' + urlencode({'start': today, 'end': today}), 'yesterday': reverse('area_access') + '?' + urlencode({'start': yesterday, 'end': yesterday}), } try: start, end = parse_start_and_end_date(request.GET['start'], request.GET['end']) area_id = request.GET.get('area') dictionary['start'] = start dictionary['end'] = end area_access_records = AreaAccessRecord.objects.filter(start__gte=start, start__lt=end, staff_charge=None) if area_id: area_id = int(area_id) filter_areas = Area.objects.get(pk=area_id).get_descendants(include_self=True) area_access_records = area_access_records.filter(area__in=filter_areas) dictionary['area_id'] = area_id area_access_records = area_access_records.order_by('area__name') area_access_records.query.add_ordering(F('end').desc(nulls_first=True)) area_access_records.query.add_ordering(F('start').desc()) dictionary['access_records'] = area_access_records except: pass dictionary['area_select_field'] = TreeNodeChoiceField(Area.objects.filter(area_children_set__isnull=True).only('name'), empty_label="All").widget.render('area', area_id) return render(request, 'area_access/area_access.html', dictionary)
def __init__(self, *args, **kwargs): app = kwargs.pop('app', '') self.screenshots = Screenshot.objects.all( ) if not app else app.screenshots.all() categories = Category.objects.filter( screenshots__in=self.screenshots).distinct() tags = Tag.objects.filter(screenshot__in=self.screenshots).distinct() #years = [[d.year, d.year] for d in self.screenshots.dates('when_created', 'year', order='DESC').distinct()] platforms = Platform.objects.filter( screenshots__in=self.screenshots).distinct() super().__init__(*args, **kwargs) self.fields['platforms'] = TreeNodeChoiceField( label=_('Platforms'), queryset=platforms, required=False, widget=forms.RadioSelect, level_indicator='---', empty_label=None) self.fields['categories'] = forms.ModelChoiceField( label=_('Categories'), queryset=categories, widget=forms.RadioSelect, required=False, empty_label=None) self.fields['tags'] = forms.ModelChoiceField(label=_('Tags'), queryset=tags, widget=forms.RadioSelect, required=False, empty_label=None) """
class CategoryAdminForm(forms.ModelForm): """ Form for Category's Admin. """ parent = TreeNodeChoiceField(label=_('Parent category'), level_indicator='|--', required=False, empty_label=_('No parent category'), queryset=Category.objects.all()) def __init__(self, *args, **kwargs): super(CategoryAdminForm, self).__init__(*args, **kwargs) rel = ManyToOneRel(Category._meta.get_field('tree_id'), Category, 'id') self.fields['parent'].widget = RelatedFieldWidgetWrapper( self.fields['parent'].widget, rel, self.admin_site) def clean_parent(self): """ Check if category parent is not selfish. """ data = self.cleaned_data['parent'] if data == self.instance: raise forms.ValidationError( _('A category cannot be parent of itself.')) return data class Meta: """ CategoryAdminForm's Meta. """ model = Category fields = forms.ALL_FIELDS
class UserMoveChildSelectUserForm(forms.Form): parent = TreeNodeChoiceField(label="Текущий вышестоящий агент", queryset=MyUser.objects.none()) def __init__(self, to_user_qs, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent'].queryset = to_user_qs
class CreateCommentForm(forms.ModelForm): """ Form used bu create comment mutation """ class Meta: model = Comment fields = ( 'message', 'content', 'parent', ) content = forms.ModelChoiceField(queryset=Book.objects.all()) parent = TreeNodeChoiceField(queryset=Comment.objects.all()) def save(self, commit: bool = True) -> Comment: comment = Comment( message=self.instance.message, content=self.instance.content, parent=self.instance.parent, ) comment.save() return comment
class NavigationItemAdminItemForm(forms.ModelForm): parent = TreeNodeChoiceField( NavigationItem.objects.all().order_by('id'), required=False) class Meta: widgets = { 'meta_description': forms.Textarea(attrs={'maxlength':156,}), 'object_id': forms.Select(attrs={ 'class':'selector', }), 'content_type': CustomSelectWidget(attrs={ 'class':'selector', }), } def __init__(self, *args, **kwargs): super(NavigationItemAdminItemForm, self).__init__(*args, **kwargs) if self.instance.id is not None: self.fields['parent'].queryset = NavigationItem.objects.filter( position__id=self.instance.position.id ).exclude( id__in=[self.instance.id]+[item.id for item in self.instance.get_descendants()] ).order_by('id') obj = ContentType.objects.get_for_id(self.instance.content_type.id) choices = [ ( x.id, x.title_name()) for x in obj.model_class().get_items_navigation()] self.fields['object_id'].widget.choices = choices