Django文件上传
在Django中实现文件上传,首先需要在models.py中定义一个模型,包含用于存储上传文件的FileField或ImageField字段。然后在forms.py中创建一个表单,使用FileField或ImageField字段。在views.py中处理上传的文件,并在urls.py中配置相应的URL路径。
以下是一个简单的例子:
models.py:
from django.db import models
class Document(models.Model):
uploaded_file = models.FileField(upload_to='documents/')
forms.py:
from django import forms
from .models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('uploaded_file',)
views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import DocumentForm
from .models import Document
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
upload.html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload file</button>
</form>
urls.py:
from django.urls import path
from .views import upload_file
urlpatterns = [
path('upload/', upload_file, name='upload_file'),
]
确保你的MEDIA\_ROOT和MEDIA\_URL设置在settings.py中正确配置,以便能够访问上传的文件。
评论已关闭