django 简单文件上传
通过模型来处理上传的文件¶
如果想要在 FileField
上的 Model
保存文件,使用 ModelForm
会让这一过程变得简单。当调用 form.save()
时,文件对象将会被保存在对相应 FileField
的 upload_to
参数所指定的地方:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField
def upload_file(request):
if request.method == "POST":
form = ModelFormWithFileField(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect("/success/url/")
else:
form = ModelFormWithFileField()
return render(request, "upload.html", {"form": form})
参考: https://docs.djangoproject.com/zh-hans/4.2/topics/http/file-uploads/
实例使用:
@login_required def upload_book(request): user = request.user if request.method == 'POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) uploaded_by = Account.objects.filter(email=user.email).first() obj.uploaded_by = uploaded_by; obj.save() return redirect('book_list') else: form = BookForm() return render(request, 'book/upload_book.html', { 'upload_form' : form })
model配置
class Book(models.Model): title = models.CharField(max_length=100, null=False, blank=False) author = models.CharField(max_length=100, null=False, blank=False) pdf = models.FileField(upload_to='files', null=False, blank=False) date_uploaded = models.DateTimeField(auto_now_add=True, verbose_name = "date uploaded") uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) # slug = models.SlugField(blank=True, unique=True)
form 配置
from django import forms from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'author', 'pdf')