tags:

views:

41

answers:

2

So I have a view that does a queryset and returns a simple list:

def cdr(request):
  queryset = CdrView.objects.all()
  return object_list(request, 
                     queryset = queryset,
                     template_name = "reports/cdrview_list.html",
                     paginate_by = 200,
                     page = request.GET.get('page', 1)
                     )

Initially, just to know if it works, I printed all the objects in "object_list" line by line in my template and it's OK but butt ugly. The problem is that my database is constantly growing and is currently at over a million objects. Each object (it's like a phone call) has source and destination among other attributes such as direction (in or out). In my template I call it by doing something like:
{{ call.src }} {{ call.dst }} Since I'm fairly new in Django, I have a question on how I can make a form to be displayed at the top of my page where I an choose to see only calls that have direction as "in" or calls that have a source that starts with "xxxx". Basically filters. Do I do most of the filtering in my views? Or is it in my templates?

Thank you!

+1  A: 

You should do all your business logic in the view, this is the basic idea of working with an MVC (MTV) framework.

beside if you want to use a form for filtering your data, you don't have a choice rather than pass from the view.py

singularity
Ok, yeah, that's what I guessed. Is it possible to do this with generic views specifically object_list? Because the way I used to do this is with RequestContext(request, {xxxx:xxxx}). Should I change to this method?
chiurox
+3  A: 

You filter in your views.py. Since it's a search, we'll use request.REQUEST instead of the normal request.POST.

from forms.py import SearchForm

def cdr(request, form_class=SearchForm):
  queryset = CdrView.objects.all()
  search_form = SearchForm(request.REQUEST)
  if search_form.is_valid():
      search_src = search_form.cleaned_data.get('search_src',None)
      search_dest = search_form.cleaned_data.get('search_dest',None)
      if search_src:
          queryset = queryset.filter(src__icontains=search_src)
      if search_dest:
          queryset = queryset.filter(dest__icontains=search_dest)
  return object_list(request, 
                     queryset = queryset,
                     template_name = "reports/cdrview_list.html",
                     extra_context = {'search_form': search_form },
                     paginate_by = 200,
                     page = request.GET.get('page', 1)
                     )

Then, in forms.py:

from django import forms

class SearchForm(forms.Form):
    search_src = forms.CharField(max_length=20, required=False)
    search_dest = forms.CharField(max_length=20, required=False)

And then in your template:

<form method="get" action="">
<ul>{{ search_form.as_ul }}</ul>
<input type="submit" value="Search" />
</form>
Jordan Reiter