17. How to work with file upload in django in the current project



hai guy let us see the file/image upload in the BTMS project...


first let us create a app ie., uploader using terminal in the project folder


$python manage.py startapp uploader


setting .py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'login',
    'contacts',
    'uploader',
)




MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'



----------------------





in the app ie., uploader

model.py

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.ImageField("Image", upload_to="images/")    
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload

View.py

from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.
def upload(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)     
        if img.is_valid():
            img.save()
            return HttpResponseRedirect(reverse('imageupload'))
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'upload.html',{'form':img,'images':images})





Create a folder templates and create a file upload.html:



<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>picture</h1>
    <form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %} {{form}}
        <input type="submit" value="Upload" />
    </form>
    {% for img in images %}
        {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
        ({{img.upload_date}})<hr />
    {% endfor %}
</div>


url.py
from django.conf.urls import patterns, include, url
from login.views import hello_page, home
from django.contrib import admin
from uploader.views import upload
admin.autodiscover()
import uploader.views
import contacts.views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'btms.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

   # url(r'^admin/', include(admin.site.urls)),
    url(r'^upload/', 'uploader.views.upload', name='imageupload'),
    url(r'^$', hello_page, name='home'),
    url(r'^home/', home),
    url(r'^view/',contacts.views.ListContactView.as_view(),name='contacts-list',),
    url(r'^new$', contacts.views.CreateContactView.as_view(), name='contacts-new',),
   


)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)






=======


now the output is .....













it is fine ......


No comments:

Post a Comment