python - Initial (default) value on Django ChoiceFilter select box -
i trying set initial, default value on select box created djangofilter choicefilter (more info here). code seems pretty simple:
class myfilter(filterset): choices = ( ('', 'any'), ('closed', 'closed'), ('new', 'new'), ) my_select_box = choicefilter(choices=choices, initial='new') class meta: model = mymodel fields = ('my_select_box') def __init__(self, *args, **kwargs): super(myfilter, self).__init__(*args, **kwargs) self.form.helper = formhelper() self.form.helper.form_method = 'get' self.form.helper.add_input(submit('submit', 'search')) self.form.helper.form_class = 'form-inline' self.form.helper.field_class = 'm-r m-b-sm' self.form.helper.label_class = 'm-r'
on views.py:
class myview(baselistview): content_template = "template.html" model = mymodel filter_class = myfilter table_class = mytable class baselistview(baseview, multipleobjectmixin, singletablemixin): table_class = none filter_class = none queryset = none list = none dictionary = {} def get_context_data(self, **kwargs): if self.list not none: self.object_list = self.list else: if self.queryset none: self.queryset = self.get_queryset() self.object_list = self.queryset if self.filter_class not none: filter = self.filter_class(self.request.get, queryset=self.object_list) table = self.table_class(filter.qs) # filter.form.fields['my_select_box'].default = 'new' # filter.form.initial['my_select_box'] = 'new' ids = json.dumps(list(filter.qs.values_list('id', flat=true))) else: filter = "" table = self.table_class(self.object_list) ids = [obj['id'] obj in self.object_list] if self.object_list list else none requestconfig(self.request, paginate={"per_page": 10}).configure(table) kwargs['content'] = render_to_string(self.content_template, context_instance=requestcontext(self.request), dictionary=dict( {'filter': filter, 'object_list': self.object_list, 'ids_list': ids, 'table': table}.items() + self.dictionary.items())) context = super(baselistview, self).get_context_data(**kwargs) return context
on template.html:
<div class="panel-body"> <section class="panel panel-default"> <header class="panel-heading font-bold"> filter </header> <div class="panel-body"> {% crispy filter.form %} </div> </section> {% render_table table %} </div>
on template side can see debugger form.my_select_box.initial set 'new'. well, not working (instead of 'new'
trying integers). if change choices
this:
choices = ( ('any', 'any'), ('closed', 'closed'), ('', 'new'), )
it seems work - don't have value "new" selection, makes things rough later - can of course swap ''
value become 'new'
, , 'any'
become ''
on backend in views.py editing request.get (not pretty solution though), after page refresh if used new, see results new, selections displays any (and opposite).
i believe solution can achieved on server side (i don't want js)?
Comments
Post a Comment