views:

278

answers:

1

I'm working with a django form, and I have a choice field. I think the problem may be that the choices are fetched dynamically, and right now there's only one value. I'm getting the TemplateSyntaxError: too many values to unpack. Some of the other posts seem to say that having only one value is a problem, so i adjusted my function that fetches the choices, and changed it so it added to blank options at the beginning, just as a test. However this brought up another error: need more than 0 values to unpack

Not really sure what to do about this, because even if there is only one value, I need it to still execute.

Form:

class UploadFileForm(forms.Form):
    category = forms.ChoiceField(get_category_list())
    file = forms.FileField()

Category Fetch Function:

def get_category_list():
    cats = [(), ()]
    for i in os.listdir(settings.MEDIA_ROOT + '/forms'):
        cats.append(i)
    return cats

Template Section:

<div id='addformdialog' title='Add Form'>
    {{ form.as_p }}
</div>

View:

def fm(request):
    if request.session['SecurityLevel'] != 2:
        return HttpResponse('Access Denied!')

    if request.method == 'POST':
        form = UpoadFileForm(request.POST, request.FILES)
        if form.is_valid():
            destination = open(settings.MEDIA_ROOT + "/forms/" + request.POST['category'] + "/" + request.FILES['file'].name, 'wb+')
            for chunk in request.FILES['file'].chunks():
                destination.write(chunk)
            destination.close()
            form = UploadFileForm()
            return render_to_response('admin/fm.html', {'categories':cats, 'form':form, 'uploadsuccess':True})
    else:
        cats = get_category_list()
        form = UploadFileForm()
        return render_to_response('admin/fm.html', {'categories':cats, 'form':form})
+2  A: 

choices is supposed to be an iterable of 2-tuples. You are only appending a single string, which is causing chaos due to how strings and tuples interact (I'll give you details if you really care). Append 2-tuples instead.

Ignacio Vazquez-Abrams
This didn't seem to make any difference.
The.Anti.9
Did you remember to remove the original bogus elements? Also, you may want to show some more code so we know that you understand what "this" meant.
Ignacio Vazquez-Abrams
Ok, I updated the get_category_list() function here.
The.Anti.9
No, 2-tuples. Those are two 0-tuples. Plus, you're still appending single strings. Remove the initial elements and try `cats.append((i, i))` instead.
Ignacio Vazquez-Abrams
Ah, that worked. Thanks
The.Anti.9
Don't forget to sanitize the filename on the way back to make sure an attacker isn't trying to send you something with `../` in it.
Ignacio Vazquez-Abrams