我真的花了最后两天搜索如何在Django 2.0中上传单个文件,在实现它之后,我在前面的“上传多个文件”,文档还不够,我搜索了很多次没有任何结果。 这是我的代码:
models.py:
from django.db import models
class Image(models.Model):
title = models.CharField(max_length=40)
image = models.ImageField()
def __str__(self):
return "{0} => {1}".format(self.id, self.title)
forms.py:
from django import forms
from . import models
class Image_Form(forms.ModelForm):
class Meta:
model = models.Image
fields = "__all__"
widgets = {
"title": forms.TextInput(
attrs={
"required": "True",
"autofocus": "True",
}
),
"image": forms.FileInput(attrs={'multiple': True}),
}
views.py:
from django.shortcuts import render, redirect
from . import models, forms
from django.views.generic.edit import FormView
def index(request):
all_images = models.Image.objects.all()
image_form = forms.Image_Form()
upload_files = Upload_Files()
dico = {
"images_key": all_images,
"form_key": image_form,
"upload_key": upload_files,
}
return render(request, "index.html", dico)
def media_upload(request):
if request.method=="POST":
upload_files = Upload_Files()
upload_files.post(request)
else:
return redirect("index")
class Upload_Files(FormView):
form_class = forms.Image_Form
template_name="index.html"
success_url = '/index/'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('image')
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
的index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>index page</title>
</head>
<body>
<form method="POST" action="{% url 'media_upload' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form_key.title }}</p>
<p>{{ form_key.image }}</p>
<p><input type="submit" value="Save"/></p>
</form>
<hr/><hr/>
{% for i in images_key %}
<p>{{ i.title }}</p>
<p><img src="{{ i.image.url }}"/></p>
<hr/>
{% endfor %}
</body>
</html>
感谢您的帮助。谢谢:) :)
答案 0 :(得分:1)
您的问题出在index.html
上:您应该删除action="{% url 'media_upload' %}"
,即更改
<form method="POST" action="{% url 'media_upload' %}" enctype="multipart/form-data">
到
<form method="POST" enctype="multipart/form-data">