2

I'm new using django. I've to upload a file and fot this I'm following the instructions present in official documentation: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs
my index.htlm

    <form action="upload_file" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        <input type="file" name="upfile" size="30">
        <input type="submit" name="upfile" value= " Upload ">
    </form> 

my views.py:

def handle_uploaded_file(f):
    destination = open('/my_path_to_tmp/tmp_files/input_file', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    if ( f.file_name.endswith("sdf") ):
        return "sdf"
    elif ( f.file_name.endswith("smi") ):
        return "smi"

def upload_file(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file_type = handle_uploaded_file(request.FILES['upfile'])
            return HttpResponseRedirect('calculate', file_type)
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

my urls.py

urlpatterns = patterns('myapp.views',
    (r'^upload_file$', 'upload_file'),   
    (r'calculate/$', 'calculation'),
)

Really I don't know what I'm doing wrong here but it seems that the condition

if request.method == "POST":

in views.py fails. Even if the method="POST" to the html form.

Anybody has an idea?
Thank you so much!

2 Answers 2

1

Are you sure that your form action is correct?

Shouldn't it be something like this instead:

<form action="{% url upload_file %}" enctype="multipart/form-data" method="post">
Sign up to request clarification or add additional context in comments.

4 Comments

Well, I'm not sure. I have no experience with django. If I try to do as you say I obtain the following error: TemplateSyntaxError: Caught NoReverseMatch while rendering: Reverse for 'upload_file' with arguments '()' and keyword arguments '{}' not found.
Yeah, that's just because your url file should look like: urlpatterns = patterns('myapp.views', (r'^upload_file$', 'upload_file' name='upload_file'), (r'calculate/$', 'calculation', name='calculation'), )
OK, thanks. If I modify as fylb says I obtain a "SyntaxError: invalid syntax" in urls.py file on "name="
@green69: Instead of name='calculation' use 'calculation', and same for the other.
0

You could perhaps output the request.method at the beginning of your method, just to be sure... after that, print form._errors.

1 Comment

Thanks to help me fyib. Actually it seems that request.method == "POST" but request.POST is empty. How is that possible?

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.