That's six steps to upload!
I.
Configuration in settings configuration file
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias').replace('\\', '/')#media is the root path for picture upload
2.
Configuring in url routing
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index,name='index'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #If uploading is the only thing, and the file is not meant to be displayed or read, you don't need to add this
3.
Writing in models.py file
class Book(models.Model): name = models.CharField(max_length=32) date1 = models.DateTimeField(auto_now=True,null=True) date2 = models.DateTimeField(auto_now_add=True,null=True) img = models.ImageField(upload_to='img',null=True) #Write upload_to and specify a path afterwards. The files uploaded in the future will be generated directly into the img folder in the medias folder in the configuration file. We don't need to write and read the contents of the files ourselves to write to the local files. django handles this automatically for us
IV.
Writing in view function, upload a picture:
def index(request): if request.method == 'POST': print(request.POST) username = request.POST.get('username') print('files',request.FILES) file_obj = request.FILES.get('file') models.Book.objects.create( name=username, img=file_obj, ) #The files are automatically uploaded to our configured img folder return render(request,'index.html')
V.
Update uploaded files (Note that only the path to the file saved in that field in the database will be updated, but previously uploaded files will not be automatically deleted, requiring us to write our own logic to delete previously uploaded errors or files that need to be overwritten).Also, if the uploaded file name is the same, then you will find that the file name behind the path of this field in the database has a random and messy string, because the uploaded file name conflicts. To resolve this conflict, django changed your file name.)
obj = models.Book.objects.get(name='chao2') obj.img=file_obj obj.save() #The following update method cannot update the saved file path correctly unless we manually stitch the file path ourselves and then img=path to update the update models.Book.objects.filter(name='chao2').update(img=file_obj)
6.
View files that have been uploaded (you will need to use our configuration above in the settings configuration file and url)
Writing view.py view function:
def index(request): objs = models.Book.objects.all() return render(request,'index.html',{'objs':objs})
Writing in index.html file:
<div> {% for obj in objs %} <img src="/media/{{ obj.img }}" alt=""> {% endfor %} </div>
<div> {% for obj in objs %} <img src="/media/{{ obj.img }}" alt=""> <!--<img src="/media/{{ obj.img.name }}" alt="">--> {% endfor %} </div>
download
In practical projects, download functions are often needed, such as importing excel, pdf or file download. Of course, you can use web services to build your own resource server for download, such as nginx. Here we mainly introduce file download in django.
Here are three simple ways to write Django download files, and then use the third way to complete an advanced file download
The index.html is as follows
<div> <a href="{% url 'download' %}">File Download</a> </div>
The contents of the urls.py file are as follows:
urlpatterns = [ url(r'^index/', views.index,name='index'), url(r'^download/', views.download,name='download'), ]
The view view function is written in three ways:
Mode 1:
from django.shortcuts import HttpResponse def download(request): file = open('crm/models.py', 'rb') #Open the specified file response = HttpResponse(file) #Give file handle to HttpResponse object response['Content-Type'] = 'application/octet-stream' #Set the header to tell the browser that this is a file response['Content-Disposition'] = 'attachment;filename="models.py"' #This is a simple description of the file. Note that the writing is the fixed one return response
Note: HttpResponse uses the iterator object directly, stores the contents of the iterator object in a city string, returns it to the client, and frees up memory.This can be seen as a time-consuming and memory-consuming process when the file gets larger.Streaming HttpResponse streams file content, which can be used for large amounts of data
Mode 2:
from django.http import StreamingHttpResponse # def download(request): file=open('crm/models.py','rb') response =StreamingHttpResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="models.py"' return response
Mode 3:
from django.http import FileResponse def download(request): file=open('crm/models.py','rb') response =FileResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="models.py"' return response
Three
Three types of http response objects are described on the django website.Entry: https://docs.djangoproject.com/en/1.11/ref/request-response/
FileResponse is recommended, as you can see from the source that FileResponse is a subclass of StreamingHttpResponse and uses iterators internally for data streaming.