Django多个上传图像不起作用

时间:2016-11-07 11:33:31

标签: python django image

我尝试添加多重上传,但我上传的2个或更多图片只能添加一个 添加文件的视图:

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>

我很乐意提供任何帮助

1 个答案:

答案 0 :(得分:1)

您的Post模型是单个图像字段,那么您对其他图像有什么影响?如果您希望每个帖子只有一个或更多图像,则需要在Image上使用外键的不同Post模型,然后使用Formset图像