Form - File Upload

 

File Upload:

File upload site development is a very common feature. Here in detail how to achieve file upload function in Django.

Distal HTML code to achieve:

1. In the front end, we need to fill in a formlabel, then the formspecified label enctype="multipart/form-data", otherwise you can not upload files.
2. formAdd a label inputtag, and then specify inputa tag name, and type="file".
Sample code above two steps as follows:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
</form>

The back-end code to achieve:

The main work is to receive back-end file. And then stored files. Way to receive the file with POST way to receive is the same, but is achieved through FILES. Sample code is as follows:

def save_file(file):
    with open('somefile.txt','wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)

def index(request):
    if request.method == 'GET':
        form = MyForm()
        return render(request,'index.html',{'form':form})
    else:
        myfile = request.FILES.get('myfile')
        save_file(myfile)
        return HttpResponse('success')


By the above code request.FILESafter receiving the file, and then written to the specified location. That way you can upload a file up.

Use models to handle file uploads:

In the definition of the model, we can assign fields to store files FileField, this Fieldcan pass a upload_toparameter to specify the file to upload up where. For example, we allow him to save the project filesfolder, then the sample code as follows:

# models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.FileField(upload_to="files")


# views.py
def index(request):
    if request.method == 'GET':
        return render(request,'index.html')
    else:
        title = request.POST.get('title')
        content = request.POST.get('content')
        thumbnail = request.FILES.get('thumbnail')
        article = Article(title=title, content=content, thumbnail=thumbnail)
        article.save()
        return HttpResponse('success')


End call the article.save()method, it will save the file to filesthe following, and path of the file will be stored in the database.

Designated MEDIA_ROOT and MEDIA_URL:

Above we are using the upload_todirectory to upload the file specified. We can also specify MEDIA_ROOT, you do not need FielFieldto specify in upload_to, he will automatically upload files to a MEDIA_ROOTdirectory.

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


Then we can add the access path under MEDIA_ROOT directory urls.py in. Sample code is as follows:

from django.urls import path
from front import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)


If you specify MEDIA_ROOT, and upload_tothen upload the files to MEDIA_ROOTin the upload_tofolder. Sample code is as follows:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.FileField(upload_to="%Y/%m/%d/")

Limit uploaded filename extension:

If you want to limit the expansion of the uploaded file name, then we need to use the form to be limited. We can use the normal Formform, it can also be used ModelFormto read the field directly from the model. Sample code is as follows:

# models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnial = models.FileField(upload_to='%Y/%m/%d/',validators=[validators.FileExtensionValidator(['txt','pdf'])])

# forms.py
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = "__all__"

upload image:

Upload pictures with a normal file upload is the same. Just upload the picture when Django will determine whether the uploaded file is a picture format (except judgment extension, it will determine whether the available picture). If not, it will fail validation. We first define a first included ImageFieldthe model. Sample code is as follows:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.ImageField(upload_to="%Y/%m/%d/")


To verify whether it is qualified as a picture, so we need to use a form to be verified. We use the form directly ModelFormon it. Sample code is as follows:

class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = "__all__"


Note: Use ImageField, you must first install Pillow library: pip install pillow

Guess you like

Origin www.cnblogs.com/ys-python/p/11285995.html