12.17.2014

Simple file upload with Model from templates in django 1.7.

 Django page describes how to upload files with form.
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

But if you want to upload file to model from your template, there is the simple way as follows.


1. Set url patch for POST method. 


urls.py
urlpatterns = patterns('',
    url(r'^add/post/$', 'photo.views.add_post'),
)

2. Model that has file attributes. 

Your model has file attributes.
It can be any fileField including imageField.

model.py

class Photo(models.Model):
    id = models.AutoField(primary_key=True)
    image_file = models.ImageField() #auto uploded MEDIA foler fllowing settings.py
    filtered_image_file = models.ImageField()
    description = models.TextField(max_length=500, blank=True)
.....

3. Make template form with file input.

Don't forget to write enctype="multipart/form-data" in your form tag.
{% csrf_token %} is for Cross site request forgery

template.html
    <form method="post" action="/add/post/" enctype="multipart/form-data">
        {% csrf_token %}
        <ul>
            <li><label for="description">Description</label></li>
            <li><input type="file" name="file" /></li>
            <li><textarea id="description" name="description"></textarea></li>
            <li><input type="submit" value="Finish" name="submit" /></li>
        </ul>
    </form>
       

   
It looks like




4. File controller for POST method.

view.py will manage POST method from template.
File object will go into request.FILES if you write enctype="multipart/form-data" in your form tag.
And you are able to get the file object through request.FILES['_FILENAME_']

Process of file control is very similar with other languages as C, JAVA.
  1. Open temporary file stream with authorization.
  2. Write file in stream. 
  3. Close.

    When you treat model with file.
  4. Send file info to model that has file attributes. 
  5. Save model.

views.py

def add_post(request):
    message = 'done. '
    if request.method == 'POST' :
         photo = Photo()

        #file upload
        if 'file' in request.FILES :
            file = request.FILES['file']
            filename = file._name

            fp = open( '%s/%s' % (/filefolder/, filename), 'wb')
            for chunk in file.chunks() :
                fp.write(chunk)
            fp.close()
            photo.image_file = request.FILES['file']
            photo.filtered_image_file = request.FILES['file']
            message += 'file uploaded';

    try :
        photo.save()
    except :
        return HttpResponse('Error!!!')

    return HttpResponse('I wrote %s' % message)



Run and check your files and admin site.



3 comments:

DedicatedHosting4u said...

What an exquisite post you have got written! It would come back to nice facilitate of the beginners like me! this can be terribly clear, precise and descriptive really! thanks most Mr.Author. Keep writing for us like this.:)

Fully dedicated

sheela rajesh said...

I am very proud to read such an informative blog. i Will follow your updates in future so, please add more and more ideas.
Python Training in Chennai
Python Training in Velachery
Big data training in chennai
JAVA Training in Chennai
SEO training in chennai
Python Training in Chennai
Python Training in Anna Nagar

greatrockdev said...

A fascinating discussion is definitely worth comment. I do believe that you ought to write more on this topic, it might not be a taboo matter but generally people don't talk about such subjects. To the next! Cheers!!
Click here to getMoreinformation.