开发者

Django POST/GET exercise

I'm trying to practice some django basics by implementing my own sortable table in Django and I've run into a couple of snags.

Here's the code that I'm working with in my view:

def __table_view_helper__(request):
    if not request.session.__contains开发者_如何学Go__('filters'):
        filters = {'filterA':'',
                   'filterB':'',
                   'filterC':''}
        request.session['filters'] = filters
    if not request.session.__contains__('headers'):
        headers = {'sortA':'asc',
           'sortB':'des',
           'sortC':'asc',
           'sortD':'asc'}
        request.session['headers'] = headers

def table_view(request):
    __table_view_helper__(request)
    records = Record.objects.all()
    nums = list(set(records.values_list('fieldA','fieldA')))
    nums.sort()
    if request.method == 'POST':
        filter = FilterForm(nums,request.POST)
        if filter.is_valid():
            fieldA =  filter.cleaned_data['fieldA']
            fieldB = filter.cleaned_data['fieldB']
            fieldC = filter.cleaned_data['fieldC']
            filters = request.session['filters']
            filters['fieldA'] = fieldA
            filters['fieldB'] = fieldB
            filters['fieldC'] = fieldC
            request.session['filters'] = filters
    else:
        filter = FilterForm(nums)
        filters = request.session['filters']
        filter.fields['fieldA'].initial = filters['fieldA']
        filter.fields['fieldB'].initial = filters['fieldB']
        filter.fields['fieldC'].initial = filters['fieldC']
    if filters['fieldA']:
        records = records.filter(fieldA=filters['fieldA'])
    if filters['fieldB']:
        records = records.filter(fieldB__in=filters['fieldB'])
    if filters['fieldC']:
        records = records.filter(fieldC=filters['fieldC'])
    sort = request.GET.get('sort')
    if sort is not None:
        headers = request.session['headers']
        if headers[sort] == "des":
            records = records.order_by(sort).reverse()
            headers[sort] = "asc"
        else:
            records = records.order_by(sort) 
            headers[sort] = "des"
        request.session['headers'] = headers
    return render_to_response("secure/table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records,'fform':filter})

I changed a lot of my code to use sessions now. It works fine. Is this a good way to do this you think?


To set the initial values from the view you have to do:

filter.fields['fieldA'].initial = filters['filterA']

To keep user related data persistent through different requests you shouldn't use globals, but sessions!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜