Simple file upload with Model from templates in django 1.7.

 Django page describes how to upload files with form.

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. 

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.


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

    <form method="post" action="/add/post/" enctype="multipart/form-data">
        {% csrf_token %}
            <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>

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.


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() :
            photo.image_file = request.FILES['file']
            photo.filtered_image_file = request.FILES['file']
            message += 'file uploaded';

    try :
    except :
        return HttpResponse('Error!!!')

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

Run and check your files and admin site.


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

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.