2

I have a listview that I access in a pretty bog standard way to return all metaobjects.

#url 
url(r'^metaobject/$', MetaObjectList.as_view(),name='metaobject_list'),

#ListView
class MetaObjectList(ListView):
    model = MetaObject

I've recently added a search form that I want to scan my objects (I've got about 5 fields but I've simplified the example). What I'd like to do is re-use my MetaObjectList class view with my specific subset. I am guessing I need to override the get_queryset method but I'm not clear in how I get the queryset from my FormView into the listview. I mucked around a bit with calling the as_view() in the formveiw's form_valid function with additional parameters but couldn't get it to work and it seemed hacky anyway.

class SearchView(FormView):
    template_name = 'heavy/search.html'
    form_class = SearchForm

    #success_url = '/thanks/'

    def form_valid(self, form):
        #build a queryset based on form
        searchval=form.cleaned_data['search']
        list = MetaObject.objects.filter(val=search)
        #where to from here?

I also looked at trying to post the data from the form view over to the listview but that seemed like I'd need to re-write the form logic into the listview.

I'm on python 3.x and django 1.11.

1

1 Answer 1

2

I found what I feel is more elegant than the comment on the question:

My form valid now points to the list object's as_view method and passes the request and the queryset I want

def form_valid(self, form):
    #build a queryset based on form
    searchval=form.cleaned_data['search']
    list = MetaObject.objects.filter(val=search)
    return MetaObjectList.as_view()(self.request,list)

This hits the ListView as a post which I use to alter the queryset

class MetaObjectList(ListView):
    model = MetaObject

    queryset = MetaObject.objects.prefetch_related('object_type','domain')

    def post(self, request, *args, **kwargs):
        self.queryset = args[0]
        return self.get(request, *args, **kwargs)

The only obvious change is using kwargs to make it a bit clearer. Otherwise this seems to work well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.