Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to upload a file in Django?

Posted on 2015-02-10
6
Medium Priority
?
282 Views
Last Modified: 2015-02-21
Hello,

I am trying to find a simple way to upload files in Django. I would like to be able to:
-  Store them on the file system
-  or Pass the file to a method

I've tried several tutorials like this one: http://zoia.org/2007/07/29/django-file-upload/

But they didn't help much, they either didn't work at all; or they gave me problems saying the CSRF token was missing (even though I had the {% csrf_token %} in between the form tags <form> </form>).

The other problem I'm having is that I seem to be losing the session when I navigate to the new form...

I tested this theory by inserting this bit of code into the html file

<p> {{ user.is_superuser }} </p>

Open in new window


The above code returns "True" when I login on the index page; but I do not see any output when I navigate to the new form.

I am open to do this in the regular Admin area in Django, or a regular page outside; which can only be accessed by Admins.

Appreciate any help on this!
0
Comment
Question by:Errang Genevre
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 17

Accepted Solution

by:
gelonida earned 2000 total points
ID: 40604171
Do you have the srf middleware enabled in the django settings.py file?

must be in the list of

MIDDLEWARE_CLASSES = (
    ....
    'django.middleware.csrf.CsrfViewMiddleware',
    ....
)

If this is not the problem, could you please show us the code of your django view?
perhaps you don't pass the correct context
0
 

Author Comment

by:Errang Genevre
ID: 40604658
I did have the 'django.middleware.csrf.CsrfViewMiddleware' in my MIDDLEWARE_CLASSES.

This is my view:
def create_quiz_form(request):
    if request.method == 'POST':
        form = UploadQuizData(request.POST, request.FILES)
        if form.is_valid():
            new_file = create_quiz(file = request.FILES['file'])
            new_file.save()

            return HttpResponseRedirect('/')
    else:
        form = UploadQuizData()

    data = {'form': form}
    return render_to_response('create_quiz_form.html', data)

Open in new window


This is my form:
from django import forms

class UploadQuizData(forms.Form):
    file = forms.Field(widget=forms.FileInput)

Open in new window


Its odd; I don't see myself doing anything different from any of the other methods I have.
0
 

Author Comment

by:Errang Genevre
ID: 40607227
Figured out why the session wasn't transferring; I was not returning the 'request' object to the new page.

Still trying to figure out how to do the file upload.
0
[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

 

Author Comment

by:Errang Genevre
ID: 40607257
Ok, I finally got the file upload to work too; I can:
 - Process the data within the file and allow the user to download the file
   - Intermediary step to processing the data; having slight problems passing the request to another method.
 - Store the file in the media folder.

Is there a cleaner way to do this? And also, I am planning to associate each file to a quiz; so would it be more efficient to store it directly on the database; or have the database store a file name, and get the file from the file system?

def create_quiz_form(request):
    if request.method == 'POST':
        form = UploadQuizData(request.POST, request.FILES)
        if form.is_valid():
            response = HttpResponse(content_type='text/plain')
            response["Content-Disposition"]= "attachment; filename=quiz.txt"
            fd = open('%s/%s' % (MEDIA_ROOT, 'THIS_IS_THE_FILE'), 'wb')
            create_quiz(request, request.FILES['file']) # This is not working
            for line in request.FILES['file'].read():
                response.write(line)


            fd.write(request.FILES['file'].name)
            fd.close()

            return response
    else:
        form = UploadQuizData()

    data = {'form': form}
    return render(request, 'create_quiz_form.html', data)

Open in new window


Appreciate any advice on this!
0
 
LVL 17

Expert Comment

by:gelonida
ID: 40623194
aplogies I didn't help you more. I was very busy the last weeks.
I'm a little embarassed that you gave me points for my answer.

Well still quite busy, but here some advice:
You can read a file from a request object only once.

But you could read / write the file from a function if you pass the request object.

I would upload the file to the media directory and save it as a FileField in the data base.


following link might give you some ideas:
https://docs.djangoproject.com/en/1.7/topics/http/file-uploads/

If you use another Django, then change the version number in the link
0
 

Author Comment

by:Errang Genevre
ID: 40623659
>> You can read a file from a request object only once.

Figured that out after 30 mins of trial and error :)

>> aplogies I didn't help you more. I was very busy the last weeks.

That's fine, I was able to figure it out; but if you do have any spare time, could you please help me out with the question below?
http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_28621740.html

I tried using this tutorial: http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/

But I get this error: 'module' object has no attribute 'Manipulator'
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question