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.
- Open temporary file stream with authorization.
- Write file in stream.
- Close.
When you treat model with file. - Send file info to model that has file attributes.
- 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.
2 comments:
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
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.
Post a Comment