我想添加多個上傳,但如果我上傳2個或多個圖像可以與添加文件添加只有一個 觀點:Django的多個上傳圖片不能正常工作
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
try:
f = request.FILES['image']
post = form.save(commit=False)
post.image.save(f.name, f)
post.date = timezone.now()
post.save()
except MultiValueDictKeyError:
post = form.save(commit=False)
post.date = timezone.now()
post.save()
return redirect('home:index')
else:
form = PostForm()
return render(request, 'home/edit_post.html',
{'form': form, 'error_message': 'something error message'})
else:
form = PostForm()
return render(request, 'home/edit_post.html', {'form': form})
和形式,其中我得到的圖像格式:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'image']
,我也試過這樣:
image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
但它並沒有幫助
自己的模型,其中是圖像:
class Post(models.Model):
title = models.CharField()
date = models.DateTimeField(editable=True, null=True)
text = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to='my-images')
is_super = models.IntegerField(default=0)
模板edit_post:
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{% if error_message %}
<p><strong style="margin-left: 35%; color: red">{{ error_message }}</strong></p>
{% endif %}
<div class="input-group" style="margin-bottom: 10px; margin-left: 38.5%">
<label for="id_title" style="margin-left: 35%">title</label>
<input style="text-align: center" value="{{ form.title.value }}" class="form-control" placeholder="****" id="id_title" name="title" type="text">
</div>
<div class="input-group" style="margin-bottom: 10px; margin-left: 30%">
<label for="id_text" style="margin-left: 42%">text</label>
<textarea style="resize: none; width: 500px; height: 250px" placeholder="***" class="form-control" id="id_text" name="text">{{ form.text.value }}</textarea>
</div>
<div class="input-group" style="margin-bottom: 10px; margin-left: 40%">
{{ form.image }}
</div>
<button type="submit" class="save btn btn-default" style="margin-left: 45.2%; margin-bottom: 20px">edit</button>
</form>
我會很高興的任何幫助
我建議使用Django批次上傳一個
Formset
:https://開頭的github .com/ninapavlich/django-batch-uploader –